Project

General

Profile

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

magiccube / src / main / java / org / distorted / objects / TwistyObject.java @ e6cf7283

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.objects;
21

    
22
import android.content.SharedPreferences;
23
import android.content.res.Resources;
24
import android.graphics.Bitmap;
25
import android.graphics.Canvas;
26
import android.graphics.Paint;
27

    
28
import com.google.firebase.crashlytics.FirebaseCrashlytics;
29

    
30
import org.distorted.library.effect.Effect;
31
import org.distorted.library.effect.MatrixEffectMove;
32
import org.distorted.library.effect.MatrixEffectQuaternion;
33
import org.distorted.library.effect.MatrixEffectScale;
34
import org.distorted.library.effect.VertexEffectQuaternion;
35
import org.distorted.library.effect.VertexEffectRotate;
36
import org.distorted.library.main.DistortedEffects;
37
import org.distorted.library.main.DistortedLibrary;
38
import org.distorted.library.main.DistortedNode;
39
import org.distorted.library.main.DistortedTexture;
40
import org.distorted.library.mesh.MeshBase;
41
import org.distorted.library.mesh.MeshFile;
42
import org.distorted.library.mesh.MeshJoined;
43
import org.distorted.library.mesh.MeshSquare;
44
import org.distorted.library.message.EffectListener;
45
import org.distorted.library.type.Dynamic1D;
46
import org.distorted.library.type.Static1D;
47
import org.distorted.library.type.Static3D;
48
import org.distorted.library.type.Static4D;
49
import org.distorted.main.BuildConfig;
50
import org.distorted.main.RubikSurfaceView;
51

    
52
import java.io.DataInputStream;
53
import java.io.IOException;
54
import java.io.InputStream;
55
import java.util.Random;
56

    
57
///////////////////////////////////////////////////////////////////////////////////////////////////
58

    
59
public abstract class TwistyObject extends DistortedNode
60
  {
61
  static final int COLOR_YELLOW = 0xffffff00;
62
  static final int COLOR_WHITE  = 0xffffffff;
63
  static final int COLOR_BLUE   = 0xff0000ff;
64
  static final int COLOR_GREEN  = 0xff00bb00;
65
  static final int COLOR_RED    = 0xff990000;
66
  static final int COLOR_ORANGE = 0xffff6200;
67
  static final int COLOR_GREY   = 0xff727c7b;
68
  static final int COLOR_VIOLET = 0xff7700bb;
69
  static final int COLOR_BLACK  = 0xff000000;
70

    
71
  static final int TEXTURE_HEIGHT = 256;
72
  static final int NUM_STICKERS_IN_ROW = 4;
73

    
74
  static final float SQ2 = (float)Math.sqrt(2);
75
  static final float SQ3 = (float)Math.sqrt(3);
76
  static final float SQ5 = (float)Math.sqrt(5);
77
  static final float SQ6 = (float)Math.sqrt(6);
78

    
79
  private static final float NODE_RATIO = 1.40f;
80
  private static final float MAX_SIZE_CHANGE = 1.35f;
81
  private static final float MIN_SIZE_CHANGE = 0.75f;
82

    
83
  private static final boolean mCreateFromDMesh = false;
84

    
85
  private static final Static3D CENTER = new Static3D(0,0,0);
86
  private static final int POST_ROTATION_MILLISEC = 500;
87

    
88
  final Static3D[] ROTATION_AXIS;
89
  final Static4D[] QUATS;
90
  final Cubit[] CUBITS;
91
  final int NUM_FACES;
92
  final int NUM_TEXTURES;
93
  final int NUM_CUBIT_FACES;
94
  final int NUM_AXIS;
95
  final int NUM_CUBITS;
96
  final float[] CUTS;
97
  final int NUM_CUTS;
98

    
99
  private static float mInitScreenRatio;
100
  private static float mObjectScreenRatio = 1.0f;
101
  private static final float[] mTmp1 = new float[4];
102
  private static final float[] mTmp2 = new float[4];
103

    
104
  private final int mNodeSize;
105
  private final float[][] mOrigPos;
106
  private final Static3D mNodeScale;
107
  private final Static4D mQuat;
108
  private final int mNumLayers, mRealSize;
109
  private final ObjectList mList;
110
  private final DistortedEffects mEffects;
111
  private final VertexEffectRotate mRotateEffect;
112
  private final Dynamic1D mRotationAngle;
113
  private final Static3D mRotationAxis;
114
  private final Static3D mObjectScale;
115
  private final int[] mQuatDebug;
116
  private final float mCameraDist;
117
  private int mNumTexRows, mNumTexCols;
118
  private int mRotRowBitmap;
119
  private int mRotAxis;
120
  private MeshBase mMesh;
121

    
122
  float[] mRowChances;
123
  Static1D mRotationAngleStatic, mRotationAngleMiddle, mRotationAngleFinal;
124
  DistortedTexture mTexture;
125
  MatrixEffectScale mScaleEffect;
126
  MatrixEffectQuaternion mQuatEffect;
127

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

    
130
  TwistyObject(int numLayers, int realSize, Static4D quat, DistortedTexture nodeTexture, MeshSquare nodeMesh,
131
               DistortedEffects nodeEffects, int[][] moves, ObjectList list, Resources res, int screenWidth)
132
    {
133
    super(nodeTexture,nodeEffects,nodeMesh);
134

    
135
    mNodeSize = screenWidth;
136

    
137
    resizeFBO(mNodeSize, (int)(NODE_RATIO*mNodeSize));
138

    
139
    mNumLayers = numLayers;
140
    mRealSize = realSize;
141
    mList = list;
142
    mOrigPos = getCubitPositions(mNumLayers);
143

    
144
    QUATS = getQuats();
145
    NUM_CUBITS  = mOrigPos.length;
146
    ROTATION_AXIS = getRotationAxis();
147
    NUM_AXIS = ROTATION_AXIS.length;
148
    mInitScreenRatio = getScreenRatio();
149
    NUM_FACES = getNumFaces();
150
    NUM_CUBIT_FACES = getNumCubitFaces();
151
    NUM_TEXTURES = getNumStickerTypes(mNumLayers)*NUM_FACES;
152
    CUTS = getCuts(mNumLayers);
153
    NUM_CUTS = CUTS.length;
154

    
155
    mQuatDebug = new int[NUM_CUBITS];
156

    
157
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
158
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
159

    
160
    mNodeScale= new Static3D(1,NODE_RATIO,1);
161
    mQuat = quat;
162

    
163
    mRowChances = getRowChances(mNumLayers);
164

    
165
    mRotationAngle= new Dynamic1D();
166
    mRotationAxis = new Static3D(1,0,0);
167
    mRotateEffect = new VertexEffectRotate(mRotationAngle, mRotationAxis, CENTER);
168

    
169
    mRotationAngleStatic = new Static1D(0);
170
    mRotationAngleMiddle = new Static1D(0);
171
    mRotationAngleFinal  = new Static1D(0);
172

    
173
    float scale  = mObjectScreenRatio*mInitScreenRatio*mNodeSize/mRealSize;
174
    mObjectScale = new Static3D(scale,scale,scale);
175
    mScaleEffect = new MatrixEffectScale(mObjectScale);
176
    mQuatEffect  = new MatrixEffectQuaternion(quat, CENTER);
177

    
178
    MatrixEffectScale nodeScaleEffect = new MatrixEffectScale(mNodeScale);
179
    nodeEffects.apply(nodeScaleEffect);
180

    
181
    mNumTexCols = NUM_STICKERS_IN_ROW;
182
    mNumTexRows = (NUM_TEXTURES+1)/NUM_STICKERS_IN_ROW;
183

    
184
    if( mNumTexCols*mNumTexRows < NUM_TEXTURES+1 ) mNumTexRows++;
185

    
186
    CUBITS = new Cubit[NUM_CUBITS];
187
    createMeshAndCubits(list,res);
188

    
189
    mTexture = new DistortedTexture();
190
    mEffects = new DistortedEffects();
191

    
192
    int num_quats = QUATS.length;
193
    for(int q=0; q<num_quats; q++)
194
      {
195
      VertexEffectQuaternion vq = new VertexEffectQuaternion(QUATS[q],CENTER);
196
      vq.setMeshAssociation(0,q);
197
      mEffects.apply(vq);
198
      }
199

    
200
    mEffects.apply(mRotateEffect);
201
    mEffects.apply(mQuatEffect);
202
    mEffects.apply(mScaleEffect);
203

    
204
    // Now postprocessed effects (the glow when you solve an object) require component centers. In
205
    // order for the effect to be in front of the object, we need to set the center to be behind it.
206
    getMesh().setComponentCenter(0,0,0,-0.1f);
207

    
208
    attach( new DistortedNode(mTexture,mEffects,mMesh) );
209

    
210
    setupPosition(moves);
211

    
212
    float fov = list.getFOV();
213
    double halfFOV = fov * (Math.PI/360);
214
    mCameraDist = 0.5f*NODE_RATIO / (float)Math.tan(halfFOV);
215

    
216
    setProjection( fov, 0.1f);
217
    }
218

    
219
///////////////////////////////////////////////////////////////////////////////////////////////////
220

    
221
  private Static3D getPos(float[] origPos)
222
    {
223
    int len = origPos.length/3;
224
    float sumX = 0.0f;
225
    float sumY = 0.0f;
226
    float sumZ = 0.0f;
227

    
228
    for(int i=0; i<len; i++)
229
      {
230
      sumX += origPos[3*i  ];
231
      sumY += origPos[3*i+1];
232
      sumZ += origPos[3*i+2];
233
      }
234

    
235
    sumX /= len;
236
    sumY /= len;
237
    sumZ /= len;
238

    
239
    return new Static3D(sumX,sumY,sumZ);
240
    }
241

    
242
///////////////////////////////////////////////////////////////////////////////////////////////////
243

    
244
  private void createMeshAndCubits(ObjectList list, Resources res)
245
    {
246
    if( mCreateFromDMesh )
247
      {
248
      int sizeIndex = ObjectList.getSizeIndex(list.ordinal(),mNumLayers);
249
      int resourceID= list.getResourceIDs()[sizeIndex];
250

    
251
      InputStream is = res.openRawResource(resourceID);
252
      DataInputStream dos = new DataInputStream(is);
253
      mMesh = new MeshFile(dos);
254

    
255
      try
256
        {
257
        is.close();
258
        }
259
      catch(IOException e)
260
        {
261
        android.util.Log.e("meshFile", "Error closing InputStream: "+e.toString());
262
        }
263

    
264
      for(int i=0; i<NUM_CUBITS; i++)
265
        {
266
        CUBITS[i] = new Cubit(this,mOrigPos[i]);
267
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
268
        }
269

    
270
      if( shouldResetTextureMaps() ) resetAllTextureMaps();
271
      }
272
    else
273
      {
274
      MeshBase[] cubitMesh = new MeshBase[NUM_CUBITS];
275

    
276
      for(int i=0; i<NUM_CUBITS; i++)
277
        {
278
        CUBITS[i] = new Cubit(this,mOrigPos[i]);
279
        cubitMesh[i] = createCubitMesh(i,mNumLayers);
280
        Static3D pos = getPos(mOrigPos[i]);
281
        cubitMesh[i].apply(new MatrixEffectMove(pos),1,0);
282
        cubitMesh[i].setEffectAssociation(0, CUBITS[i].computeAssociation(), 0);
283
        }
284

    
285
      mMesh = new MeshJoined(cubitMesh);
286
      resetAllTextureMaps();
287
      }
288
    }
289

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

    
292
  public void setObjectRatio(float sizeChange)
293
    {
294
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
295

    
296
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
297
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
298

    
299
    float scale = mObjectScreenRatio*mInitScreenRatio*mNodeSize/mRealSize;
300
    mObjectScale.set(scale,scale,scale);
301
    }
302

    
303
///////////////////////////////////////////////////////////////////////////////////////////////////
304

    
305
  static float getObjectRatio()
306
    {
307
    return mObjectScreenRatio*mInitScreenRatio;
308
    }
309

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

    
312
  int computeRow(float[] pos, int rotIndex)
313
    {
314
    int ret=0;
315
    int len = pos.length / 3;
316
    Static3D axis = ROTATION_AXIS[rotIndex];
317
    float axisX = axis.get0();
318
    float axisY = axis.get1();
319
    float axisZ = axis.get2();
320

    
321
    for(int i=0; i<len; i++)
322
      {
323
      ret |= computeRow(pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ);
324
      }
325

    
326
    return ret;
327
    }
328

    
329
///////////////////////////////////////////////////////////////////////////////////////////////////
330

    
331
  private int computeRow(float casted)
332
    {
333
    for(int i=0; i<NUM_CUTS; i++)
334
      {
335
      if( casted<CUTS[i] ) return (1<<i);
336
      }
337

    
338
    return (1<<NUM_CUTS);
339
    }
340

    
341
///////////////////////////////////////////////////////////////////////////////////////////////////
342

    
343
  private boolean wasRotateApplied()
344
    {
345
    return mEffects.exists(mRotateEffect.getID());
346
    }
347

    
348
///////////////////////////////////////////////////////////////////////////////////////////////////
349

    
350
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
351
    {
352
    return (CUBITS[cubit].mRotationRow[axis] & rowBitmap) != 0;
353
    }
354

    
355
///////////////////////////////////////////////////////////////////////////////////////////////////
356
// note the minus in front of the sin() - we rotate counterclockwise
357
// when looking towards the direction where the axis increases in values.
358

    
359
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
360
    {
361
    Static3D axis = ROTATION_AXIS[axisIndex];
362

    
363
    while( angleInDegrees<0 ) angleInDegrees += 360;
364
    angleInDegrees %= 360;
365
    
366
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
367
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
368

    
369
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
370
    }
371

    
372
///////////////////////////////////////////////////////////////////////////////////////////////////
373

    
374
  private synchronized void setupPosition(int[][] moves)
375
    {
376
    if( moves!=null )
377
      {
378
      Static4D quat;
379
      int index, axis, rowBitmap, angle;
380
      int corr = (360/getBasicAngle());
381

    
382
      for(int[] move: moves)
383
        {
384
        axis     = move[0];
385
        rowBitmap= move[1];
386
        angle    = move[2]*corr;
387
        quat     = makeQuaternion(axis,angle);
388

    
389
        for(int j=0; j<NUM_CUBITS; j++)
390
          if( belongsToRotation(j,axis,rowBitmap) )
391
            {
392
            index = CUBITS[j].removeRotationNow(quat);
393
            mMesh.setEffectAssociation(j, CUBITS[j].computeAssociation(),index);
394
            }
395
        }
396
      }
397
    }
398

    
399
///////////////////////////////////////////////////////////////////////////////////////////////////
400

    
401
  int getCubitFaceColorIndex(int cubit, int face)
402
    {
403
    Static4D texMap = mMesh.getTextureMap(NUM_FACES*cubit + face);
404

    
405
    int x = (int)(texMap.get0()/texMap.get2());
406
    int y = (int)(texMap.get1()/texMap.get3());
407

    
408
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
409
    }
410

    
411
///////////////////////////////////////////////////////////////////////////////////////////////////
412
// Clamp all rotated positions to one of those original ones to avoid accumulating errors.
413

    
414
  void clampPos(float[] pos, int offset)
415
    {
416
    float currError, minError = Float.MAX_VALUE;
417
    int minErrorIndex1 = -1;
418
    int minErrorIndex2 = -1;
419

    
420
    float x = pos[offset  ];
421
    float y = pos[offset+1];
422
    float z = pos[offset+2];
423

    
424
    float xo,yo,zo;
425

    
426
    for(int i=0; i<NUM_CUBITS; i++)
427
      {
428
      int len = mOrigPos[i].length / 3;
429

    
430
      for(int j=0; j<len; j++)
431
        {
432
        xo = mOrigPos[i][3*j  ];
433
        yo = mOrigPos[i][3*j+1];
434
        zo = mOrigPos[i][3*j+2];
435

    
436
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
437

    
438
        if( currError<minError )
439
          {
440
          minError = currError;
441
          minErrorIndex1 = i;
442
          minErrorIndex2 = j;
443
          }
444
        }
445
      }
446

    
447
    pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
448
    pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
449
    pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
450
    }
451

    
452
///////////////////////////////////////////////////////////////////////////////////////////////////
453
// return if the Cubit, when rotated with its own mQuatScramble, would have looked any different
454
// then if it were rotated by quaternion 'quat'.
455
// No it is not so simple as the quats need to be the same - imagine a 4x4x4 cube where the two
456
// middle squares get interchanged. No visible difference!
457
//
458
// So: this is true iff the cubit
459
// a) is a corner or edge and the quaternions are the same
460
// b) is inside one of the faces and after rotations by both quats it ends up on the same face.
461

    
462
  boolean thereIsVisibleDifference(Cubit cubit, int quatIndex)
463
    {
464
    if ( cubit.mQuatIndex == quatIndex ) return false;
465

    
466
    int belongsToHowManyFaces = 0;
467
    int bitmap = (1<<(getNumLayers()-1)) + 1;
468

    
469
    for(int i=0; i<NUM_AXIS; i++)
470
      {
471
      if( (cubit.mRotationRow[i] & bitmap) != 0 ) belongsToHowManyFaces++;
472
      }
473

    
474
    switch(belongsToHowManyFaces)
475
      {
476
      case 0 : return false;  // 'inside' cubit that does not lie on any face
477
      case 1 :                // cubit that lies inside one of the faces
478
               float[] orig   = cubit.getOrigPosition();
479
               Static4D quat1 = QUATS[quatIndex];
480
               Static4D quat2 = QUATS[cubit.mQuatIndex];
481

    
482
               Static4D cubitCenter = new Static4D( orig[0], orig[1], orig[2], 0);              // not used for bandaged objects,
483
               Static4D rotated1 = RubikSurfaceView.rotateVectorByQuat( cubitCenter, quat1 );   // only check the first position
484
               Static4D rotated2 = RubikSurfaceView.rotateVectorByQuat( cubitCenter, quat2 );
485

    
486
               rotated1.get(mTmp1, 0, 0, 0);
487
               rotated2.get(mTmp2, 0, 0, 0);
488

    
489
               for(int i=0; i<NUM_AXIS; i++)
490
                 {
491
                 if( (computeRow(mTmp1,i) & computeRow(mTmp2,i) & bitmap) != 0 ) return false;
492
                 }
493
               return true;
494

    
495
      default: return true;  // edge or corner
496
      }
497
    }
498

    
499
///////////////////////////////////////////////////////////////////////////////////////////////////
500
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
501

    
502
  public void createTexture()
503
    {
504
    Bitmap bitmap;
505

    
506
    Paint paint = new Paint();
507
    bitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_8888);
508
    Canvas canvas = new Canvas(bitmap);
509

    
510
    paint.setAntiAlias(true);
511
    paint.setTextAlign(Paint.Align.CENTER);
512
    paint.setStyle(Paint.Style.FILL);
513

    
514
    paint.setColor(COLOR_BLACK);
515
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
516

    
517
    int tex = 0;
518

    
519
    for(int row=0; row<mNumTexRows; row++)
520
      for(int col=0; col<mNumTexCols; col++)
521
        {
522
        if( tex>=NUM_TEXTURES ) break;
523
        createFaceTexture(canvas, paint, tex, col*TEXTURE_HEIGHT, row*TEXTURE_HEIGHT);
524
        tex++;
525
        }
526

    
527
    if( !mTexture.setTexture(bitmap) )
528
      {
529
      int max = DistortedLibrary.getMaxTextureSize();
530
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
531
      crashlytics.log("failed to set texture of size "+bitmap.getWidth()+"x"+bitmap.getHeight()+" max is "+max);
532
      }
533
    }
