Project

General

Profile

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

magiccube / src / main / java / org / distorted / objects / TwistyObject.java @ 749ef882

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
  public static final int COLOR_YELLOW = 0xffffff00;
62
  public static final int COLOR_WHITE  = 0xffffffff;
63
  public static final int COLOR_BLUE   = 0xff0000ff;
64
  public static final int COLOR_GREEN  = 0xff00bb00;
65
  public static final int COLOR_RED    = 0xff990000;
66
  public static final int COLOR_ORANGE = 0xffff6200;
67
  public static final int COLOR_GREY   = 0xff727c7b;
68
  public static final int COLOR_VIOLET = 0xff7700bb;
69
  public static final int COLOR_BLACK  = 0xff000000;
70

    
71
  public 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 = true;
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== null ? 0: 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
// normal, not bandaged, object.
413

    
414
  int computeBitmapFromRow(int rowBitmap, int axis)
415
    {
416
    return rowBitmap;
417
    }
418

    
419
///////////////////////////////////////////////////////////////////////////////////////////////////
420
// Clamp all rotated positions to one of those original ones to avoid accumulating errors.
421

    
422
  void clampPos(float[] pos, int offset)
423
    {
424
    float currError, minError = Float.MAX_VALUE;
425
    int minErrorIndex1 = -1;
426
    int minErrorIndex2 = -1;
427

    
428
    float x = pos[offset  ];
429
    float y = pos[offset+1];
430
    float z = pos[offset+2];
431

    
432
    float xo,yo,zo;
433

    
434
    for(int i=0; i<NUM_CUBITS; i++)
435
      {
436
      int len = mOrigPos[i].length / 3;
437

    
438
      for(int j=0; j<len; j++)
439
        {
440
        xo = mOrigPos[i][3*j  ];
441
        yo = mOrigPos[i][3*j+1];
442
        zo = mOrigPos[i][3*j+2];
443

    
444
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
445

    
446
        if( currError<minError )
447
          {
448
          minError = currError;
449
          minErrorIndex1 = i;
450
          minErrorIndex2 = j;
451
          }
452
        }
453
      }
454

    
455
    pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
456
    pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
457
    pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
458
    }
459

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

    
470
  boolean thereIsVisibleDifference(Cubit cubit, int quatIndex)
471
    {
472
    if ( cubit.mQuatIndex == quatIndex ) return false;
473

    
474
    int belongsToHowManyFaces = 0;
475
    int bitmap = (1<<(getNumLayers()-1)) + 1;
476

    
477
    for(int i=0; i<NUM_AXIS; i++)
478
      {
479
      if( (cubit.mRotationRow[i] & bitmap) != 0 ) belongsToHowManyFaces++;
480
      }
481

    
482
    switch(belongsToHowManyFaces)
483
      {
484
      case 0 : return false;  // 'inside' cubit that does not lie on any face
485
      case 1 :                // cubit that lies inside one of the faces
486
               float[] orig   = cubit.getOrigPosition();
487
               Static4D quat1 = QUATS[quatIndex];
488
               Static4D quat2 = QUATS[cubit.mQuatIndex];
489

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

    
494
               rotated1.get(mTmp1, 0, 0, 0);
495
               rotated2.get(mTmp2, 0, 0, 0);
496

    
497
               for(int i=0; i<NUM_AXIS; i++)
498
                 {
499
                 if( (computeRow(mTmp1,i) & computeRow(mTmp2,i) & bitmap) != 0 ) return false;
500
                 }
501
               return true;
502

    
503
      default: return true;  // edge or corner
504
      }
505
    }
506

    
507
///////////////////////////////////////////////////////////////////////////////////////////////////
508
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
509

    
510
  public void createTexture()
511
    {
512
    Bitmap bitmap;
513

    
514
    Paint paint = new Paint();
515
    bitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_8888);
516
    Canvas canvas = new Canvas(bitmap);
517

    
518
    paint.setAntiAlias(true);
519
    paint.setTextAlign(Paint.Align.CENTER);
520
    paint.setStyle(Paint.Style.FILL);
521

    
522
    paint.setColor(COLOR_BLACK);
523
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
524

    
525
    int tex = 0;
526

    
527
    for(int row=0; row<mNumTexRows; row++)
528
      for(int col=0; col<mNumTexCols; col++)
529
        {
530
        if( tex>=NUM_TEXTURES ) break;
531
        createFaceTexture(canvas, paint, tex, col*TEXTURE_HEIGHT, row*TEXTURE_HEIGHT);
532
        tex++;
533
        }
