Project

General

Profile

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

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

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

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

    
58
///////////////////////////////////////////////////////////////////////////////////////////////////
59

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

    
72
  public static final int TEXTURE_HEIGHT = 256;
73
  static final int NUM_STICKERS_IN_ROW = 4;
74

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

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

    
84
  private static final boolean mCreateFromDMesh = false;
85

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

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

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

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

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

    
129
///////////////////////////////////////////////////////////////////////////////////////////////////
130

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

    
136
    mNodeSize = screenWidth;
137

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

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

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

    
156
    mQuatDebug = new int[NUM_CUBITS];
157

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

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

    
164
    mRowChances = getRowChances(mNumLayers);
165

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

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

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

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

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

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

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

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

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

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

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

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

    
211
    setupPosition(moves);
212

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

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

    
220
///////////////////////////////////////////////////////////////////////////////////////////////////
221

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

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

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

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

    
243
///////////////////////////////////////////////////////////////////////////////////////////////////
244

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

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

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

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

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

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

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

    
291
///////////////////////////////////////////////////////////////////////////////////////////////////
292

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

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

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

    
304
///////////////////////////////////////////////////////////////////////////////////////////////////
305

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

    
311
///////////////////////////////////////////////////////////////////////////////////////////////////
312

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

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

    
327
    return ret;
328
    }
329

    
330
///////////////////////////////////////////////////////////////////////////////////////////////////
331

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

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

    
342
///////////////////////////////////////////////////////////////////////////////////////////////////
343

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

    
349
///////////////////////////////////////////////////////////////////////////////////////////////////
350

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

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

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

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

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

    
373
///////////////////////////////////////////////////////////////////////////////////////////////////
374

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

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

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

    
400
///////////////////////////////////////////////////////////////////////////////////////////////////
401

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

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

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

    
412
///////////////////////////////////////////////////////////////////////////////////////////////////
413
// normal, not bandaged, object.
414

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

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

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

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

    
433
    float xo,yo,zo;
434

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
508
///////////////////////////////////////////////////////////////////////////////////////////////////
509
// create StickerCoord and FaceTransform data structures
510

    
511
  void createFaceDataStructures()
512
    {
513
    int numCubitTypes = getNumCubitTypes(mNumLayers);
514
    FactoryCubit factory = FactoryCubit.getInstance();
515
    factory.clear();
516

    
517
    for(int cubit=0; cubit<numCubitTypes; cubit++)
518
      {
519
      double[][] vertices = getVertices(cubit);
520
      int[][] vertIndices = getVertIndexes(cubit);
521

    
522
      factory.createNewFaceTransform(vertices,vertIndices);
523
      factory.printFaceTransform();
524
      }
525

    
526
    factory.printStickerCoords();
527
    }
528

    
529
///////////////////////////////////////////////////////////////////////////////////////////////////
530
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
531

    
532
  public void createTexture()
533
    {
534
    Bitmap bitmap;
535

    
536
    Paint paint = new Paint();
537
    bitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_8888);
538
    Canvas canvas = new Canvas(bitmap);
539

    
540
    paint.setAntiAlias(true);
541
    paint.setTextAlign(Paint.Align.CENTER);
542
    paint.setStyle(Paint.Style.FILL);
543

    
544
    paint.setColor(COLOR_BLACK);
545
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
546

    
547
    int tex = 0;
548

    
549
    for(int row=0; row<mNumTexRows; row++)
550
      for(int col=0; col<mNumTexCols; col++)
551
        {
552
        if( tex>=NUM_TEXTURES ) break;
553
        createFaceTexture(canvas, paint, tex, col*TEXTURE_HEIGHT, row*TEXTURE_HEIGHT);
554
        tex++;
555
        }
556

    
557
    if( !mTexture.setTexture(bitmap) )
558
      {
559
      int max = DistortedLibrary.getMaxTextureSize();
560
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
561
      crashlytics.log("failed to set texture of size "+bitmap.getWidth()+"x"+bitmap.getHeight()+" max is "+max);
562
      }
563
    }
564

    
565
///////////////////////////////////////////////////////////////////////////////////////////////////
566

    
567
  public int getNumLayers()
568
    {
569
    return mNumLayers;
570
    }
