Project

General

Profile

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

magiccube / src / main / java / org / distorted / tutorials / TutorialSurfaceView.java @ 1cd323dd

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 TutorialObjectStateActioner mActioner;
53
    private Movement mMovement;
54
    private boolean mDragging, mBeginningRotation, mContinuingRotation;
55
    private int mScreenWidth, mScreenHeight, mScreenMin;
56

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

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

    
74
///////////////////////////////////////////////////////////////////////////////////////////////////
75

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

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

    
84
///////////////////////////////////////////////////////////////////////////////////////////////////
85

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
170
///////////////////////////////////////////////////////////////////////////////////////////////////
171

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

    
181
      long timeDiff = lastTime-firstTime;
182

    
183
      mLastIndex = 0;
184
      mFirstIndex= 0;
185

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

    
189
///////////////////////////////////////////////////////////////////////////////////////////////////
190

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

    
197
      return distInPixels/mDensity;
198
      }
199

    
200
///////////////////////////////////////////////////////////////////////////////////////////////////
201

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

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

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

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

    
233
///////////////////////////////////////////////////////////////////////////////////////////////////
234

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

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

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

    
256
          return;
257
          }
258

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

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

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

    
270
        mRotAngle = angleNow;
271

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

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

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

    
290
///////////////////////////////////////////////////////////////////////////////////////////////////
291

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

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

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

    
310
///////////////////////////////////////////////////////////////////////////////////////////////////
311

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

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

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

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

    
329
      addSpeedProbe(x2,y2);
330
      }
331

    
332
///////////////////////////////////////////////////////////////////////////////////////////////////
333

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

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

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

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

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

    
352
      object.beginNewRotation( mCurrentAxis, mCurrentRow );
353

    
354
      addSpeedProbe(x,y);
355

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

    
360
///////////////////////////////////////////////////////////////////////////////////////////////////
361

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

    
367
///////////////////////////////////////////////////////////////////////////////////////////////////
368

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

    
373
      if( pointer<0 ) return;
374

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

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

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

    
402
///////////////////////////////////////////////////////////////////////////////////////////////////
403

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

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

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

    
414
      setUpDragOrRotate(mX,mY);
415
      }
416

    
417
///////////////////////////////////////////////////////////////////////////////////////////////////
418

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

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

    
430
///////////////////////////////////////////////////////////////////////////////////////////////////
431

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

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

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

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

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

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

    
463
            return;
464
            }
465
          }
466

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

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

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

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

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

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

    
498
            return;
499
            }
500
          }
501

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

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

    
521
///////////////////////////////////////////////////////////////////////////////////////////////////
522

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

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

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

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

    
547
///////////////////////////////////////////////////////////////////////////////////////////////////
548

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

    
555
///////////////////////////////////////////////////////////////////////////////////////////////////
556
// PUBLIC API
557
///////////////////////////////////////////////////////////////////////////////////////////////////
558

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

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

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

    
573
        mActioner  = new TutorialObjectStateActioner();
574
        mRenderer  = new TutorialRenderer(this);
575
        mPreRender = new TutorialPreRender(this,mActioner);
576

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

    
581
        mDensity = dm.densityDpi;
582

    
583
        final ActivityManager activityManager= (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
584

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

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

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

    
611
///////////////////////////////////////////////////////////////////////////////////////////////////
612

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

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

    
627
      return true;
628
      }
629
}
630

    
(7-7/8)