534

    
535
///////////////////////////////////////////////////////////////////////////////////////////////////
536

    
537
  public int getNumLayers()
538
    {
539
    return mNumLayers;
540
    }
541

    
542
///////////////////////////////////////////////////////////////////////////////////////////////////
543

    
544
  public void continueRotation(float angleInDegrees)
545
    {
546
    mRotationAngleStatic.set0(angleInDegrees);
547
    }
548

    
549
///////////////////////////////////////////////////////////////////////////////////////////////////
550

    
551
  public Static4D getRotationQuat()
552
      {
553
      return mQuat;
554
      }
555

    
556
///////////////////////////////////////////////////////////////////////////////////////////////////
557

    
558
  public void recomputeScaleFactor(int scrWidth)
559
    {
560
    mNodeScale.set(scrWidth,NODE_RATIO*scrWidth,scrWidth);
561
    }
562

    
563
///////////////////////////////////////////////////////////////////////////////////////////////////
564

    
565
  public void savePreferences(SharedPreferences.Editor editor)
566
    {
567
    for(int i=0; i<NUM_CUBITS; i++) CUBITS[i].savePreferences(editor);
568
    }
569

    
570
///////////////////////////////////////////////////////////////////////////////////////////////////
571

    
572
  public synchronized void restorePreferences(SharedPreferences preferences)
