Project

General

Profile

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

magiccube / src / main / java / org / distorted / main / RubikSurfaceView.java @ f0533889

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.solvers.SolverMain;
35
import org.distorted.states.RubikState;
36
import org.distorted.states.RubikStateSolver;
37
import org.distorted.states.RubikStateSolving;
38

    
39
///////////////////////////////////////////////////////////////////////////////////////////////////
40

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

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

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

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

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

    
74
    private float mX, mY;
75
    private float mStartRotX, mStartRotY;
76
    private float mAxisX, mAxisY;
77
    private float mRotationFactor;
78
    private int mLastCubitColor, mLastCubitFace, mLastCubit;
79
    private int mCurrentAxis, mCurrentRow;
80
    private float mCurrentAngle, mCurrRotSpeed;
81
    private float[] mLastAngles;
82
    private long[] mLastTimestamps;
83
    private int mFirstIndex, mLastIndex;
84

    
85
    private static Static4D mQuatCurrent    = new Static4D(0,0,0,1);
86
    private static Static4D mQuatAccumulated= new Static4D(-0.25189602f,0.3546389f,0.009657208f,0.90038127f);
87
    private static Static4D mTempCurrent    = new Static4D(0,0,0,1);
88
    private static Static4D mTempAccumulated= new Static4D(0,0,0,1);
89

    
90
///////////////////////////////////////////////////////////////////////////////////////////////////
91

    
92
    void setScreenSize(int width, int height)
93
      {
94
      mScreenWidth = width;
95
      mScreenHeight= height;
96

    
97
      mScreenMin = Math.min(width, height);
98
      }
99

    
100
///////////////////////////////////////////////////////////////////////////////////////////////////
101

    
102
    boolean isVertical()
103
      {
104
      return mScreenHeight>mScreenWidth;
105
      }
106

    
107
///////////////////////////////////////////////////////////////////////////////////////////////////
108

    
109
    RubikRenderer getRenderer()
110
      {
111
      return mRenderer;
112
      }
113

    
114
///////////////////////////////////////////////////////////////////////////////////////////////////
115

    
116
    RubikPreRender getPreRender()
117
      {
118
      return mPreRender;
119
      }
120

    
121
///////////////////////////////////////////////////////////////////////////////////////////////////
122

    
123
    void setQuatAccumulated()
124
      {
125
      mQuatAccumulated.set(mTempAccumulated);
126
      }
127

    
128
///////////////////////////////////////////////////////////////////////////////////////////////////
129

    
130
    void setQuatCurrent()
131
      {
132
      mQuatCurrent.set(mTempCurrent);
133
      }
134

    
135
///////////////////////////////////////////////////////////////////////////////////////////////////
136

    
137
    Static4D getQuatAccumulated()
138
      {
139
      return mQuatAccumulated;
140
      }
141

    
142
///////////////////////////////////////////////////////////////////////////////////////////////////
143

    
144
    Static4D getQuatCurrent()
145
      {
146
      return mQuatCurrent;
147
      }
148

    
149
///////////////////////////////////////////////////////////////////////////////////////////////////
150

    
151
    void setMovement(RubikObjectMovement movement)
152
      {
153
      mMovement = movement;
154
      }
155

    
156
///////////////////////////////////////////////////////////////////////////////////////////////////
157

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

    
165
      if( axisL>0 )
166
        {
167
        axisX /= axisL;
168
        axisY /= axisL;
169
        axisZ /= axisL;
170

    
171
        float ratio = axisL;
172
        ratio = ratio - (int)ratio;     // the cos() is only valid in (0,Pi)
173

    
174
        float cosA = (float)Math.cos(Math.PI*ratio);
175
        float sinA = (float)Math.sqrt(1-cosA*cosA);
176

    
177
        return new Static4D(axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
178
        }
179

    
180
      return new Static4D(0f, 0f, 0f, 1f);
181
      }
182

    
183
///////////////////////////////////////////////////////////////////////////////////////////////////
184
// cast the 3D axis we are currently rotating along to the 2D in-screen-surface axis
185

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

    
191
      mAxisX =result.get0();
192
      mAxisY =result.get1();
193

    
194
      float len = (float)Math.sqrt(mAxisX*mAxisX + mAxisY*mAxisY);
195
      mAxisX /= len;
196
      mAxisY /= len;
197
      }
198

    
199
///////////////////////////////////////////////////////////////////////////////////////////////////
200

    
201
    private float continueRotation(float dx, float dy)
202
      {
203
      float alpha = dx*mAxisX + dy*mAxisY;
204
      float x = dx - alpha*mAxisX;
205
      float y = dy - alpha*mAxisY;
206

    
207
      float len = (float)Math.sqrt(x*x + y*y);
208

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

    
212
      return (tmp>0 ? 1:-1)*len*mRotationFactor;
213
      }
214

    
215
///////////////////////////////////////////////////////////////////////////////////////////////////
216
// return quat1*quat2
217

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

    
225
      float rx = quat2.get0();
226
      float ry = quat2.get1();