534

    
535
    if( !mTexture.setTexture(bitmap) )
536
      {
537
      int max = DistortedLibrary.getMaxTextureSize();
538
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
539
      crashlytics.log("failed to set texture of size "+bitmap.getWidth()+"x"+bitmap.getHeight()+" max is "+max);
540
      }
541
    }
542

    
543
///////////////////////////////////////////////////////////////////////////////////////////////////
544

    
545
  public int getNumLayers()
546
    {
547
    return mNumLayers;
548
    }
549

    
550
///////////////////////////////////////////////////////////////////////////////////////////////////
551

    
552
  public void continueRotation(float angleInDegrees)
553
    {
554
    mRotationAngleStatic.set0(angleInDegrees);
555
    }
556

    
557
///////////////////////////////////////////////////////////////////////////////////////////////////
558

    
559
  public Static4D getRotationQuat()
560
      {
561
      return mQuat;
562
      }
563

    
564
///////////////////////////////////////////////////////////////////////////////////////////////////
565

    
566
  public void recomputeScaleFactor(int scrWidth)
567
    {
568
    mNodeScale.set(scrWidth,NODE_RATIO*scrWidth,scrWidth);
569
    }
570

    
571
///////////////////////////////////////////////////////////////////////////////////////////////////
572

    
573
  public void savePreferences(SharedPreferences.Editor editor)
574
    {
575
    for(int i=0; i<NUM_CUBITS; i++) CUBITS[i].savePreferences(editor);
576
    }
577

    
578
///////////////////////////////////////////////////////////////////////////////////////////////////
579

    
580
  public synchronized void restorePreferences(SharedPreferences preferences)
581
    {
582
    boolean error = false;
583

    
584
    for(int i=0; i<NUM_CUBITS; i++)
585
      {
586
      mQuatDebug[i] = CUBITS[i].restorePreferences(preferences);
587

    
588
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<QUATS.length)
589
        {
590
        CUBITS[i].modifyCurrentPosition(QUATS[mQuatDebug[i]]);
591
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),mQuatDebug[i]);
592
        }
593
      else
594
        {
595
        error = true;
596
        }
597
      }
598

    
599
    if( error )
600
      {
601
      for(int i=0; i<NUM_CUBITS; i++)
602
        {
603
        CUBITS[i].solve();
604
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),0);
605
        }
606
      recordQuatsState("Failed to restorePreferences");
607
      }
608
    }
609

    
610
///////////////////////////////////////////////////////////////////////////////////////////////////
611

    
612
  public void recordQuatsState(String message)
613
    {
614
    StringBuilder quats = new StringBuilder();
615

    
616
    for(int j=0; j<NUM_CUBITS; j++)
617
      {
618
      quats.append(mQuatDebug[j]);
619
      quats.append(" ");
620
      }
621

    
622
    if( BuildConfig.DEBUG )
623
      {
624
      android.util.Log.e("quats" , quats.toString());
625
      android.util.Log.e("object", mList.name()+"_"+mNumLayers);
626
      }
627
    else
628
      {
629
      Exception ex = new Exception(message);
630
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
631
      crashlytics.setCustomKey("quats" , quats.toString());
632
      crashlytics.setCustomKey("object", mList.name()+"_"+mNumLayers );
633
      crashlytics.recordException(ex);
634
      }
635
    }
636

    
637
///////////////////////////////////////////////////////////////////////////////////////////////////
638

    
639
  public void releaseResources()
640
    {
641
    mTexture.markForDeletion();
642
    mMesh.markForDeletion();
643
    mEffects.markForDeletion();
644

    
645
    for(int j=0; j<NUM_CUBITS; j++)
646
      {
647
      CUBITS[j].releaseResources();
648
      }
649
    }
650

    
651
///////////////////////////////////////////////////////////////////////////////////////////////////
652

    
653
  public void apply(Effect effect, int position)
654
    {
655
    mEffects.apply(effect, position);
656
    }
657

    
658
///////////////////////////////////////////////////////////////////////////////////////////////////
659

    
660
  public void remove(long effectID)
661
    {
662
    mEffects.abortById(effectID);
663
    }
664

    
665
///////////////////////////////////////////////////////////////////////////////////////////////////
666

    
667
  public synchronized void solve()