573
    {
574
    boolean error = false;
575

    
576
    for(int i=0; i<NUM_CUBITS; i++)
577
      {
578
      mQuatDebug[i] = CUBITS[i].restorePreferences(preferences);
579

    
580
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<QUATS.length)
581
        {
582
        CUBITS[i].modifyCurrentPosition(QUATS[mQuatDebug[i]]);
583
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),mQuatDebug[i]);
584
        }
585
      else
586
        {
587
        error = true;
588
        }
589
      }
590

    
591
    if( error )
592
      {
593
      for(int i=0; i<NUM_CUBITS; i++)
594
        {
595
        CUBITS[i].solve();
596
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),0);
597
        }
598
      recordQuatsState("Failed to restorePreferences");
599
      }
600
    }
601

    
602
///////////////////////////////////////////////////////////////////////////////////////////////////
603

    
604
  public void recordQuatsState(String message)
605
    {
606
    StringBuilder quats = new StringBuilder();
607

    
608
    for(int j=0; j<NUM_CUBITS; j++)
609
      {
610
      quats.append(mQuatDebug[j]);
611
      quats.append(" ");
612
      }
613

    
614
    if( BuildConfig.DEBUG )
615
      {
616
      android.util.Log.e("quats" , quats.toString());
617
      android.util.Log.e("object", mList.name()+"_"+mNumLayers);
618
      }
619
    else
620
      {
621
      Exception ex = new Exception(message);
622
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
623
      crashlytics.setCustomKey("quats" , quats.toString());
624
      crashlytics.setCustomKey("object", mList.name()+"_"+mNumLayers );
625
      crashlytics.recordException(ex);
626
      }
627
    }