227
      float rz = quat2.get2();
228
      float rw = quat2.get3();
229

    
230
      float tx = rw*qx - rz*qy + ry*qz + rx*qw;
231
      float ty = rw*qy + rz*qx + ry*qw - rx*qz;
232
      float tz = rw*qz + rz*qw - ry*qx + rx*qy;
233
      float tw = rw*qw - rz*qz - ry*qy - rx*qx;
234

    
235
      return new Static4D(tx,ty,tz,tw);
236
      }
237

    
238
///////////////////////////////////////////////////////////////////////////////////////////////////
239
// rotate 'vector' by quat  ( i.e. return quat*vector*(quat^-1) )
240

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

    
248
      Static4D quatInverted= new Static4D(-qx,-qy,-qz,qw);
249
      Static4D tmp = quatMultiply(quat,vector);
250

    
251
      return quatMultiply(tmp,quatInverted);
252
      }
253

    
254
///////////////////////////////////////////////////////////////////////////////////////////////////
255
// rotate 'vector' by quat^(-1)  ( i.e. return (quat^-1)*vector*quat )
256

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

    
264
      Static4D quatInverted= new Static4D(-qx,-qy,-qz,qw);
265
      Static4D tmp = quatMultiply(quatInverted,vector);
266

    
267
      return quatMultiply(tmp,quat);
268
      }
269

    
270
///////////////////////////////////////////////////////////////////////////////////////////////////
271

    
272
    private void addSpeedProbe(float angle)
273
      {
274
      long currTime = System.currentTimeMillis();
275
      boolean theSame = mLastIndex==mFirstIndex;
276

    
277
      mLastIndex++;
278
      if( mLastIndex>=NUM_SPEED_PROBES ) mLastIndex=0;
279

    
280
      mLastTimestamps[mLastIndex] = currTime;
281
      mLastAngles[mLastIndex] = angle;
282

    
283
      if( mLastIndex==mFirstIndex)
284
        {
285
        mFirstIndex++;
286
        if( mFirstIndex>=NUM_SPEED_PROBES ) mFirstIndex=0;
287
        }
288

    
289
      if( theSame )
290
        {
291
        mLastTimestamps[mFirstIndex] = currTime;
292
        mLastAngles[mFirstIndex] = angle;
293
        }
294
      }
295

    
296
///////////////////////////////////////////////////////////////////////////////////////////////////
297

    
298
    private void computeCurrentSpeed()
299
      {
300
      long firstTime = mLastTimestamps[mFirstIndex];
301
      long lastTime  = mLastTimestamps[mLastIndex];
302
      float firstAngle = mLastAngles[mFirstIndex];
303
      float lastAngle  = mLastAngles[mLastIndex];
304

    
305
      long timeDiff = lastTime-firstTime;
306

    
307
      mLastIndex = 0;
308
      mFirstIndex= 0;
309

    
310
      mCurrRotSpeed = timeDiff>0 ? (lastAngle-firstAngle)/timeDiff : 0;
311
      }
312

    
313
///////////////////////////////////////////////////////////////////////////////////////////////////
314

    
315
    private boolean canBeginRotate(float x, float y)
316
      {
317
      return (mX-x)*(mX-x) + (mY-y)*(mY-y) > 1.0f/(ROTATION_SENSITIVITY*ROTATION_SENSITIVITY);
318
      }
319

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

    
322
    private boolean shouldChangeDirection(float x, float y)
323
      {
324
      return (mX-x)*(mX-x) + (mY-y)*(mY-y) > 1.0f/(DIRECTION_SENSITIVITY*DIRECTION_SENSITIVITY);
325
      }
326

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

    
329
    private void setUpDragOrRotate(boolean down, float x, float y)