571

    
572
///////////////////////////////////////////////////////////////////////////////////////////////////
573

    
574
  public void continueRotation(float angleInDegrees)
575
    {
576
    mRotationAngleStatic.set0(angleInDegrees);
577
    }
578

    
579
///////////////////////////////////////////////////////////////////////////////////////////////////
580

    
581
  public Static4D getRotationQuat()
582
      {
583
      return mQuat;
584
      }
585

    
586
///////////////////////////////////////////////////////////////////////////////////////////////////
587

    
588
  public void recomputeScaleFactor(int scrWidth)
589
    {
590
    mNodeScale.set(scrWidth,NODE_RATIO*scrWidth,scrWidth);
591
    }
592

    
593
///////////////////////////////////////////////////////////////////////////////////////////////////
594

    
595
  public void savePreferences(SharedPreferences.Editor editor)
596
    {
597
    for(int i=0; i<NUM_CUBITS; i++) CUBITS[i].savePreferences(editor);
598
    }
599

    
600
///////////////////////////////////////////////////////////////////////////////////////////////////
601

    
602
  public synchronized void restorePreferences(SharedPreferences preferences)
603
    {
604
    boolean error = false;
605

    
606
    for(int i=0; i<NUM_CUBITS; i++)
607
      {
608
      mQuatDebug[i] = CUBITS[i].restorePreferences(preferences);
609

    
610
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<QUATS.length)
611
        {
612
        CUBITS[i].modifyCurrentPosition(QUATS[mQuatDebug[i]]);
613
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),mQuatDebug[i]);
614
        }
615
      else
616
        {
617
        error = true;
618
        }
619
      }
620

    
621
    if( error )
622
      {
623
      for(int i=0; i<NUM_CUBITS; i++)
624
        {
625
        CUBITS[i].solve();
626
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),0);
627
        }
628
      recordQuatsState("Failed to restorePreferences");
629
      }
630
    }
631

    
632
///////////////////////////////////////////////////////////////////////////////////////////////////
633

    
634
  public void recordQuatsState(String message)
635
    {
636
    StringBuilder quats = new StringBuilder();
637

    
638
    for(int j=0; j<NUM_CUBITS; j++)
639
      {
640
      quats.append(mQuatDebug[j]);
641
      quats.append(" ");
642
      }
643

    
644
    if( BuildConfig.DEBUG )
645
      {
646
      android.util.Log.e("quats" , quats.toString());
647
      android.util.Log.e("object", mList.name()+"_"+mNumLayers);
648
      }
649
    else
650
      {
651
      Exception ex = new Exception(message);
652
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
653
      crashlytics.setCustomKey("quats" , quats.toString());
654
      crashlytics.setCustomKey("object", mList.name()+"_"+mNumLayers );
655
      crashlytics.recordException(ex);
656
      }
657
    }
658

    
659
///////////////////////////////////////////////////////////////////////////////////////////////////
660

    
661
  public void releaseResources()
662
    {
663
    mTexture.markForDeletion();
664
    mMesh.markForDeletion();
665
    mEffects.markForDeletion();
666

    
667
    for(int j=0; j<NUM_CUBITS; j++)
668
      {
669
      CUBITS[j].releaseResources();
670
      }
671
    }
672

    
673
///////////////////////////////////////////////////////////////////////////////////////////////////
674

    
675
  public void apply(Effect effect, int position)
676
    {
677
    mEffects.apply(effect, position);
678
    }
679

    
680
///////////////////////////////////////////////////////////////////////////////////////////////////
681

    
682
  public void remove(long effectID)
683
    {
684
    mEffects.abortById(effectID);
685
    }
686

    
687
///////////////////////////////////////////////////////////////////////////////////////////////////
688

    
689
  public synchronized void solve()
690
    {
691
    for(int i=0; i<NUM_CUBITS; i++)
692
      {
693
      CUBITS[i].solve();
694
      mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
695
      }
696
    }
697

    
698
///////////////////////////////////////////////////////////////////////////////////////////////////
699

    
700
  public void resetAllTextureMaps()