628

    
629
///////////////////////////////////////////////////////////////////////////////////////////////////
630

    
631
  public void releaseResources()
632
    {
633
    mTexture.markForDeletion();
634
    mMesh.markForDeletion();
635
    mEffects.markForDeletion();
636

    
637
    for(int j=0; j<NUM_CUBITS; j++)
638
      {
639
      CUBITS[j].releaseResources();
640
      }
641
    }
642

    
643
///////////////////////////////////////////////////////////////////////////////////////////////////
644

    
645
  public void apply(Effect effect, int position)
646
    {
647
    mEffects.apply(effect, position);
648
    }
649

    
650
///////////////////////////////////////////////////////////////////////////////////////////////////
651

    
652
  public void remove(long effectID)
653
    {
654
    mEffects.abortById(effectID);
655
    }
656

    
657
///////////////////////////////////////////////////////////////////////////////////////////////////
658

    
659
  public synchronized void solve()
660
    {
661
    for(int i=0; i<NUM_CUBITS; i++)
662
      {
663
      CUBITS[i].solve();
664
      mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
665
      }
666
    }
667

    
668
///////////////////////////////////////////////////////////////////////////////////////////////////
669

    
670
  public void resetAllTextureMaps()
671
    {
672
    final float ratioW = 1.0f/mNumTexCols;
673
    final float ratioH = 1.0f/mNumTexRows;
674
    int color, row, col;
675

    
676
    for(int cubit=0; cubit<NUM_CUBITS; cubit++)
677
      {
678
      final Static4D[] maps = new Static4D[NUM_CUBIT_FACES];
679

    
680
      for(int cubitface=0; cubitface<NUM_CUBIT_FACES; cubitface++)
681
        {
682
        color = getFaceColor(cubit,cubitface,mNumLayers);
683
        row = (mNumTexRows-1) - color/mNumTexCols;
684
        col = color%mNumTexCols;
685
        maps[cubitface] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
686
        }
687

    
688
      mMesh.setTextureMap(maps,NUM_CUBIT_FACES*cubit);
689
      }
690
    }