330
      {
331
      int mode = RubikState.getMode();
332

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

    
345
        if( mMovement!=null && mMovement.faceTouched(rotatedTouchPoint1,rotatedCamera) )
346
          {
347
          mDragging           = false;
348
          mContinuingRotation = false;
349

    
350
          if( mode==MODE_ROTATE )
351
            {
352
            mBeginningRotation= mPreRender.canRotate();
353
            }
354
          else if( mode==MODE_REPLACE )
355
            {
356
            mBeginningRotation= false;
357

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

    
380
///////////////////////////////////////////////////////////////////////////////////////////////////
381

    
382
    private void actionDown(float x, float y)
383
      {
384
      mX = x;
385
      mY = y;
386
      setUpDragOrRotate(true,x,y);
387
      }
388

    
389
///////////////////////////////////////////////////////////////////////////////////////////////////
390

    
391
    private void actionMove(float x, float y)
392
      {
393
      if( mBeginningRotation )
394
        {
395
        if( canBeginRotate(x,y) )
396
          {
397
          mStartRotX = x;
398
          mStartRotY = y;
399

    
400
          Static4D touchPoint2 = new Static4D(x, y, 0, 0);
401
          Static4D rotatedTouchPoint2= rotateVectorByInvertedQuat(touchPoint2, mQuatAccumulated);
402

    
403
          Static2D res = mMovement.newRotation(rotatedTouchPoint2);
404
          RubikObject object = mPreRender.getObject();
405

    
406
          mCurrentAxis = (int)res.get0();
407
          float offset = res.get1();
408
          mCurrentRow = (int)(object.returnMultiplier()*offset);
409
          computeCurrentAxis( object.getRotationAxis()[mCurrentAxis] );
410
          mRotationFactor = object.returnRotationFactor(offset);
411

    
412
          object.beginNewRotation( mCurrentAxis, mCurrentRow );
413

    
414
          if( RubikState.getCurrentState()==RubikState.READ )
415
            {
416
            RubikStateSolving solving = (RubikStateSolving)RubikState.SOLV.getStateClass();
417
            solving.resetElapsed();
418

    
419
            final RubikActivity act = (RubikActivity)getContext();
420

    
421
            act.runOnUiThread(new Runnable()
422
              {
423
              @Override
424
              public void run()
425
                {
426
                RubikState.switchState( act, RubikState.SOLV);
427
                }
428
              });
429
            }
430

    
431
          addSpeedProbe(0.0f);
432

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

    
443
        addSpeedProbe(mCurrentAngle);
444
        }
445
      else if( mDragging )
446
        {
447
        mTempCurrent.set(quatFromDrag(mX-x,y-mY));
448
        mPreRender.setQuatCurrentOnNextRender();
449

    
450
        if( shouldChangeDirection(x,y) )
451
          {
452
          mX = x;
453
          mY = y;
454
          mTempAccumulated.set(quatMultiply(mQuatCurrent, mQuatAccumulated));
455
          mTempCurrent.set(0f, 0f, 0f, 1f);
456
          mPreRender.setQuatCurrentOnNextRender();
457
          mPreRender.setQuatAccumulatedOnNextRender();
458
          }
459
        }
460
      else
461
        {
462
        setUpDragOrRotate(false,x,y);
463
        }
464
      }
465

    
466
///////////////////////////////////////////////////////////////////////////////////////////////////
467

    
468
    private void actionUp()
469
      {
470
      if( mDragging )
471
        {
472
        mTempAccumulated.set(quatMultiply(mQuatCurrent, mQuatAccumulated));
473
        mTempCurrent.set(0f, 0f, 0f, 1f);
474
        mPreRender.setQuatCurrentOnNextRender();
475
        mPreRender.setQuatAccumulatedOnNextRender();
476
        }
477

    
478
      if( mContinuingRotation )
479
        {
480
        computeCurrentSpeed();
481
        int angle = mPreRender.getObject().computeNearestAngle(mCurrentAngle, mCurrRotSpeed);
482
        mPreRender.finishRotation(angle);
483

    
484
        if( RubikState.getCurrentState()==RubikState.SOLV && angle!=0 )
485
          {
486
          RubikStateSolving solving = (RubikStateSolving)RubikState.SOLV.getStateClass();
487
          solving.addMove(mCurrentAxis, mCurrentRow, angle);
488
          }
489
        }
490

    
491
      if( mLastCubitColor>=0 )
492
        {
493
        mPreRender.setTextureMap( mLastCubit, mLastCubitFace, mLastCubitColor );
494
        }
495
      }
496

    
497
///////////////////////////////////////////////////////////////////////////////////////////////////
498
// PUBLIC API
499
///////////////////////////////////////////////////////////////////////////////////////////////////
500

    
501
    public RubikSurfaceView(Context context, AttributeSet attrs)
502
      {
503
      super(context,attrs);
504

    
505
      if(!isInEditMode())
506
        {
507
        mLastCubitColor = -1;
508
        mCurrRotSpeed   = 0.0f;
509

    
510
        mLastAngles = new float[NUM_SPEED_PROBES];
511
        mLastTimestamps = new long[NUM_SPEED_PROBES];
512
        mFirstIndex =0;
513
        mLastIndex  =0;
514

    
515
        mRenderer  = new RubikRenderer(this);
516
        mPreRender = new RubikPreRender(this);
517

    
518
        final ActivityManager activityManager     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
519
        final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
520
        setEGLContextClientVersion( (configurationInfo.reqGlEsVersion>>16) >= 3 ? 3:2 );
521
        setRenderer(mRenderer);
522
        }
523
      }
524

    
525
///////////////////////////////////////////////////////////////////////////////////////////////////
526

    
527
    @Override
528
    public boolean onTouchEvent(MotionEvent event)
529
      {
530
      int action = event.getAction();
531
      float x = (event.getX() - mScreenWidth*0.5f)/mScreenMin;
532
      float y = (mScreenHeight*0.5f -event.getY())/mScreenMin;
533

    
534
      switch(action)
535
         {
536
         case MotionEvent.ACTION_DOWN: actionDown(x,y); break;
537
         case MotionEvent.ACTION_MOVE: actionMove(x,y); break;
538
         case MotionEvent.ACTION_UP  : actionUp()     ; break;
539
         }
540

    
541
      return true;
542
      }
543
}
544

    
(4-4/4)