Project

General

Profile

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

magiccube / src / main / java / org / distorted / main / RubikSurfaceView.java @ 4c864c68

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.util.DisplayMetrics;
28
import android.view.MotionEvent;
29

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

    
40
///////////////////////////////////////////////////////////////////////////////////////////////////
41

    
42
public class RubikSurfaceView extends GLSurfaceView
43
{
44
    private static final int NUM_SPEED_PROBES = 10;
45

    
46
    public static final int MODE_ROTATE  = 0;
47
    public static final int MODE_DRAG    = 1;
48
    public static final int MODE_REPLACE = 2;
49

    
50
    // Moving the finger from the middle of the vertical screen to the right edge will rotate a
51
    // given face by SWIPING_SENSITIVITY/2 degrees.
52
    private final static int SWIPING_SENSITIVITY  = 240;
53
    // Moving the finger by 0.33 of an inch will start a Rotation.
54
    private final static float ROTATION_SENSITIVITY =  0.33f;
55
    // Every 0.33 of an inch the direction of cube drag will reset.
56
    private final static float DIRECTION_SENSITIVITY=  0.33f;
57

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

    
69
    private RubikRenderer mRenderer;
70
    private RubikPreRender mPreRender;
71
    private RubikObjectMovement mMovement;
72
    private boolean mDragging, mBeginningRotation, mContinuingRotation;
73
    private int mScreenWidth, mScreenHeight, mScreenMin;
74

    
75
    private float mX, mY;
76
    private float mStartRotX, mStartRotY;
77
    private float mAxisX, mAxisY;
78
    private float mRotationFactor;
79
    private int mLastCubitColor, mLastCubitFace, mLastCubit;
80
    private int mCurrentAxis, mCurrentRow;
81
    private float mCurrentAngle, mCurrRotSpeed;
82
    private float[] mLastX;
83
    private float[] mLastY;
84
    private long[] mLastT;
85
    private int mFirstIndex, mLastIndex;
86
    private int mDensity;
87

    
88
    private static Static4D mQuatCurrent    = new Static4D(0,0,0,1);
89
    private static Static4D mQuatAccumulated= new Static4D(-0.25189602f,0.3546389f,0.009657208f,0.90038127f);
90
    private static Static4D mTempCurrent    = new Static4D(0,0,0,1);
91
    private static Static4D mTempAccumulated= new Static4D(0,0,0,1);
92

    
93
///////////////////////////////////////////////////////////////////////////////////////////////////
94

    
95
    void setScreenSize(int width, int height)
96
      {
97
      mScreenWidth = width;
98
      mScreenHeight= height;
99

    
100
      mScreenMin = Math.min(width, height);
101
      }
102

    
103
///////////////////////////////////////////////////////////////////////////////////////////////////
104

    
105
    boolean isVertical()
106
      {
107
      return mScreenHeight>mScreenWidth;
108
      }
109

    
110
///////////////////////////////////////////////////////////////////////////////////////////////////
111

    
112
    RubikRenderer getRenderer()
113
      {
114
      return mRenderer;
115
      }
116

    
117
///////////////////////////////////////////////////////////////////////////////////////////////////
118

    
119
    RubikPreRender getPreRender()
120
      {
121
      return mPreRender;
122
      }
123

    
124
///////////////////////////////////////////////////////////////////////////////////////////////////
125

    
126
    void setQuatAccumulated()
127
      {
128
      mQuatAccumulated.set(mTempAccumulated);
129
      }
130

    
131
///////////////////////////////////////////////////////////////////////////////////////////////////
132

    
133
    void setQuatCurrent()
134
      {
135
      mQuatCurrent.set(mTempCurrent);
136
      }
137

    
138
///////////////////////////////////////////////////////////////////////////////////////////////////
139

    
140
    Static4D getQuatAccumulated()
141
      {
142
      return mQuatAccumulated;
143
      }
144

    
145
///////////////////////////////////////////////////////////////////////////////////////////////////
146

    
147
    Static4D getQuatCurrent()
148
      {
149
      return mQuatCurrent;
150
      }
151

    
152
///////////////////////////////////////////////////////////////////////////////////////////////////
153

    
154
    void setMovement(RubikObjectMovement movement)
155
      {
156
      mMovement = movement;
157
      }
158

    
159
///////////////////////////////////////////////////////////////////////////////////////////////////
160

    
161
    private Static4D quatFromDrag(float dragX, float dragY)
162
      {
163
      float axisX = dragY;  // inverted X and Y - rotation axis is perpendicular to (dragX,dragY)
164
      float axisY = dragX;  // Why not (-dragY, dragX) ? because Y axis is also inverted!
165
      float axisZ = 0;
166
      float axisL = (float)Math.sqrt(axisX*axisX + axisY*axisY + axisZ*axisZ);
167

    
168
      if( axisL>0 )
169
        {
170
        axisX /= axisL;
171
        axisY /= axisL;
172
        axisZ /= axisL;
173

    
174
        float ratio = axisL;
175
        ratio = ratio - (int)ratio;     // the cos() is only valid in (0,Pi)
176

    
177
        float cosA = (float)Math.cos(Math.PI*ratio);
178
        float sinA = (float)Math.sqrt(1-cosA*cosA);
179

    
180
        return new Static4D(axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
181
        }
182

    
183
      return new Static4D(0f, 0f, 0f, 1f);
184
      }
185

    
186
///////////////////////////////////////////////////////////////////////////////////////////////////
187
// cast the 3D axis we are currently rotating along to the 2D in-screen-surface axis
188

    
189
    private void computeCurrentAxis(Static3D axis)
190
      {
191
      Static4D axis4D = new Static4D(axis.get0(), axis.get1(), axis.get2(), 0);
192
      Static4D result = rotateVectorByQuat(axis4D, mQuatAccumulated);
193

    
194
      mAxisX =result.get0();
195
      mAxisY =result.get1();
196

    
197
      float len = (float)Math.sqrt(mAxisX*mAxisX + mAxisY*mAxisY);
198
      mAxisX /= len;
199
      mAxisY /= len;
200
      }
201

    
202
///////////////////////////////////////////////////////////////////////////////////////////////////
203

    
204
    private float continueRotation(float dx, float dy)
205
      {
206
      float alpha = dx*mAxisX + dy*mAxisY;
207
      float x = dx - alpha*mAxisX;
208
      float y = dy - alpha*mAxisY;
209

    
210
      float len = (float)Math.sqrt(x*x + y*y);
211

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

    
215
      return (tmp>0 ? 1:-1)*len*mRotationFactor;
216
      }
217

    
218
///////////////////////////////////////////////////////////////////////////////////////////////////
219
// return quat1*quat2
220

    
221
    public static Static4D quatMultiply( Static4D quat1, Static4D quat2 )
222
      {
223
      float qx = quat1.get0();
224
      float qy = quat1.get1();
225
      float qz = quat1.get2();
226
      float qw = quat1.get3();
227

    
228
      float rx = quat2.get0();
229
      float ry = quat2.get1();
230
      float rz = quat2.get2();
231
      float rw = quat2.get3();
232

    
233
      float tx = rw*qx - rz*qy + ry*qz + rx*qw;
234
      float ty = rw*qy + rz*qx + ry*qw - rx*qz;
235
      float tz = rw*qz + rz*qw - ry*qx + rx*qy;
236
      float tw = rw*qw - rz*qz - ry*qy - rx*qx;
237

    
238
      return new Static4D(tx,ty,tz,tw);
239
      }
240

    
241
///////////////////////////////////////////////////////////////////////////////////////////////////
242
// rotate 'vector' by quat  ( i.e. return quat*vector*(quat^-1) )
243

    
244
    public static Static4D rotateVectorByQuat(Static4D vector, Static4D quat)
245
      {
246
      float qx = quat.get0();
247
      float qy = quat.get1();
248
      float qz = quat.get2();
249
      float qw = quat.get3();
250

    
251
      Static4D quatInverted= new Static4D(-qx,-qy,-qz,qw);
252
      Static4D tmp = quatMultiply(quat,vector);
253

    
254
      return quatMultiply(tmp,quatInverted);
255
      }
256

    
257
///////////////////////////////////////////////////////////////////////////////////////////////////
258
// rotate 'vector' by quat^(-1)  ( i.e. return (quat^-1)*vector*quat )
259

    
260
    public static Static4D rotateVectorByInvertedQuat(Static4D vector, Static4D quat)
261
      {
262
      float qx = quat.get0();
263
      float qy = quat.get1();
264
      float qz = quat.get2();
265
      float qw = quat.get3();
266

    
267
      Static4D quatInverted= new Static4D(-qx,-qy,-qz,qw);
268
      Static4D tmp = quatMultiply(quatInverted,vector);
269

    
270
      return quatMultiply(tmp,quat);
271
      }
272

    
273
///////////////////////////////////////////////////////////////////////////////////////////////////
274

    
275
    private void addSpeedProbe(float x, float y)
276
      {
277
      long currTime = System.currentTimeMillis();
278
      boolean theSame = mLastIndex==mFirstIndex;
279

    
280
      mLastIndex++;
281
      if( mLastIndex>=NUM_SPEED_PROBES ) mLastIndex=0;
282

    
283
      mLastT[mLastIndex] = currTime;
284
      mLastX[mLastIndex] = x;
285
      mLastY[mLastIndex] = y;
286

    
287
      if( mLastIndex==mFirstIndex)
288
        {
289
        mFirstIndex++;
290
        if( mFirstIndex>=NUM_SPEED_PROBES ) mFirstIndex=0;
291
        }
292

    
293
      if( theSame )
294
        {
295
        mLastT[mFirstIndex] = currTime;
296
        mLastX[mFirstIndex] = x;
297
        mLastY[mFirstIndex] = y;
298
        }
299
      }
300

    
301
///////////////////////////////////////////////////////////////////////////////////////////////////
302

    
303
    private void computeCurrentSpeedInInchesPerSecond()
304
      {
305
      long firstTime = mLastT[mFirstIndex];
306
      long lastTime  = mLastT[mLastIndex];
307
      float fX = mLastX[mFirstIndex];
308
      float fY = mLastY[mFirstIndex];
309
      float lX = mLastX[mLastIndex];
310
      float lY = mLastY[mLastIndex];
311

    
312
      long timeDiff = lastTime-firstTime;
313

    
314
      mLastIndex = 0;
315
      mFirstIndex= 0;
316

    
317
      mCurrRotSpeed = timeDiff>0 ? 1000*retFingerDragDistanceInInches(fX,fY,lX,lY)/timeDiff : 0;
318
      }
319

    
320
///////////////////////////////////////////////////////////////////////////////////////////////////
321

    
322
    private float retFingerDragDistanceInInches(float xFrom, float yFrom, float xTo, float yTo)
323
      {
324
      float xDist = mScreenWidth*(xFrom-xTo);
325
      float yDist = mScreenHeight*(yFrom-yTo);
326
      float distInPixels = (float)Math.sqrt(xDist*xDist + yDist*yDist);
327

    
328
      return distInPixels/mDensity;
329
      }
330

    
331
///////////////////////////////////////////////////////////////////////////////////////////////////
332

    
333
    private void setUpDragOrRotate(boolean down, float x, float y)
334
      {
335
      int mode = RubikState.getMode();
336

    
337
      if( mode==MODE_DRAG )
338
        {
339
        mDragging           = true;
340
        mBeginningRotation  = false;
341
        mContinuingRotation = false;
342
        }
343
      else
344
        {
345
        Static4D touchPoint1 = new Static4D(x, y, 0, 0);
346
        Static4D rotatedTouchPoint1= rotateVectorByInvertedQuat(touchPoint1, mQuatAccumulated);
347
        Static4D rotatedCamera= rotateVectorByInvertedQuat(CAMERA_POINT, mQuatAccumulated);
348

    
349
        if( mMovement!=null && mMovement.faceTouched(rotatedTouchPoint1,rotatedCamera) )
350
          {
351
          mDragging           = false;
352
          mContinuingRotation = false;
353

    
354
          if( mode==MODE_ROTATE )
355
            {
356
            mBeginningRotation= mPreRender.canRotate();
357
            }
358
          else if( mode==MODE_REPLACE )
359
            {
360
            mBeginningRotation= false;
361

    
362
            if( down )
363
              {
364
              RubikStateSolver solver = (RubikStateSolver) RubikState.SVER.getStateClass();
365
              mLastCubitFace = mMovement.getTouchedFace();
366
              float[] point = mMovement.getTouchedPoint3D();
367
              int color = solver.getCurrentColor();
368
              RubikObject object = mPreRender.getObject();
369
              mLastCubit = object.getCubit(point);
370
              mPreRender.setTextureMap( mLastCubit, mLastCubitFace, color );
371
              mLastCubitColor = SolverMain.cubitIsLocked(object.getObjectList(), object.getSize(), mLastCubit);
372
              }
373
            }
374
          }
375
        else
376
          {
377
          mDragging           = true;
378
          mBeginningRotation  = false;
379
          mContinuingRotation = false;
380
          }
381
        }
382
      }
383

    
384
///////////////////////////////////////////////////////////////////////////////////////////////////
385

    
386
    private void actionDown(float x, float y)
387
      {
388
      mX = x;
389
      mY = y;
390
      setUpDragOrRotate(true,x,y);
391
      }
392

    
393
///////////////////////////////////////////////////////////////////////////////////////////////////
394

    
395
    private void actionMove(float x, float y)
396
      {
397
      if( mBeginningRotation )
398
        {
399
        if( retFingerDragDistanceInInches(mX,mY,x,y) > ROTATION_SENSITIVITY )
400
          {
401
          mStartRotX = x;
402
          mStartRotY = y;
403

    
404
          Static4D touchPoint2 = new Static4D(x, y, 0, 0);
405
          Static4D rotatedTouchPoint2= rotateVectorByInvertedQuat(touchPoint2, mQuatAccumulated);
406

    
407
          Static2D res = mMovement.newRotation(rotatedTouchPoint2);
408
          RubikObject object = mPreRender.getObject();
409

    
410
          mCurrentAxis = (int)res.get0();
411
          float offset = res.get1();
412
          mCurrentRow = (int)(object.returnMultiplier()*offset);
413
          computeCurrentAxis( object.getRotationAxis()[mCurrentAxis] );
414
          mRotationFactor = object.returnRotationFactor(offset);
415

    
416
          object.beginNewRotation( mCurrentAxis, mCurrentRow );
417

    
418
          if( RubikState.getCurrentState()==RubikState.READ )
419
            {
420
            RubikStateSolving solving = (RubikStateSolving)RubikState.SOLV.getStateClass();
421
            solving.resetElapsed();
422

    
423
            final RubikActivity act = (RubikActivity)getContext();
424

    
425
            act.runOnUiThread(new Runnable()
426
              {
427
              @Override
428
              public void run()
429
                {
430
                RubikState.switchState( act, RubikState.SOLV);
431
                }
432
              });
433
            }
434

    
435
          addSpeedProbe(x,y);
436

    
437
          mBeginningRotation = false;
438
          mContinuingRotation= true;
439
          }
440
        }
441
      else if( mContinuingRotation )
442
        {
443
        float angle = continueRotation(x-mStartRotX,y-mStartRotY);
444
        mCurrentAngle = SWIPING_SENSITIVITY*angle;
445
        mPreRender.getObject().continueRotation(mCurrentAngle);
446

    
447
        addSpeedProbe(x,y);
448
        }
449
      else if( mDragging )
450
        {
451
        mTempCurrent.set(quatFromDrag(mX-x,y-mY));
452
        mPreRender.setQuatCurrentOnNextRender();
453

    
454
        if( retFingerDragDistanceInInches(mX,mY,x,y) > DIRECTION_SENSITIVITY )
455
          {
456
          mX = x;
457
          mY = y;
458
          mTempAccumulated.set(quatMultiply(mQuatCurrent, mQuatAccumulated));
459
          mTempCurrent.set(0f, 0f, 0f, 1f);
460
          mPreRender.setQuatCurrentOnNextRender();
461
          mPreRender.setQuatAccumulatedOnNextRender();
462
          }
463
        }
464
      else
465
        {
466
        setUpDragOrRotate(false,x,y);
467
        }
468
      }
469

    
470
///////////////////////////////////////////////////////////////////////////////////////////////////
471

    
472
    private void actionUp()
473
      {
474
      if( mDragging )
475
        {
476
        mTempAccumulated.set(quatMultiply(mQuatCurrent, mQuatAccumulated));
477
        mTempCurrent.set(0f, 0f, 0f, 1f);
478
        mPreRender.setQuatCurrentOnNextRender();
479
        mPreRender.setQuatAccumulatedOnNextRender();
480
        }
481

    
482
      if( mContinuingRotation )
483
        {
484
        computeCurrentSpeedInInchesPerSecond();
485
        int angle = mPreRender.getObject().computeNearestAngle(mCurrentAngle, mCurrRotSpeed);
486
        mPreRender.finishRotation(angle);
487

    
488
        if( RubikState.getCurrentState()==RubikState.SOLV && angle!=0 )
489
          {
490
          RubikStateSolving solving = (RubikStateSolving)RubikState.SOLV.getStateClass();
491
          solving.addMove(mCurrentAxis, mCurrentRow, angle);
492
          }
493
        }
494

    
495
      if( mLastCubitColor>=0 )
496
        {
497
        mPreRender.setTextureMap( mLastCubit, mLastCubitFace, mLastCubitColor );
498
        }
499
      }
500

    
501
///////////////////////////////////////////////////////////////////////////////////////////////////
502
// PUBLIC API
503
///////////////////////////////////////////////////////////////////////////////////////////////////
504

    
505
    public RubikSurfaceView(Context context, AttributeSet attrs)
506
      {
507
      super(context,attrs);
508

    
509
      if(!isInEditMode())
510
        {
511
        mLastCubitColor = -1;
512
        mCurrRotSpeed   = 0.0f;
513

    
514
        mLastX = new float[NUM_SPEED_PROBES];
515
        mLastY = new float[NUM_SPEED_PROBES];
516
        mLastT = new long[NUM_SPEED_PROBES];
517
        mFirstIndex =0;
518
        mLastIndex  =0;
519

    
520
        mRenderer  = new RubikRenderer(this);
521
        mPreRender = new RubikPreRender(this);
522

    
523
        RubikActivity act = (RubikActivity)context;
524
        DisplayMetrics dm = new DisplayMetrics();
525
        act.getWindowManager().getDefaultDisplay().getMetrics(dm);
526

    
527
        mDensity = dm.densityDpi;
528

    
529
        final ActivityManager activityManager= (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
530

    
531
        if( activityManager!=null )
532
          {
533
          final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
534
          setEGLContextClientVersion( (configurationInfo.reqGlEsVersion>>16) >= 3 ? 3:2 );
535
          setRenderer(mRenderer);
536
          }
537
        }
538
      }
539

    
540
///////////////////////////////////////////////////////////////////////////////////////////////////
541

    
542
    @Override
543
    public boolean onTouchEvent(MotionEvent event)
544
      {
545
      int action = event.getAction();
546
      float x = (event.getX() - mScreenWidth*0.5f)/mScreenMin;
547
      float y = (mScreenHeight*0.5f -event.getY())/mScreenMin;
548

    
549
      switch(action)
550
         {
551
         case MotionEvent.ACTION_DOWN: actionDown(x,y); break;
552
         case MotionEvent.ACTION_MOVE: actionMove(x,y); break;
553
         case MotionEvent.ACTION_UP  : actionUp()     ; break;
554
         }
555

    
556
      return true;
557
      }
558
}
559

    
(4-4/4)