691

    
692
///////////////////////////////////////////////////////////////////////////////////////////////////
693

    
694
  public void setTextureMap(int cubit, int face, int newColor)
695
    {
696
    final float ratioW = 1.0f/mNumTexCols;
697
    final float ratioH = 1.0f/mNumTexRows;
698
    final Static4D[] maps = new Static4D[NUM_CUBIT_FACES];
699
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
700
    int col = newColor%mNumTexCols;
701

    
702
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
703
    mMesh.setTextureMap(maps,NUM_CUBIT_FACES*cubit);
704
    }
705

    
706
///////////////////////////////////////////////////////////////////////////////////////////////////
707

    
708
  public synchronized void beginNewRotation(int axis, int row )
709
    {
710
    if( axis<0 || axis>=ROTATION_AXIS.length )
711
      {
712
      android.util.Log.e("object", "invalid rotation axis: "+axis);
713
      return;
714
      }
715
    if( row<0 || row>=mNumLayers )
716
      {
717
      android.util.Log.e("object", "invalid rotation row: "+row);
718
      return;
719
      }
720

    
721
    mRotAxis     = axis;
722
    mRotRowBitmap= (1<<row);
723
    mRotationAngleStatic.set0(0.0f);
724
    mRotationAxis.set( ROTATION_AXIS[axis] );
725
    mRotationAngle.add(mRotationAngleStatic);
726
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis* ObjectList.MAX_OBJECT_SIZE) , -1);
727
    }