701
    {
702
    final float ratioW = 1.0f/mNumTexCols;
703
    final float ratioH = 1.0f/mNumTexRows;
704
    int color, row, col;
705

    
706
    for(int cubit=0; cubit<NUM_CUBITS; cubit++)
707
      {
708
      final Static4D[] maps = new Static4D[NUM_CUBIT_FACES];
709

    
710
      for(int cubitface=0; cubitface<NUM_CUBIT_FACES; cubitface++)
711
        {
712
        color = getFaceColor(cubit,cubitface,mNumLayers);
713
        row = (mNumTexRows-1) - color/mNumTexCols;
714
        col = color%mNumTexCols;
715
        maps[cubitface] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
716
        }
717

    
718
      mMesh.setTextureMap(maps,NUM_CUBIT_FACES*cubit);
719
      }
720
    }
721

    
722
///////////////////////////////////////////////////////////////////////////////////////////////////
723

    
724
  public void setTextureMap(int cubit, int face, int newColor)
725
    {
726
    final float ratioW = 1.0f/mNumTexCols;
727
    final float ratioH = 1.0f/mNumTexRows;
728
    final Static4D[] maps = new Static4D[NUM_CUBIT_FACES];
729
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
730
    int col = newColor%mNumTexCols;
731

    
732
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
733
    mMesh.setTextureMap(maps,NUM_CUBIT_FACES*cubit);
734
    }
735

    
736
///////////////////////////////////////////////////////////////////////////////////////////////////
737

    
738
  public synchronized void beginNewRotation(int axis, int row )
739
    {
740
    if( axis<0 || axis>=ROTATION_AXIS.length )
741
      {
742
      android.util.Log.e("object", "invalid rotation axis: "+axis);
743
      return;
744
      }
745
    if( row<0 || row>=mNumLayers )
746
      {
747
      android.util.Log.e("object", "invalid rotation row: "+row);
748
      return;
749
      }
750

    
751
    mRotAxis     = axis;
752
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
753
    mRotationAngleStatic.set0(0.0f);
754
    mRotationAxis.set( ROTATION_AXIS[axis] );
755
    mRotationAngle.add(mRotationAngleStatic);
756
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis* ObjectList.MAX_OBJECT_SIZE) , -1);
757
    }
758

    
759
///////////////////////////////////////////////////////////////////////////////////////////////////
760

    
761
  public synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
762
    {
763
    if( wasRotateApplied() )
764
      {
765
      mRotAxis     = axis;
766
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
767

    
768
      mRotationAngleStatic.set0(0.0f);
769
      mRotationAxis.set( ROTATION_AXIS[axis] );
770
      mRotationAngle.setDuration(durationMillis);
771
      mRotationAngle.resetToBeginning();
772
      mRotationAngle.add(new Static1D(0));
773
      mRotationAngle.add(new Static1D(angle));
774
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis* ObjectList.MAX_OBJECT_SIZE) , -1);
775
      mRotateEffect.notifyWhenFinished(listener);
776

    
777
      return mRotateEffect.getID();
778
      }
779

    
780
    return 0;
781
    }
782

    
783
///////////////////////////////////////////////////////////////////////////////////////////////////
784

    
785
  public long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
786
    {
787
    if( wasRotateApplied() )
788
      {
789
      float angle = getAngle();
790
      mRotationAngleStatic.set0(angle);
791
      mRotationAngleFinal.set0(nearestAngleInDegrees);
792
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
793

    
794
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
795
      mRotationAngle.resetToBeginning();
796
      mRotationAngle.removeAll();
797
      mRotationAngle.add(mRotationAngleStatic);
798
      mRotationAngle.add(mRotationAngleMiddle);
799
      mRotationAngle.add(mRotationAngleFinal);
800
      mRotateEffect.notifyWhenFinished(listener);
801

    
802
      return mRotateEffect.getID();
803
      }
804

    
805
    return 0;
806
    }
807

    
808
///////////////////////////////////////////////////////////////////////////////////////////////////
809

    
810
  private float getAngle()
811
    {
812
    int pointNum = mRotationAngle.getNumPoints();
813

    
814
    if( pointNum>=1 )
815
      {
816
      return mRotationAngle.getPoint(pointNum-1).get0();
817
      }
818
    else
819
      {
820
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
821
      crashlytics.log("points in RotationAngle: "+pointNum);
822
      return 0;
823
      }
824
    }
825

    
826
///////////////////////////////////////////////////////////////////////////////////////////////////
827

    
828
  public synchronized void removeRotationNow()