668
    {
669
    for(int i=0; i<NUM_CUBITS; i++)
670
      {
671
      CUBITS[i].solve();
672
      mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
673
      }
674
    }
675

    
676
///////////////////////////////////////////////////////////////////////////////////////////////////
677

    
678
  public void resetAllTextureMaps()
679
    {
680
    final float ratioW = 1.0f/mNumTexCols;
681
    final float ratioH = 1.0f/mNumTexRows;
682
    int color, row, col;
683

    
684
    for(int cubit=0; cubit<NUM_CUBITS; cubit++)
685
      {
686
      final Static4D[] maps = new Static4D[NUM_CUBIT_FACES];
687

    
688
      for(int cubitface=0; cubitface<NUM_CUBIT_FACES; cubitface++)
689
        {
690
        color = getFaceColor(cubit,cubitface,mNumLayers);
691
        row = (mNumTexRows-1) - color/mNumTexCols;
692
        col = color%mNumTexCols;
693
        maps[cubitface] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
694
        }
695

    
696
      mMesh.setTextureMap(maps,NUM_CUBIT_FACES*cubit);
697
      }
698
    }
699

    
700
///////////////////////////////////////////////////////////////////////////////////////////////////
701

    
702
  public void setTextureMap(int cubit, int face, int newColor)
703
    {
704
    final float ratioW = 1.0f/mNumTexCols;
705
    final float ratioH = 1.0f/mNumTexRows;
706
    final Static4D[] maps = new Static4D[NUM_CUBIT_FACES];
707
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
708
    int col = newColor%mNumTexCols;
709

    
710
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
711
    mMesh.setTextureMap(maps,NUM_CUBIT_FACES*cubit);
712
    }
713

    
714
///////////////////////////////////////////////////////////////////////////////////////////////////
715

    
716
  public synchronized void beginNewRotation(int axis, int row )
717
    {
718
    if( axis<0 || axis>=ROTATION_AXIS.length )
719
      {
720
      android.util.Log.e("object", "invalid rotation axis: "+axis);
721
      return;
722
      }
723
    if( row<0 || row>=mNumLayers )
724
      {
725
      android.util.Log.e("object", "invalid rotation row: "+row);
726
      return;
727
      }
728

    
729
    mRotAxis     = axis;
730
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
731
    mRotationAngleStatic.set0(0.0f);
732
    mRotationAxis.set( ROTATION_AXIS[axis] );
733
    mRotationAngle.add(mRotationAngleStatic);
734
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis* ObjectList.MAX_OBJECT_SIZE) , -1);
735
    }
736

    
737
///////////////////////////////////////////////////////////////////////////////////////////////////
738

    
739
  public synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
740
    {
741
    if( wasRotateApplied() )
742
      {
743
      mRotAxis     = axis;
744
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
745

    
746
      mRotationAngleStatic.set0(0.0f);
747
      mRotationAxis.set( ROTATION_AXIS[axis] );
748
      mRotationAngle.setDuration(durationMillis);
749
      mRotationAngle.resetToBeginning();
750
      mRotationAngle.add(new Static1D(0));
751
      mRotationAngle.add(new Static1D(angle));
752
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis* ObjectList.MAX_OBJECT_SIZE) , -1);
753
      mRotateEffect.notifyWhenFinished(listener);
754

    
755
      return mRotateEffect.getID();
756
      }
757

    
758
    return 0;
759
    }
760

    
761
///////////////////////////////////////////////////////////////////////////////////////////////////
762

    
763
  public long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
764
    {
765
    if( wasRotateApplied() )
766
      {
767
      float angle = getAngle();
768
      mRotationAngleStatic.set0(angle);
769
      mRotationAngleFinal.set0(nearestAngleInDegrees);
770
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
771

    
772
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
773
      mRotationAngle.resetToBeginning();
774
      mRotationAngle.removeAll();
775
      mRotationAngle.add(mRotationAngleStatic);
776
      mRotationAngle.add(mRotationAngleMiddle);
777
      mRotationAngle.add(mRotationAngleFinal);
778
      mRotateEffect.notifyWhenFinished(listener);
779

    
780
      return mRotateEffect.getID();
781
      }
782

    
783
    return 0;
784
    }
785

    
786
///////////////////////////////////////////////////////////////////////////////////////////////////
787

    
788
  private float getAngle()