728

    
729
///////////////////////////////////////////////////////////////////////////////////////////////////
730

    
731
  public synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
732
    {
733
    if( wasRotateApplied() )
734
      {
735
      mRotAxis     = axis;
736
      mRotRowBitmap= rowBitmap;
737

    
738
      mRotationAngleStatic.set0(0.0f);
739
      mRotationAxis.set( ROTATION_AXIS[axis] );
740
      mRotationAngle.setDuration(durationMillis);
741
      mRotationAngle.resetToBeginning();
742
      mRotationAngle.add(new Static1D(0));
743
      mRotationAngle.add(new Static1D(angle));
744
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis* ObjectList.MAX_OBJECT_SIZE) , -1);
745
      mRotateEffect.notifyWhenFinished(listener);
746

    
747
      return mRotateEffect.getID();
748
      }
749

    
750
    return 0;
751
    }
752

    
753
///////////////////////////////////////////////////////////////////////////////////////////////////
754

    
755
  public long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
756
    {
757
    if( wasRotateApplied() )
758
      {
759
      float angle = getAngle();
760
      mRotationAngleStatic.set0(angle);
761
      mRotationAngleFinal.set0(nearestAngleInDegrees);
762
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
763

    
764
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
765
      mRotationAngle.resetToBeginning();
766
      mRotationAngle.removeAll();
767
      mRotationAngle.add(mRotationAngleStatic);
768
      mRotationAngle.add(mRotationAngleMiddle);
769
      mRotationAngle.add(mRotationAngleFinal);
770
      mRotateEffect.notifyWhenFinished(listener);
771

    
772
      return mRotateEffect.getID();
773
      }
774

    
775
    return 0;
776
    }