829
    {
830
    float angle = getAngle();
831
    double nearestAngleInRadians = angle*Math.PI/180;
832
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
833
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
834
    float axisX = ROTATION_AXIS[mRotAxis].get0();
835
    float axisY = ROTATION_AXIS[mRotAxis].get1();
836
    float axisZ = ROTATION_AXIS[mRotAxis].get2();
837
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
838

    
839
    mRotationAngle.removeAll();
840
    mRotationAngleStatic.set0(0);
841

    
842
    for(int i=0; i<NUM_CUBITS; i++)
843
      if( belongsToRotation(i,mRotAxis,mRotRowBitmap) )
844
        {
845
        int index = CUBITS[i].removeRotationNow(quat);
846
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),index);
847
        }
848
    }
849

    
850
///////////////////////////////////////////////////////////////////////////////////////////////////
851

    
852
  public void initializeObject(int[][] moves)
853
    {
854
    solve();
855
    setupPosition(moves);
856
    }
857

    
858
///////////////////////////////////////////////////////////////////////////////////////////////////
859

    
860
  public int getCubit(float[] point3D)
861
    {
862
    float dist, minDist = Float.MAX_VALUE;
863
    int currentBest=-1;
864
    float multiplier = returnMultiplier();
865

    
866
    point3D[0] *= multiplier;
867
    point3D[1] *= multiplier;
868
    point3D[2] *= multiplier;
869

    
870
    for(int i=0; i<NUM_CUBITS; i++)
871
      {
872
      dist = CUBITS[i].getDistSquared(point3D);
873
      if( dist<minDist )
874
        {
875
        minDist = dist;
876
        currentBest = i;
877
        }
878
      }
879

    
880
    return currentBest;
881
    }
882

    
883
///////////////////////////////////////////////////////////////////////////////////////////////////
884

    
885
  public int computeNearestAngle(float angle, float speed)
886
    {
887
    final int NEAREST = 360/getBasicAngle();
888

    
889
    int tmp = (int)((angle+NEAREST/2)/NEAREST);
890
    if( angle< -(NEAREST*0.5) ) tmp-=1;
891

    
892
    if( tmp!=0 ) return NEAREST*tmp;
893

    
894
    return speed> 1.2f ? NEAREST*(angle>0 ? 1:-1) : 0;
895
    }
896

    
897
///////////////////////////////////////////////////////////////////////////////////////////////////
898

    
899
  public float getCameraDist()
900
    {
901
    return mCameraDist;
902
    }
903

    
904
///////////////////////////////////////////////////////////////////////////////////////////////////
905

    
906
  public int getNodeSize()
907
    {
908
    return mNodeSize;
909
    }
910

    
911
///////////////////////////////////////////////////////////////////////////////////////////////////
912

    
913
  public ObjectList getObjectList()
914
    {
915
    return mList;
916
    }
917

    
918
///////////////////////////////////////////////////////////////////////////////////////////////////
919

    
920
  abstract float getScreenRatio();
921
  abstract float[][] getCubitPositions(int numLayers);
922
  abstract Static4D[] getQuats();
923
  abstract int getNumFaces();
924
  abstract int getNumStickerTypes(int numLayers);
925
  abstract int getNumCubitFaces();
926
  abstract MeshBase createCubitMesh(int cubit, int numLayers);
927
  abstract void createFaceTexture(Canvas canvas, Paint paint, int face, int left, int top);
928
  abstract int getFaceColor(int cubit, int cubitface, int numLayers);
929
  abstract float returnMultiplier();
930
  abstract float[] getRowChances(int numLayers);
931
  abstract float[] getCuts(int numLayers);
932
  abstract boolean shouldResetTextureMaps();
933
  abstract double[][] getVertices(int cubitType);
934
  abstract int[][] getVertIndexes(int cubitType);
935
  abstract int getNumCubitTypes(int numLayers);
936

    
937
  public abstract boolean isSolved();
938
  public abstract Static3D[] getRotationAxis();
939
  public abstract int getBasicAngle();
940
  public abstract String retObjectString();
941
  public abstract void randomizeNewScramble(int[][] scramble, Random rnd, int numScramble);
942
  public abstract int getObjectName(int numLayers);
943
  public abstract int getInventor(int numLayers);
944
  public abstract int getComplexity(int numLayers);
945
  }
(29-29/33)