Project

General

Profile

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

magiccube / src / main / java / org / distorted / tutorials / TutorialSurfaceView.java @ b6dcb62b

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2020 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.tutorials;
21

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

    
31
import com.google.firebase.crashlytics.FirebaseCrashlytics;
32

    
33
import org.distorted.library.type.Static2D;
34
import org.distorted.library.type.Static4D;
35
import org.distorted.library.main.QuatHelper;
36

    
37
import org.distorted.objectlib.main.Movement;
38
import org.distorted.objectlib.main.TwistyObject;
39

    
40
import static org.distorted.main.RubikSurfaceView.INVALID_POINTER_ID;
41
import static org.distorted.main.RubikSurfaceView.NUM_SPEED_PROBES;
42
import static org.distorted.main.RubikSurfaceView.ROTATION_SENSITIVITY;
43
import static org.distorted.main.RubikSurfaceView.SWIPING_SENSITIVITY;
44

    
45
///////////////////////////////////////////////////////////////////////////////////////////////////
46

    
47
public class TutorialSurfaceView extends GLSurfaceView
48
{
49
    private final Static4D CAMERA_POINT = new Static4D(0, 0, 0, 0);
50
    private TutorialRenderer mRenderer;
51
    private TutorialPreRender mPreRender;
52
    private Movement mMovement;
53
    private boolean mDragging, mBeginningRotation, mContinuingRotation;
54
    private int mScreenWidth, mScreenHeight, mScreenMin;
55

    
56
    private float mRotAngle, mInitDistance;
57
    private int mPtrID1, mPtrID2;
58
    private float mX, mY;
59
    private float mStartRotX, mStartRotY;
60
    private float mAxisX, mAxisY;
61
    private float mRotationFactor;
62
    private int mCurrentAxis, mCurrentRow;
63
    private float mCurrentAngle, mCurrRotSpeed;
64
    private float[] mLastX;
65
    private float[] mLastY;
66
    private long[] mLastT;
67
    private int mFirstIndex, mLastIndex;
68
    private int mDensity;
69

    
70
    private static final Static4D mQuat= new Static4D(-0.25189602f,0.3546389f,0.009657208f,0.90038127f);
71
    private static final Static4D mTemp= new Static4D(0,0,0,1);
72

    
73
///////////////////////////////////////////////////////////////////////////////////////////////////
74

    
75
    void setScreenSize(int width, int height)
76
      {
77
      mScreenWidth = width;
78
      mScreenHeight= height;
79

    
80
      mScreenMin = Math.min(width, height);
81
      }
82

    
83
///////////////////////////////////////////////////////////////////////////////////////////////////
84

    
85
    boolean isVertical()
86
      {
87
      return mScreenHeight>mScreenWidth;
88
      }
89

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

    
92
    TutorialRenderer getRenderer()
93
      {
94
      return mRenderer;
95
      }
96

    
97
///////////////////////////////////////////////////////////////////////////////////////////////////
98

    
99
    TutorialPreRender getPreRender()
100
      {
101
      return mPreRender;
102
      }
103

    
104
///////////////////////////////////////////////////////////////////////////////////////////////////
105

    
106
    void setQuat()
107
      {
108
      mQuat.set(mTemp);
109
      }
110

    
111
///////////////////////////////////////////////////////////////////////////////////////////////////
112

    
113
    Static4D getQuat()
114
      {
115
      return mQuat;
116
      }
117

    
118
///////////////////////////////////////////////////////////////////////////////////////////////////
119

    
120
    void setMovement(Movement movement)
121
      {
122
      mMovement = movement;
123
      }
124

    
125
///////////////////////////////////////////////////////////////////////////////////////////////////
126
// cast the 3D axis we are currently rotating along (which is already casted to the surface of the
127
// currently touched face AND converted into a 4D vector - fourth 0) to a 2D in-screen-surface axis
128

    
129
    private void computeCurrentAxis(Static4D axis)
130
      {
131
      Static4D result = QuatHelper.rotateVectorByQuat(axis, mQuat);
132

    
133
      mAxisX =result.get0();
134
      mAxisY =result.get1();
135

    
136
      float len = (float)Math.sqrt(mAxisX*mAxisX + mAxisY*mAxisY);
137
      mAxisX /= len;
138
      mAxisY /= len;
139
      }
140

    
141
///////////////////////////////////////////////////////////////////////////////////////////////////
142

    
143
    private void addSpeedProbe(float x, float y)
144
      {
145
      long currTime = System.currentTimeMillis();
146
      boolean theSame = mLastIndex==mFirstIndex;
147

    
148
      mLastIndex++;
149
      if( mLastIndex>=NUM_SPEED_PROBES ) mLastIndex=0;
150

    
151
      mLastT[mLastIndex] = currTime;
152
      mLastX[mLastIndex] = x;
153
      mLastY[mLastIndex] = y;
154

    
155
      if( mLastIndex==mFirstIndex)
156
        {
157
        mFirstIndex++;
158
        if( mFirstIndex>=NUM_SPEED_PROBES ) mFirstIndex=0;
159
        }
160

    
161
      if( theSame )
162
        {
163
        mLastT[mFirstIndex] = currTime;
164
        mLastX[mFirstIndex] = x;
165
        mLastY[mFirstIndex] = y;
166
        }
167
      }
168

    
169
///////////////////////////////////////////////////////////////////////////////////////////////////
170

    
171
    private void computeCurrentSpeedInInchesPerSecond()
172
      {
173
      long firstTime = mLastT[mFirstIndex];
174
      long lastTime  = mLastT[mLastIndex];
175
      float fX = mLastX[mFirstIndex];
176
      float fY = mLastY[mFirstIndex];
177
      float lX = mLastX[mLastIndex];
178
      float lY = mLastY[mLastIndex];
179

    
180
      long timeDiff = lastTime-firstTime;
181

    
182
      mLastIndex = 0;
183
      mFirstIndex= 0;
184

    
185
      mCurrRotSpeed = timeDiff>0 ? 1000*retFingerDragDistanceInInches(fX,fY,lX,lY)/timeDiff : 0;
186
      }
187

    
188
///////////////////////////////////////////////////////////////////////////////////////////////////
189

    
190
    private float retFingerDragDistanceInInches(float xFrom, float yFrom, float xTo, float yTo)
191
      {
192
      float xDist = mScreenWidth*(xFrom-xTo);
193
      float yDist = mScreenHeight*(yFrom-yTo);
194
      float distInPixels = (float)Math.sqrt(xDist*xDist + yDist*yDist);
195

    
196
      return distInPixels/mDensity;
197
      }
198

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

    
201
    private void setUpDragOrRotate(float x, float y)
202
      {
203
      TwistyObject object = mPreRender.getObject();
204
      CAMERA_POINT.set2( object==null ? 1.21f : object.getCameraDist() );
205

    
206
      Static4D touchPoint = new Static4D(x, y, 0, 0);
207
      Static4D rotatedTouchPoint= QuatHelper.rotateVectorByInvertedQuat(touchPoint, mQuat);
208
      Static4D rotatedCamera= QuatHelper.rotateVectorByInvertedQuat(CAMERA_POINT, mQuat);
209

    
210
      if( mMovement!=null && mMovement.faceTouched(rotatedTouchPoint,rotatedCamera,object.getObjectRatio()) )
211
        {
212
        mDragging           = false;
213
        mContinuingRotation = false;
214
        mBeginningRotation= !mPreRender.isTouchBlocked();
215
        }
216
      else
217
        {
218
        final TutorialActivity act = (TutorialActivity)getContext();
219
        boolean locked      = act.isLocked();
220
        mDragging           = !locked;
221
        mContinuingRotation = false;
222
        mBeginningRotation  = false;
223

    
224
        if( !mDragging )
225
          {
226
          TutorialState state = act.getState();
227
          state.reddenLock(act);
228
          }
229
        }
230
      }
231

    
232
///////////////////////////////////////////////////////////////////////////////////////////////////
233

    
234
    private void drag(MotionEvent event, float x, float y)
235
      {
236
      if( mPtrID1!=INVALID_POINTER_ID && mPtrID2!=INVALID_POINTER_ID)
237
        {
238
        int pointer = event.findPointerIndex(mPtrID2);
239
        float pX,pY;
240

    
241
        try
242
          {
243
          pX = event.getX(pointer);
244
          pY = event.getY(pointer);
245
          }
246
        catch(IllegalArgumentException ex)
247
          {
248
          mPtrID1=INVALID_POINTER_ID;
249
          mPtrID2=INVALID_POINTER_ID;
250

    
251
          FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
252
          crashlytics.setCustomKey("DragError", "pointer="+pointer );
253
          crashlytics.recordException(ex);
254

    
255
          return;
256
          }
257

    
258
        float x2 = (pX - mScreenWidth*0.5f)/mScreenMin;
259
        float y2 = (mScreenHeight*0.5f -pY)/mScreenMin;
260

    
261
        float angleNow = getAngle(x,y,x2,y2);
262
        float angleDiff = angleNow-mRotAngle;
263
        float sinA =-(float)Math.sin(angleDiff);
264
        float cosA = (float)Math.cos(angleDiff);
265

    
266
        Static4D dragQuat = QuatHelper.quatMultiply(new Static4D(0,0,sinA,cosA), mQuat);
267
        mTemp.set(dragQuat);
268

    
269
        mRotAngle = angleNow;
270

    
271
        float distNow  = (float)Math.sqrt( (x-x2)*(x-x2) + (y-y2)*(y-y2) );
272
        float distQuot = mInitDistance<0 ? 1.0f : distNow/ mInitDistance;
273
        mInitDistance = distNow;
274

    
275
        TwistyObject object = mPreRender.getObject();
276
        if( object!=null ) object.setObjectRatio(distQuot);
277
        }
278
      else
279
        {
280
        Static4D dragQuat = QuatHelper.quatMultiply(QuatHelper.quatFromDrag(mX-x,y-mY), mQuat);
281
        mTemp.set(dragQuat);
282
        }
283

    
284
      mPreRender.setQuatOnNextRender();
285
      mX = x;
286
      mY = y;
287
      }
288

    
289
///////////////////////////////////////////////////////////////////////////////////////////////////
290

    
291
    private void finishRotation()
292
      {
293
      computeCurrentSpeedInInchesPerSecond();
294
      int angle = mPreRender.getObject().computeNearestAngle(mCurrentAxis,mCurrentAngle, mCurrRotSpeed);
295
      mPreRender.finishRotation(angle);
296

    
297
      if( angle!=0 )
298
        {
299
        final TutorialActivity act = (TutorialActivity)getContext();
300
        TutorialState state = act.getState();
301
        state.addMove(act,mCurrentAxis, mCurrentRow, angle);
302
        }
303

    
304
      mContinuingRotation = false;
305
      mBeginningRotation  = false;
306
      mDragging           = true;
307
      }
308

    
309
///////////////////////////////////////////////////////////////////////////////////////////////////
310

    
311
    private void continueRotation(float x, float y)
312
      {
313
      float dx = x-mStartRotX;
314
      float dy = y-mStartRotY;
315
      float alpha = dx*mAxisX + dy*mAxisY;
316
      float x2 = dx - alpha*mAxisX;
317
      float y2 = dy - alpha*mAxisY;
318

    
319
      float len = (float)Math.sqrt(x2*x2 + y2*y2);
320

    
321
      // we have the length of 1D vector 'angle', now the direction:
322
      float tmp = mAxisY==0 ? -mAxisX*y2 : mAxisY*x2;
323

    
324
      float angle = (tmp>0 ? 1:-1)*len*mRotationFactor;
325
      mCurrentAngle = SWIPING_SENSITIVITY*angle;
326
      mPreRender.getObject().continueRotation(mCurrentAngle);
327

    
328
      addSpeedProbe(x2,y2);
329
      }
330

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

    
333
    private void beginRotation(float x, float y)
334
      {
335
      mStartRotX = x;
336
      mStartRotY = y;
337

    
338
      TwistyObject object = mPreRender.getObject();
339
      int numLayers = object.getNumLayers();
340

    
341
      Static4D touchPoint2 = new Static4D(x, y, 0, 0);
342
      Static4D rotatedTouchPoint2= QuatHelper.rotateVectorByInvertedQuat(touchPoint2, mQuat);
343
      Static2D res = mMovement.newRotation(rotatedTouchPoint2,object.getObjectRatio());
344

    
345
      mCurrentAxis = (int)res.get0();
346
      mCurrentRow  = (int)res.get1();
347

    
348
      computeCurrentAxis( mMovement.getCastedRotAxis(mCurrentAxis) );
349
      mRotationFactor = mMovement.returnRotationFactor(numLayers,mCurrentRow);
350

    
351
      object.beginNewRotation( mCurrentAxis, mCurrentRow );
352

    
353
      addSpeedProbe(x,y);
354

    
355
      mBeginningRotation = false;
356
      mContinuingRotation= true;
357
      }
358

    
359
///////////////////////////////////////////////////////////////////////////////////////////////////
360

    
361
    private float getAngle(float x1, float y1, float x2, float y2)
362
      {
363
      return (float) Math.atan2(y1-y2, x1-x2);
364
      }
365

    
366
///////////////////////////////////////////////////////////////////////////////////////////////////
367

    
368
    private void actionMove(MotionEvent event)
369
      {
370
      int pointer = event.findPointerIndex(mPtrID1 != INVALID_POINTER_ID ? mPtrID1:mPtrID2);
371

    
372
      if( pointer<0 ) return;
373

    
374
      float pX = event.getX(pointer);
375
      float pY = event.getY(pointer);
376

    
377
      float x = (pX - mScreenWidth*0.5f)/mScreenMin;
378
      float y = (mScreenHeight*0.5f -pY)/mScreenMin;
379

    
380
      if( mBeginningRotation )
381
        {
382
        if( retFingerDragDistanceInInches(mX,mY,x,y) > ROTATION_SENSITIVITY )
383
          {
384
          beginRotation(x,y);
385
          }
386
        }
387
      else if( mContinuingRotation )
388
        {
389
        continueRotation(x,y);
390
        }
391
      else if( mDragging )
392
        {
393
        drag(event,x,y);
394
        }
395
      else
396
        {
397
        setUpDragOrRotate(x,y);
398
        }
399
      }
400

    
401
///////////////////////////////////////////////////////////////////////////////////////////////////
402

    
403
    private void actionDown(MotionEvent event)
404
      {
405
      mPtrID1 = event.getPointerId(0);
406

    
407
      float x = event.getX();
408
      float y = event.getY();
409

    
410
      mX = (x - mScreenWidth*0.5f)/mScreenMin;
411
      mY = (mScreenHeight*0.5f -y)/mScreenMin;
412

    
413
      setUpDragOrRotate(mX,mY);
414
      }
415

    
416
///////////////////////////////////////////////////////////////////////////////////////////////////
417

    
418
    private void actionUp(MotionEvent event)
419
      {
420
      mPtrID1 = INVALID_POINTER_ID;
421
      mPtrID2 = INVALID_POINTER_ID;
422

    
423
      if( mContinuingRotation )
424
        {
425
        finishRotation();
426
        }
427
      }
428

    
429
///////////////////////////////////////////////////////////////////////////////////////////////////
430

    
431
    private void actionDown2(MotionEvent event)
432
      {
433
      int index = event.getActionIndex();
434

    
435
      if( mPtrID1==INVALID_POINTER_ID )
436
        {
437
        mPtrID1 = event.getPointerId(index);
438
        float x = event.getX();
439
        float y = event.getY();
440

    
441
        if( mPtrID2 != INVALID_POINTER_ID )
442
          {
443
          int pointer = event.findPointerIndex(mPtrID2);
444

    
445
          try
446
            {
447
            float x2 = event.getX(pointer);
448
            float y2 = event.getY(pointer);
449

    
450
            mRotAngle = getAngle(x,-y,x2,-y2);
451
            mInitDistance = -1;
452
            }
453
          catch(IllegalArgumentException ex)
454
            {
455
            mPtrID1=INVALID_POINTER_ID;
456
            mPtrID2=INVALID_POINTER_ID;
457

    
458
            FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
459
            crashlytics.setCustomKey("DragError", "pointer="+pointer );
460
            crashlytics.recordException(ex);
461

    
462
            return;
463
            }
464
          }
465

    
466
        mX = (x - mScreenWidth*0.5f)/mScreenMin;
467
        mY = (mScreenHeight*0.5f -y)/mScreenMin;
468
        }
469
      else if( mPtrID2==INVALID_POINTER_ID )
470
        {
471
        mPtrID2 = event.getPointerId(index);
472

    
473
        float x = event.getX();
474
        float y = event.getY();
475

    
476
        if( mPtrID2 != INVALID_POINTER_ID )
477
          {
478
          int pointer = event.findPointerIndex(mPtrID2);
479

    
480
          try
481
            {
482
            float x2 = event.getX(pointer);
483
            float y2 = event.getY(pointer);
484

    
485
            mRotAngle = getAngle(x,-y,x2,-y2);
486
            mInitDistance = -1;
487
            }
488
          catch(IllegalArgumentException ex)
489
            {
490
            mPtrID1=INVALID_POINTER_ID;
491
            mPtrID2=INVALID_POINTER_ID;
492

    
493
            FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
494
            crashlytics.setCustomKey("DragError", "pointer="+pointer );
495
            crashlytics.recordException(ex);
496

    
497
            return;
498
            }
499
          }
500

    
501
        if( mBeginningRotation || mContinuingRotation )
502
          {
503
          mX = (x - mScreenWidth*0.5f)/mScreenMin;
504
          mY = (mScreenHeight*0.5f -y)/mScreenMin;
505
          }
506
        }
507

    
508
      if( mBeginningRotation )
509
        {
510
        mContinuingRotation = false;
511
        mBeginningRotation  = false;
512
        mDragging           = true;
513
        }
514
      else if( mContinuingRotation )
515
        {
516
        finishRotation();
517
        }
518
      }
519

    
520
///////////////////////////////////////////////////////////////////////////////////////////////////
521

    
522
    private void actionUp2(MotionEvent event)
523
      {
524
      int index = event.getActionIndex();
525

    
526
      if( index==event.findPointerIndex(mPtrID1) )
527
        {
528
        mPtrID1 = INVALID_POINTER_ID;
529
        int pointer = event.findPointerIndex(mPtrID2);
530

    
531
        if( pointer>=0 )
532
          {
533
          float x1 = event.getX(pointer);
534
          float y1 = event.getY(pointer);
535

    
536
          mX = (x1 - mScreenWidth*0.5f)/mScreenMin;
537
          mY = (mScreenHeight*0.5f -y1)/mScreenMin;
538
          }
539
        }
540
      else if( index==event.findPointerIndex(mPtrID2) )
541
        {
542
        mPtrID2 = INVALID_POINTER_ID;
543
        }
544
      }
545

    
546
///////////////////////////////////////////////////////////////////////////////////////////////////
547

    
548
    void initialize()
549
      {
550
      mPtrID1 = INVALID_POINTER_ID;
551
      mPtrID2 = INVALID_POINTER_ID;
552
      }
553

    
554
///////////////////////////////////////////////////////////////////////////////////////////////////
555
// PUBLIC API
556
///////////////////////////////////////////////////////////////////////////////////////////////////
557

    
558
    public TutorialSurfaceView(Context context, AttributeSet attrs)
559
      {
560
      super(context,attrs);
561

    
562
      if(!isInEditMode())
563
        {
564
        mCurrRotSpeed= 0.0f;
565

    
566
        mLastX = new float[NUM_SPEED_PROBES];
567
        mLastY = new float[NUM_SPEED_PROBES];
568
        mLastT = new long[NUM_SPEED_PROBES];
569
        mFirstIndex =0;
570
        mLastIndex  =0;
571

    
572
        mRenderer  = new TutorialRenderer(this);
573
        mPreRender = new TutorialPreRender(this);
574

    
575
        TutorialActivity act = (TutorialActivity)context;
576
        DisplayMetrics dm = new DisplayMetrics();
577
        act.getWindowManager().getDefaultDisplay().getMetrics(dm);
578

    
579
        mDensity = dm.densityDpi;
580

    
581
        final ActivityManager activityManager= (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
582

    
583
        try
584
          {
585
          final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
586
          int esVersion = configurationInfo.reqGlEsVersion>>16;
587
          setEGLContextClientVersion(esVersion);
588
          setRenderer(mRenderer);
589
          }
590
        catch(Exception ex)
591
          {
592
          act.OpenGLError();
593

    
594
          String shading = GLES30.glGetString(GLES30.GL_SHADING_LANGUAGE_VERSION);
595
          String version = GLES30.glGetString(GLES30.GL_VERSION);
596
          String vendor  = GLES30.glGetString(GLES30.GL_VENDOR);
597
          String renderer= GLES30.glGetString(GLES30.GL_RENDERER);
598

    
599
          FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
600
          crashlytics.setCustomKey("GLSL Version"  , shading );
601
          crashlytics.setCustomKey("GLversion"     , version );
602
          crashlytics.setCustomKey("GL Vendor "    , vendor  );
603
          crashlytics.setCustomKey("GLSLrenderer"  , renderer);
604
          crashlytics.recordException(ex);
605
          }
606
        }
607
      }
608

    
609
///////////////////////////////////////////////////////////////////////////////////////////////////
610

    
611
    @Override
612
    public boolean onTouchEvent(MotionEvent event)
613
      {
614
      int action = event.getActionMasked();
615

    
616
      switch(action)
617
         {
618
         case MotionEvent.ACTION_DOWN        : actionDown(event) ; break;
619
         case MotionEvent.ACTION_MOVE        : actionMove(event) ; break;
620
         case MotionEvent.ACTION_UP          : actionUp(event)   ; break;
621
         case MotionEvent.ACTION_POINTER_DOWN: actionDown2(event); break;
622
         case MotionEvent.ACTION_POINTER_UP  : actionUp2(event)  ; break;
623
         }
624

    
625
      return true;
626
      }
627
}
628

    
(6-6/7)