Project

General

Profile

Download (17.1 KB) Statistics
| Branch: | Tag: | Revision:

magiccube / src / main / java / org / distorted / main / RubikSurfaceView.java @ 473611ee

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2019 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Magic Cube.                                                              //
5
//                                                                                               //
6
// Magic Cube is free software: you can redistribute it and/or modify                            //
7
// it under the terms of the GNU General Public License as published by                          //
8
// the Free Software Foundation, either version 2 of the License, or                             //
9
// (at your option) any later version.                                                           //
10
//                                                                                               //
11
// Magic Cube is distributed in the hope that it will be useful,                                 //
12
// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
13
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
14
// GNU General Public License for more details.                                                  //
15
//                                                                                               //
16
// You should have received a copy of the GNU General Public License                             //
17
// along with Magic Cube.  If not, see <http://www.gnu.org/licenses/>.                           //
18
///////////////////////////////////////////////////////////////////////////////////////////////////
19

    
20
package org.distorted.main;
21

    
22
import android.app.ActivityManager;
23
import android.content.Context;
24
import android.content.pm.ConfigurationInfo;
25
import android.opengl.GLSurfaceView;
26
import android.util.AttributeSet;
27
import android.view.MotionEvent;
28

    
29
import org.distorted.library.type.Static2D;
30
import org.distorted.library.type.Static3D;
31
import org.distorted.library.type.Static4D;
32
import org.distorted.objects.RubikObject;
33
import org.distorted.objects.RubikObjectMovement;
34
import org.distorted.states.RubikState;
35
import org.distorted.states.RubikStateSolver;
36
import org.distorted.states.RubikStateSolving;
37

    
38
///////////////////////////////////////////////////////////////////////////////////////////////////
39

    
40
public class RubikSurfaceView extends GLSurfaceView
41
{
42
    public static final int MODE_ROTATE  = 0;
43
    public static final int MODE_DRAG    = 1;
44
    public static final int MODE_REPLACE = 2;
45

    
46
    // Moving the finger from the middle of the vertical screen to the right edge will rotate a
47
    // given face by SWIPING_SENSITIVITY/2 degrees.
48
    private final static int SWIPING_SENSITIVITY  = 240;
49
    // Moving the finger by 1/15 the distance of min(scrWidth,scrHeight) will start a Rotation.
50
    private final static int ROTATION_SENSITIVITY =  15;
51
    // Every 1/12 the distance of min(scrWidth,scrHeight) the direction of cube rotation will reset.
52
    private final static int DIRECTION_SENSITIVITY=  12;
53

    
54
    // Where did we get this sqrt(3)/2 ? From the (default, i.e. 60 degrees - see InternalOutputSurface!)
55
    // FOV of the projection matrix of the Node onto the Screen.
56
    // Take a look how the CAMERA_POINT is used in onTouchEvent - (x,y) there are expressed in sort of
57
    // 'half-NDC' coordinates i.e. they range from +0.5 to -0.5; thus CAMERA_POINT also needs to be
58
    // in 'half-NDC'. Since in this coordinate system the height of the screen is equal to 1, then the
59
    // Z-distance from the center of the object to the camera is equal to (scrHeight/2)/tan(FOV/2) =
60
    // 0.5/tan(30) = sqrt(3)/2.
61
    // Why is the Z-distance between the camera and the object equal to (scrHeight/2)/tan(FOV/2)?
62
    // Because of the way the View part of the ModelView matrix is constructed in EffectQueueMatrix.send().
63
    private final Static4D CAMERA_POINT = new Static4D(0, 0, (float)Math.sqrt(3)*0.5f, 0);
64

    
65
    private RubikRenderer mRenderer;
66
    private RubikPostRender mPostRender;
67
    private RubikObjectMovement mMovement;
68
    private boolean mDragging, mBeginningRotation, mContinuingRotation;
69
    private int mScreenWidth, mScreenHeight, mScreenMin;
70

    
71
    private float mX, mY;
72
    private float mStartRotX, mStartRotY;
73
    private float mAxisX, mAxisY;
74
    private float mRotationFactor;
75

    
76
    private static Static4D mQuatCurrent    = new Static4D(0,0,0,1);
77
    private static Static4D mQuatAccumulated= new Static4D(-0.25189602f,0.3546389f,0.009657208f,0.90038127f);
78
    private static Static4D mTempCurrent    = new Static4D(0,0,0,1);
79
    private static Static4D mTempAccumulated= new Static4D(0,0,0,1);
80

    
81
///////////////////////////////////////////////////////////////////////////////////////////////////
82

    
83
    void setScreenSize(int width, int height)
84
      {
85
      mScreenWidth = width;
86
      mScreenHeight= height;
87

    
88
      mScreenMin = Math.min(width, height);
89
      }
90

    
91
///////////////////////////////////////////////////////////////////////////////////////////////////
92

    
93
    boolean isVertical()
94
      {
95
      return mScreenHeight>mScreenWidth;
96
      }
97

    
98
///////////////////////////////////////////////////////////////////////////////////////////////////
99

    
100
    RubikRenderer getRenderer()
101
      {
102
      return mRenderer;
103
      }
104

    
105
///////////////////////////////////////////////////////////////////////////////////////////////////
106

    
107
    RubikPostRender getPostRender()
108
      {
109
      return mPostRender;
110
      }
111

    
112
///////////////////////////////////////////////////////////////////////////////////////////////////
113

    
114
    void setQuatAccumulated()
115
      {
116
      mQuatAccumulated.set(mTempAccumulated);
117
      }
118

    
119
///////////////////////////////////////////////////////////////////////////////////////////////////
120

    
121
    void setQuatCurrent()
122
      {
123
      mQuatCurrent.set(mTempCurrent);
124
      }
125

    
126
///////////////////////////////////////////////////////////////////////////////////////////////////
127

    
128
    Static4D getQuatAccumulated()
129
      {
130
      return mQuatAccumulated;
131
      }
132

    
133
///////////////////////////////////////////////////////////////////////////////////////////////////
134

    
135
    Static4D getQuatCurrent()
136
      {
137
      return mQuatCurrent;
138
      }
139

    
140
///////////////////////////////////////////////////////////////////////////////////////////////////
141

    
142
    void setMovement(RubikObjectMovement movement)
143
      {
144
      mMovement = movement;
145
      }
146

    
147
///////////////////////////////////////////////////////////////////////////////////////////////////
148

    
149
    private Static4D quatFromDrag(float dragX, float dragY)
150
      {
151
      float axisX = dragY;  // inverted X and Y - rotation axis is perpendicular to (dragX,dragY)
152
      float axisY = dragX;  // Why not (-dragY, dragX) ? because Y axis is also inverted!
153
      float axisZ = 0;
154
      float axisL = (float)Math.sqrt(axisX*axisX + axisY*axisY + axisZ*axisZ);
155

    
156
      if( axisL>0 )
157
        {
158
        axisX /= axisL;
159
        axisY /= axisL;
160
        axisZ /= axisL;
161

    
162
        float ratio = axisL;
163
        ratio = ratio - (int)ratio;     // the cos() is only valid in (0,Pi)
164

    
165
        float cosA = (float)Math.cos(Math.PI*ratio);
166
        float sinA = (float)Math.sqrt(1-cosA*cosA);
167

    
168
        return new Static4D(axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
169
        }
170

    
171
      return new Static4D(0f, 0f, 0f, 1f);
172
      }
173

    
174
///////////////////////////////////////////////////////////////////////////////////////////////////
175

    
176
    private void setUpDragOrRotate(float x, float y)
177
      {
178
      int mode = RubikState.getMode();
179

    
180
      if( mode==MODE_DRAG )
181
        {
182
        mDragging           = true;
183
        mBeginningRotation  = false;
184
        mContinuingRotation = false;
185
        }
186
      else
187
        {
188
        Static4D touchPoint1 = new Static4D(x, y, 0, 0);
189
        Static4D rotatedTouchPoint1= rotateVectorByInvertedQuat(touchPoint1, mQuatAccumulated);
190
        Static4D rotatedCamera= rotateVectorByInvertedQuat(CAMERA_POINT, mQuatAccumulated);
191

    
192
        if( mMovement!=null && mMovement.faceTouched(rotatedTouchPoint1,rotatedCamera) )
193
          {
194
          mDragging           = false;
195
          mContinuingRotation = false;
196

    
197
          if( mode==MODE_ROTATE )
198
            {
199
            mBeginningRotation= mPostRender.canRotate();
200
            }
201
          else if( mode==MODE_REPLACE )
202
            {
203
            mBeginningRotation= false;
204
            RubikStateSolver solver = (RubikStateSolver) RubikState.SVER.getStateClass();
205
            int cubit = mMovement.getTouchedCubit();
206
            int face  = mMovement.getTouchedFace();
207
            int color = solver.getCurrentColor();
208
            mPostRender.setTextureMap( cubit, face, color );
209
            }
210
          }
211
        else
212
          {
213
          mDragging           = true;
214
          mBeginningRotation  = false;
215
          mContinuingRotation = false;
216
          }
217
        }
218
      }
219

    
220
///////////////////////////////////////////////////////////////////////////////////////////////////
221
// cast the 3D axis we are currently rotating along to the 2D in-screen-surface axis
222

    
223
    private void computeCurrentAxis(Static3D axis)
224
      {
225
      Static4D axis4D = new Static4D(axis.get0(), axis.get1(), axis.get2(), 0);
226
      Static4D result = rotateVectorByQuat(axis4D, mQuatAccumulated);
227

    
228
      mAxisX =result.get0();
229
      mAxisY =result.get1();
230

    
231
      float len = (float)Math.sqrt(mAxisX*mAxisX + mAxisY*mAxisY);
232
      mAxisX /= len;
233
      mAxisY /= len;
234
      }
235

    
236
///////////////////////////////////////////////////////////////////////////////////////////////////
237

    
238
    private float continueRotation(float dx, float dy)
239
      {
240
      float alpha = dx*mAxisX + dy*mAxisY;
241
      float x = dx - alpha*mAxisX;
242
      float y = dy - alpha*mAxisY;
243

    
244
      float len = (float)Math.sqrt(x*x + y*y);
245

    
246
      // we have the length of 1D vector 'angle', now the direction:
247
      float tmp = mAxisY==0 ? -mAxisX*y : mAxisY*x;
248

    
249
      return (tmp>0 ? 1:-1)*len*mRotationFactor;
250
      }
251

    
252
///////////////////////////////////////////////////////////////////////////////////////////////////
253
// return quat1*quat2
254

    
255
    public static Static4D quatMultiply( Static4D quat1, Static4D quat2 )
256
      {
257
      float qx = quat1.get0();
258
      float qy = quat1.get1();
259
      float qz = quat1.get2();
260
      float qw = quat1.get3();
261

    
262
      float rx = quat2.get0();
263
      float ry = quat2.get1();
264
      float rz = quat2.get2();
265
      float rw = quat2.get3();
266

    
267
      float tx = rw*qx - rz*qy + ry*qz + rx*qw;
268
      float ty = rw*qy + rz*qx + ry*qw - rx*qz;
269
      float tz = rw*qz + rz*qw - ry*qx + rx*qy;
270
      float tw = rw*qw - rz*qz - ry*qy - rx*qx;
271

    
272
      return new Static4D(tx,ty,tz,tw);
273
      }
274

    
275
///////////////////////////////////////////////////////////////////////////////////////////////////
276
// rotate 'vector' by quat  ( i.e. return quat*vector*(quat^-1) )
277

    
278
    public static Static4D rotateVectorByQuat(Static4D vector, Static4D quat)
279
      {
280
      float qx = quat.get0();
281
      float qy = quat.get1();
282
      float qz = quat.get2();
283
      float qw = quat.get3();
284

    
285
      Static4D quatInverted= new Static4D(-qx,-qy,-qz,qw);
286
      Static4D tmp = quatMultiply(quat,vector);
287

    
288
      return quatMultiply(tmp,quatInverted);
289
      }
290

    
291
///////////////////////////////////////////////////////////////////////////////////////////////////
292
// rotate 'vector' by quat^(-1)  ( i.e. return (quat^-1)*vector*quat )
293

    
294
    public static Static4D rotateVectorByInvertedQuat(Static4D vector, Static4D quat)
295
      {
296
      float qx = quat.get0();
297
      float qy = quat.get1();
298
      float qz = quat.get2();
299
      float qw = quat.get3();
300

    
301
      Static4D quatInverted= new Static4D(-qx,-qy,-qz,qw);
302
      Static4D tmp = quatMultiply(quatInverted,vector);
303

    
304
      return quatMultiply(tmp,quat);
305
      }
306

    
307
///////////////////////////////////////////////////////////////////////////////////////////////////
308
// PUBLIC API
309
///////////////////////////////////////////////////////////////////////////////////////////////////
310

    
311
    public RubikSurfaceView(Context context, AttributeSet attrs)
312
      {
313
      super(context,attrs);
314

    
315
      if(!isInEditMode())
316
        {
317
        mRenderer   = new RubikRenderer(this);
318
        mPostRender = new RubikPostRender(this);
319

    
320
        final ActivityManager activityManager     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
321
        final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
322
        setEGLContextClientVersion( (configurationInfo.reqGlEsVersion>>16) >= 3 ? 3:2 );
323
        setRenderer(mRenderer);
324
        }
325
      }
326

    
327
///////////////////////////////////////////////////////////////////////////////////////////////////
328

    
329
    @Override
330
    public boolean onTouchEvent(MotionEvent event)
331
      {
332
      int action = event.getAction();
333
      float x = (event.getX() - mScreenWidth*0.5f)/mScreenMin;
334
      float y = (mScreenHeight*0.5f -event.getY())/mScreenMin;
335

    
336
      switch(action)
337
         {
338
         case MotionEvent.ACTION_DOWN: mX = x;
339
                                       mY = y;
340
                                       setUpDragOrRotate(x,y);
341
                                       break;
342
         case MotionEvent.ACTION_MOVE: if( mBeginningRotation )
343
                                         {
344
                                         if( (mX-x)*(mX-x)+(mY-y)*(mY-y) > 1.0f/(ROTATION_SENSITIVITY*ROTATION_SENSITIVITY) )
345
                                           {
346
                                           mStartRotX = x;
347
                                           mStartRotY = y;
348

    
349
                                           Static4D touchPoint2 = new Static4D(x, y, 0, 0);
350
                                           Static4D rotatedTouchPoint2= rotateVectorByInvertedQuat(touchPoint2, mQuatAccumulated);
351

    
352
                                           Static2D res = mMovement.newRotation(rotatedTouchPoint2);
353
                                           RubikObject object = mPostRender.getObject();
354

    
355
                                           int axis = (int)res.get0();
356
                                           float offset = res.get1();
357
                                           computeCurrentAxis( object.getRotationAxis()[axis] );
358
                                           mRotationFactor = object.returnRotationFactor(offset);
359

    
360
                                           object.beginNewRotation( axis, object.returnRowFromOffset(offset) );
361

    
362
                                           if( RubikState.getCurrentState()==RubikState.SOLV )
363
                                             {
364
                                             RubikStateSolving solving = (RubikStateSolving)RubikState.SOLV.getStateClass();
365
                                             solving.startCounting( (RubikActivity)getContext() );
366
                                             }
367

    
368
                                           mBeginningRotation = false;
369
                                           mContinuingRotation= true;
370
                                           }
371
                                         }
372
                                       else if( mContinuingRotation )
373
                                         {
374
                                         float angle = continueRotation(x-mStartRotX,y-mStartRotY);
375
                                         mPostRender.getObject().continueRotation(SWIPING_SENSITIVITY*angle);
376
                                         }
377
                                       else if( mDragging )
378
                                         {
379
                                         mTempCurrent.set(quatFromDrag(mX-x,y-mY));
380
                                         mPostRender.setQuatCurrentOnNextRender();
381

    
382
                                         if( (mX-x)*(mX-x) + (mY-y)*(mY-y) > 1.0f/(DIRECTION_SENSITIVITY*DIRECTION_SENSITIVITY) )
383
                                           {
384
                                           mX = x;
385
                                           mY = y;
386
                                           mTempAccumulated.set(quatMultiply(mQuatCurrent, mQuatAccumulated));
387
                                           mTempCurrent.set(0f, 0f, 0f, 1f);
388
                                           mPostRender.setQuatCurrentOnNextRender();
389
                                           mPostRender.setQuatAccumulatedOnNextRender();
390
                                           }
391
                                         }
392
                                       else
393
                                         {
394
                                         setUpDragOrRotate(x,y);
395
                                         }
396
                                       break;
397
         case MotionEvent.ACTION_UP  : if( mDragging )
398
                                         {
399
                                         mTempAccumulated.set(quatMultiply(mQuatCurrent, mQuatAccumulated));
400
                                         mTempCurrent.set(0f, 0f, 0f, 1f);
401
                                         mPostRender.setQuatCurrentOnNextRender();
402
                                         mPostRender.setQuatAccumulatedOnNextRender();
403
                                         }
404

    
405
                                       if( mContinuingRotation )
406
                                         {
407
                                         mPostRender.finishRotation();
408
                                         }
409
                                       break;
410
         }
411

    
412
      return true;
413
      }
414
}
415

    
(4-4/4)