789
    {
790
    int pointNum = mRotationAngle.getNumPoints();
791

    
792
    if( pointNum>=1 )
793
      {
794
      return mRotationAngle.getPoint(pointNum-1).get0();
795
      }
796
    else
797
      {
798
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
799
      crashlytics.log("points in RotationAngle: "+pointNum);
800
      return 0;
801
      }
802
    }
803

    
804
///////////////////////////////////////////////////////////////////////////////////////////////////
805

    
806
  public synchronized void removeRotationNow()
807
    {
808
    float angle = getAngle();
809
    double nearestAngleInRadians = angle*Math.PI/180;
810
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
811
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
812
    float axisX = ROTATION_AXIS[mRotAxis].get0();
813
    float axisY = ROTATION_AXIS[mRotAxis].get1();
814
    float axisZ = ROTATION_AXIS[mRotAxis].get2();
815
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
816

    
817
    mRotationAngle.removeAll();
818
    mRotationAngleStatic.set0(0);
819

    
820
    for(int i=0; i<NUM_CUBITS; i++)
821
      if( belongsToRotation(i,mRotAxis,mRotRowBitmap) )
822
        {
823
        int index = CUBITS[i].removeRotationNow(quat);
824
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),index);
825
        }
826
    }
827

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

    
830
  public void initializeObject(int[][] moves)
831
    {
832
    solve();
833
    setupPosition(moves);
834
    }
835

    
836
///////////////////////////////////////////////////////////////////////////////////////////////////
837

    
838
  public int getCubit(float[] point3D)
839
    {
840
    float dist, minDist = Float.MAX_VALUE;
841
    int currentBest=-1;
842
    float multiplier = returnMultiplier();
843

    
844
    point3D[0] *= multiplier;
845
    point3D[1] *= multiplier;
846
    point3D[2] *= multiplier;
847

    
848
    for(int i=0; i<NUM_CUBITS; i++)
849
      {
850
      dist = CUBITS[i].getDistSquared(point3D);
851
      if( dist<minDist )
852
        {
853
        minDist = dist;
854
        currentBest = i;
855
        }
856
      }
857

    
858
    return currentBest;
859
    }
860

    
861
///////////////////////////////////////////////////////////////////////////////////////////////////
862

    
863
  public int computeNearestAngle(float angle, float speed)
864
    {
865
    final int NEAREST = 360/getBasicAngle();
866

    
867
    int tmp = (int)((angle+NEAREST/2)/NEAREST);
868
    if( angle< -(NEAREST*0.5) ) tmp-=1;
869

    
870
    if( tmp!=0 ) return NEAREST*tmp;
871

    
872
    return speed> 1.2f ? NEAREST*(angle>0 ? 1:-1) : 0;
873
    }
874

    
875
///////////////////////////////////////////////////////////////////////////////////////////////////
876

    
877
  public float getCameraDist()
878
    {
879
    return mCameraDist;
880
    }
881

    
882
///////////////////////////////////////////////////////////////////////////////////////////////////
883

    
884
  public int getNodeSize()
885
    {
886
    return mNodeSize;
887
    }
888

    
889
///////////////////////////////////////////////////////////////////////////////////////////////////
890

    
891
  public ObjectList getObjectList()
892
    {
893
    return mList;
894
    }
895

    
896
///////////////////////////////////////////////////////////////////////////////////////////////////
897

    
898
  abstract float getScreenRatio();
899
  abstract float[][] getCubitPositions(int numLayers);
900
  abstract Static4D[] getQuats();
901
  abstract int getNumFaces();
902
  abstract int getNumStickerTypes(int numLayers);
903
  abstract int getNumCubitFaces();
904
  abstract MeshBase createCubitMesh(int cubit, int numLayers);
905
  abstract void createFaceTexture(Canvas canvas, Paint paint, int face, int left, int top);
906
  abstract int getFaceColor(int cubit, int cubitface, int numLayers);
907
  abstract float returnMultiplier();
908
  abstract float[] getRowChances(int numLayers);
909
  abstract float[] getCuts(int numLayers);
910
  abstract boolean shouldResetTextureMaps();
911

    
912
  public abstract boolean isSolved();
913
  public abstract Static3D[] getRotationAxis();
914
  public abstract int getBasicAngle();
915
  public abstract String retObjectString();
916
  public abstract void randomizeNewScramble(int[][] scramble, Random rnd, int numScramble);
917
  public abstract int getObjectName(int numLayers);
918
  public abstract int getInventor(int numLayers);
919
  public abstract int getComplexity(int numLayers);
920
  }
(29-29/33)