777

    
778
///////////////////////////////////////////////////////////////////////////////////////////////////
779

    
780
  private float getAngle()
781
    {
782
    int pointNum = mRotationAngle.getNumPoints();
783

    
784
    if( pointNum>=1 )
785
      {
786
      return mRotationAngle.getPoint(pointNum-1).get0();
787
      }
788
    else
789
      {
790
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
791
      crashlytics.log("points in RotationAngle: "+pointNum);
792
      return 0;
793
      }
794
    }
795

    
796
///////////////////////////////////////////////////////////////////////////////////////////////////
797

    
798
  public synchronized void removeRotationNow()
799
    {
800
    float angle = getAngle();
801
    double nearestAngleInRadians = angle*Math.PI/180;
802
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
803
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
804
    float axisX = ROTATION_AXIS[mRotAxis].get0();
805
    float axisY = ROTATION_AXIS[mRotAxis].get1();
806
    float axisZ = ROTATION_AXIS[mRotAxis].get2();
807
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
808

    
809
    mRotationAngle.removeAll();
810
    mRotationAngleStatic.set0(0);
811

    
812
    for(int i=0; i<NUM_CUBITS; i++)
813
      if( belongsToRotation(i,mRotAxis,mRotRowBitmap) )
814
        {
815
        int index = CUBITS[i].removeRotationNow(quat);
816
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),index);
817
        }
818
    }
819

    
820
///////////////////////////////////////////////////////////////////////////////////////////////////
821

    
822
  public void initializeObject(int[][] moves)
823
    {
824
    solve();
825
    setupPosition(moves);
826
    }
827

    
828
///////////////////////////////////////////////////////////////////////////////////////////////////
829

    
830
  public int getCubit(float[] point3D)
831
    {
832
    float dist, minDist = Float.MAX_VALUE;
833
    int currentBest=-1;
834
    float multiplier = returnMultiplier();
835

    
836
    point3D[0] *= multiplier;
837
    point3D[1] *= multiplier;
838
    point3D[2] *= multiplier;
839

    
840
    for(int i=0; i<NUM_CUBITS; i++)
841
      {
842
      dist = CUBITS[i].getDistSquared(point3D);
843
      if( dist<minDist )
844
        {
845
        minDist = dist;
846
        currentBest = i;
847
        }
848
      }
849

    
850
    return currentBest;
851
    }
852

    
853
///////////////////////////////////////////////////////////////////////////////////////////////////
854

    
855
  public int computeNearestAngle(float angle, float speed)
856
    {
857
    final int NEAREST = 360/getBasicAngle();
858

    
859
    int tmp = (int)((angle+NEAREST/2)/NEAREST);
860
    if( angle< -(NEAREST*0.5) ) tmp-=1;
861

    
862
    if( tmp!=0 ) return NEAREST*tmp;
863

    
864
    return speed> 1.2f ? NEAREST*(angle>0 ? 1:-1) : 0;
865
    }
866

    
867
///////////////////////////////////////////////////////////////////////////////////////////////////
868

    
869
  public float getCameraDist()
870
    {
871
    return mCameraDist;
872
    }
873

    
874
///////////////////////////////////////////////////////////////////////////////////////////////////
875

    
876
  public int getNodeSize()
877
    {
878
    return mNodeSize;
879
    }
880

    
881
///////////////////////////////////////////////////////////////////////////////////////////////////
882

    
883
  public ObjectList getObjectList()
884
    {
885
    return mList;
886
    }
887

    
888
///////////////////////////////////////////////////////////////////////////////////////////////////
889

    
890
  abstract float getScreenRatio();
891
  abstract float[][] getCubitPositions(int numLayers);
892
  abstract Static4D[] getQuats();
893
  abstract int getNumFaces();
894
  abstract int getNumStickerTypes(int numLayers);
895
  abstract int getNumCubitFaces();
896
  abstract MeshBase createCubitMesh(int cubit, int numLayers);
897
  abstract void createFaceTexture(Canvas canvas, Paint paint, int face, int left, int top);
898
  abstract int getFaceColor(int cubit, int cubitface, int numLayers);
899
  abstract float returnMultiplier();
900
  abstract float[] getRowChances(int numLayers);
901
  abstract float[] getCuts(int numLayers);
902
  abstract boolean shouldResetTextureMaps();
903

    
904
  public abstract boolean isSolved();
905
  public abstract Static3D[] getRotationAxis();
906
  public abstract int getBasicAngle();
907
  public abstract String retObjectString();
908
  public abstract int randomizeNewRotAxis(Random rnd, int oldRotAxis);
909
  public abstract int randomizeNewRow(Random rnd, int oldRotAxis, int oldRow, int newRotAxis);
910
  public abstract int getObjectName(int numLayers);
911
  public abstract int getInventor(int numLayers);
912
  public abstract int getComplexity(int numLayers);
913
  }
(31-31/35)