Project

General

Profile

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

magiccube / src / main / java / org / distorted / objects / TwistyObject.java @ 43889e94

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 Static3D CENTER = new Static3D(0,0,0);
85
  private static final int POST_ROTATION_MILLISEC = 500;
86

    
87
  final Static4D[] QUATS;
88
  final Cubit[] CUBITS;
89
  final int NUM_FACES;
90
  final int NUM_TEXTURES;
91
  final int NUM_CUBITS;
92
  final int NUM_AXIS;
93

    
94
  private static float mInitScreenRatio;
95
  private static float mObjectScreenRatio = 1.0f;
96
  private static final float[] mTmp1 = new float[4];
97
  private static final float[] mTmp2 = new float[4];
98

    
99
  private final int mNumCubitFaces;
100
  private final Static3D[] mAxis;
101
  private final float[][] mCuts;
102
  private final int[] mNumCuts;
103
  private final int mNodeSize;
104
  private final float[][] mOrigPos;
105
  private final Static3D mNodeScale;
106
  private final Static4D mQuat;
107
  private final int mNumLayers, mRealSize;
108
  private final ObjectList mList;
109
  private final DistortedEffects mEffects;
110
  private final VertexEffectRotate mRotateEffect;
111
  private final Dynamic1D mRotationAngle;
112
  private final Static3D mRotationAxis;
113
  private final Static3D mObjectScale;
114
  private final int[] mQuatDebug;
115
  private final float mCameraDist;
116
  private final Static1D mRotationAngleStatic, mRotationAngleMiddle, mRotationAngleFinal;
117
  private final DistortedTexture mTexture;
118
  private int mNumTexRows, mNumTexCols;
119
  private int mRotRowBitmap;
120
  private int mRotAxis;
121
  private MeshBase mMesh;
122

    
123
///////////////////////////////////////////////////////////////////////////////////////////////////
124

    
125
  TwistyObject(int numLayers, int realSize, Static4D quat, DistortedTexture nodeTexture, MeshSquare nodeMesh,
126
               DistortedEffects nodeEffects, int[][] moves, ObjectList list, Resources res, int screenWidth)
127
    {
128
    super(nodeTexture,nodeEffects,nodeMesh);
129

    
130
    mNodeSize = screenWidth;
131

    
132
    resizeFBO(mNodeSize, (int)(NODE_RATIO*mNodeSize));
133

    
134
    mNumLayers = numLayers;
135
    mRealSize = realSize;
136
    mList = list;
137
    mOrigPos = getCubitPositions(mNumLayers);
138
    mAxis = getRotationAxis();
139
    mInitScreenRatio = getScreenRatio();
140
    mNumCubitFaces = getNumCubitFaces();
141

    
142
    mCuts = getCuts(mNumLayers);
143
    mNumCuts = new int[mAxis.length];
144
    if( mCuts==null ) for(int i=0; i<mAxis.length; i++) mNumCuts[i] = 0;
145
    else              for(int i=0; i<mAxis.length; i++) mNumCuts[i] = mCuts[i].length;
146

    
147
    QUATS = getQuats();
148
    NUM_CUBITS  = mOrigPos.length;
149
    NUM_FACES = getNumFaces();
150
    NUM_TEXTURES = getNumStickerTypes(mNumLayers)*NUM_FACES;
151
    NUM_AXIS = mAxis.length;
152

    
153
    mQuatDebug = new int[NUM_CUBITS];
154

    
155
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
156
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
157

    
158
    mNodeScale= new Static3D(1,NODE_RATIO,1);
159
    mQuat = quat;
160

    
161
    mRotationAngle= new Dynamic1D();
162
    mRotationAxis = new Static3D(1,0,0);
163
    mRotateEffect = new VertexEffectRotate(mRotationAngle, mRotationAxis, CENTER);
164

    
165
    mRotationAngleStatic = new Static1D(0);
166
    mRotationAngleMiddle = new Static1D(0);
167
    mRotationAngleFinal  = new Static1D(0);
168

    
169
    float scale  = mObjectScreenRatio*mInitScreenRatio*mNodeSize/mRealSize;
170
    mObjectScale = new Static3D(scale,scale,scale);
171
    MatrixEffectScale scaleEffect = new MatrixEffectScale(mObjectScale);
172
    MatrixEffectQuaternion quatEffect  = new MatrixEffectQuaternion(quat, CENTER);
173

    
174
    MatrixEffectScale nodeScaleEffect = new MatrixEffectScale(mNodeScale);
175
    nodeEffects.apply(nodeScaleEffect);
176

    
177
    mNumTexCols = NUM_STICKERS_IN_ROW;
178
    mNumTexRows = (NUM_TEXTURES+1)/NUM_STICKERS_IN_ROW;
179

    
180
    if( mNumTexCols*mNumTexRows < NUM_TEXTURES+1 ) mNumTexRows++;
181

    
182
    CUBITS = new Cubit[NUM_CUBITS];
183
    createMeshAndCubits(list,res);
184

    
185
    mTexture = new DistortedTexture();
186
    mEffects = new DistortedEffects();
187

    
188
    int num_quats = QUATS.length;
189
    for(int q=0; q<num_quats; q++)
190
      {
191
      VertexEffectQuaternion vq = new VertexEffectQuaternion(QUATS[q],CENTER);
192
      vq.setMeshAssociation(0,q);
193
      mEffects.apply(vq);
194
      }
195

    
196
    mEffects.apply(mRotateEffect);
197
    mEffects.apply(quatEffect);
198
    mEffects.apply(scaleEffect);
199

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

    
204
    attach( new DistortedNode(mTexture,mEffects,mMesh) );
205

    
206
    setupPosition(moves);
207

    
208
    float fov = list.getFOV();
209
    double halfFOV = fov * (Math.PI/360);
210
    mCameraDist = 0.5f*NODE_RATIO / (float)Math.tan(halfFOV);
211

    
212
    setProjection( fov, 0.1f);
213
    }
214

    
215
///////////////////////////////////////////////////////////////////////////////////////////////////
216

    
217
  private Static3D getPos(float[] origPos)
218
    {
219
    int len = origPos.length/3;
220
    float sumX = 0.0f;
221
    float sumY = 0.0f;
222
    float sumZ = 0.0f;
223

    
224
    for(int i=0; i<len; i++)
225
      {
226
      sumX += origPos[3*i  ];
227
      sumY += origPos[3*i+1];
228
      sumZ += origPos[3*i+2];
229
      }
230

    
231
    sumX /= len;
232
    sumY /= len;
233
    sumZ /= len;
234

    
235
    return new Static3D(sumX,sumY,sumZ);
236
    }
237

    
238
///////////////////////////////////////////////////////////////////////////////////////////////////
239

    
240
  private void createMeshAndCubits(ObjectList list, Resources res)
241
    {
242
    int sizeIndex = ObjectList.getSizeIndex(list.ordinal(),mNumLayers);
243
    int resourceID= list.getResourceIDs()[sizeIndex];
244

    
245
    if( resourceID!=0 )
246
      {
247
      InputStream is = res.openRawResource(resourceID);
248
      DataInputStream dos = new DataInputStream(is);
249
      mMesh = new MeshFile(dos);
250

    
251
      try
252
        {
253
        is.close();
254
        }
255
      catch(IOException e)
256
        {
257
        android.util.Log.e("meshFile", "Error closing InputStream: "+e.toString());
258
        }
259

    
260
      for(int i=0; i<NUM_CUBITS; i++)
261
        {
262
        CUBITS[i] = new Cubit(this,mOrigPos[i], NUM_AXIS);
263
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
264
        }
265

    
266
      if( shouldResetTextureMaps() ) resetAllTextureMaps();
267
      }
268
    else
269
      {
270
      MeshBase[] cubitMesh = new MeshBase[NUM_CUBITS];
271

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

    
281
      mMesh = new MeshJoined(cubitMesh);
282
      resetAllTextureMaps();
283
      }
284
    }
285

    
286
///////////////////////////////////////////////////////////////////////////////////////////////////
287

    
288
  public void setObjectRatio(float sizeChange)
289
    {
290
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
291

    
292
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
293
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
294

    
295
    float scale = mObjectScreenRatio*mInitScreenRatio*mNodeSize/mRealSize;
296
    mObjectScale.set(scale,scale,scale);
297
    }
298

    
299
///////////////////////////////////////////////////////////////////////////////////////////////////
300

    
301
  static float getObjectRatio()
302
    {
303
    return mObjectScreenRatio*mInitScreenRatio;
304
    }
305

    
306
///////////////////////////////////////////////////////////////////////////////////////////////////
307

    
308
  int computeRow(float[] pos, int axisIndex)
309
    {
310
    int ret=0;
311
    int len = pos.length / 3;
312
    Static3D axis = mAxis[axisIndex];
313
    float axisX = axis.get0();
314
    float axisY = axis.get1();
315
    float axisZ = axis.get2();
316
    float casted;
317

    
318
    for(int i=0; i<len; i++)
319
      {
320
      casted = pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ;
321
      ret |= computeSingleRow(axisIndex,casted);
322
      }
323

    
324
    return ret;
325
    }
326

    
327
///////////////////////////////////////////////////////////////////////////////////////////////////
328

    
329
  private int computeSingleRow(int axisIndex,float casted)
330
    {
331
    int num = mNumCuts[axisIndex];
332

    
333
    for(int i=0; i<num; i++)
334
      {
335
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
336
      }
337

    
338
    return (1<<num);
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 = mAxis[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[] basic = getBasicAngle();
381

    
382
      for(int[] move: moves)
383
        {
384
        axis     = move[0];
385
        rowBitmap= move[1];
386
        angle    = move[2]*(360/basic[axis]);
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
    if( minError< 0.1f )
456
      {
457
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
458
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
459
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
460
      }
461
    }
462

    
463
///////////////////////////////////////////////////////////////////////////////////////////////////
464
// remember about the double cover or unit quaternions!
465

    
466
  int mulQuat(int q1, int q2)
467
    {
468
    Static4D result = RubikSurfaceView.quatMultiply(QUATS[q1],QUATS[q2]);
469

    
470
    float rX = result.get0();
471
    float rY = result.get1();
472
    float rZ = result.get2();
473
    float rW = result.get3();
474

    
475
    final float MAX_ERROR = 0.1f;
476
    float dX,dY,dZ,dW;
477

    
478
    for(int i=0; i<QUATS.length; i++)
479
      {
480
      dX = QUATS[i].get0() - rX;
481
      dY = QUATS[i].get1() - rY;
482
      dZ = QUATS[i].get2() - rZ;
483
      dW = QUATS[i].get3() - rW;
484

    
485
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
486
          dY<MAX_ERROR && dY>-MAX_ERROR &&
487
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
488
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
489

    
490
      dX = QUATS[i].get0() + rX;
491
      dY = QUATS[i].get1() + rY;
492
      dZ = QUATS[i].get2() + rZ;
493
      dW = QUATS[i].get3() + rW;
494

    
495
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
496
          dY<MAX_ERROR && dY>-MAX_ERROR &&
497
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
498
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
499
      }
500

    
501
    return -1;
502
    }
503

    
504
///////////////////////////////////////////////////////////////////////////////////////////////////
505
// return if the Cubit, when rotated with its own mQuatScramble, would have looked any different
506
// then if it were rotated by quaternion 'quat'.
507
// No it is not so simple as the quats need to be the same - imagine a 4x4x4 cube where the two
508
// middle squares get interchanged. No visible difference!
509
//
510
// So: this is true iff the cubit
511
// a) is a corner or edge and the quaternions are the same
512
// b) is inside one of the faces and after rotations by both quats it ends up on the same face.
513

    
514
  boolean thereIsVisibleDifference(Cubit cubit, int quatIndex)
515
    {
516
    if ( cubit.mQuatIndex == quatIndex ) return false;
517

    
518
    int belongsToHowManyFaces = 0;
519
    int bitmap = (1<<(getNumLayers()-1)) + 1;
520

    
521
    for(int i = 0; i< NUM_AXIS; i++)
522
      {
523
      if( (cubit.mRotationRow[i] & bitmap) != 0 ) belongsToHowManyFaces++;
524
      }
525

    
526
    switch(belongsToHowManyFaces)
527
      {
528
      case 0 : return false;  // 'inside' cubit that does not lie on any face
529
      case 1 :                // cubit that lies inside one of the faces
530
               float[] orig   = cubit.getOrigPosition();
531
               Static4D quat1 = QUATS[quatIndex];
532
               Static4D quat2 = QUATS[cubit.mQuatIndex];
533

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

    
538
               rotated1.get(mTmp1, 0, 0, 0);
539
               rotated2.get(mTmp2, 0, 0, 0);
540

    
541
               for(int i = 0; i< NUM_AXIS; i++)
542
                 {
543
                 if( (computeRow(mTmp1,i) & computeRow(mTmp2,i) & bitmap) != 0 ) return false;
544
                 }
545
               return true;
546

    
547
      default: return true;  // edge or corner
548
      }
549
    }
550

    
551
///////////////////////////////////////////////////////////////////////////////////////////////////
552
// create StickerCoord and FaceTransform data structures
553

    
554
  void createFaceDataStructures(double[][][] verts, int[][][] indices)
555
    {
556
    int numCubitTypes = verts.length;
557
    FactoryCubit factory = FactoryCubit.getInstance();
558
    factory.clear();
559

    
560
    for(int cubit=0; cubit<numCubitTypes; cubit++)
561
      {
562
      double[][] vertices = verts[cubit];
563
      int[][] vertIndices = indices[cubit];
564
      factory.createNewFaceTransform(vertices,vertIndices);
565
      }
566

    
567
    factory.printFaceTransform();
568
    factory.printStickerCoords();
569
    }
570

    
571
///////////////////////////////////////////////////////////////////////////////////////////////////
572
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
573

    
574
  public void createTexture()
575
    {
576
    Bitmap bitmap;
577

    
578
    Paint paint = new Paint();
579
    bitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_8888);
580
    Canvas canvas = new Canvas(bitmap);
581

    
582
    paint.setAntiAlias(true);
583
    paint.setTextAlign(Paint.Align.CENTER);
584
    paint.setStyle(Paint.Style.FILL);
585

    
586
    paint.setColor(COLOR_BLACK);
587
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
588

    
589
    int tex = 0;
590

    
591
    for(int row=0; row<mNumTexRows; row++)
592
      for(int col=0; col<mNumTexCols; col++)
593
        {
594
        if( tex>=NUM_TEXTURES ) break;
595
        createFaceTexture(canvas, paint, tex, col*TEXTURE_HEIGHT, row*TEXTURE_HEIGHT);
596
        tex++;
597
        }
598

    
599
    if( !mTexture.setTexture(bitmap) )
600
      {
601
      int max = DistortedLibrary.getMaxTextureSize();
602
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
603
      crashlytics.log("failed to set texture of size "+bitmap.getWidth()+"x"+bitmap.getHeight()+" max is "+max);
604
      }
605
    }
606

    
607
///////////////////////////////////////////////////////////////////////////////////////////////////
608

    
609
  public int getNumLayers()
610
    {
611
    return mNumLayers;
612
    }
613

    
614
///////////////////////////////////////////////////////////////////////////////////////////////////
615

    
616
  public void continueRotation(float angleInDegrees)
617
    {
618
    mRotationAngleStatic.set0(angleInDegrees);
619
    }
620

    
621
///////////////////////////////////////////////////////////////////////////////////////////////////
622

    
623
  public Static4D getRotationQuat()
624
      {
625
      return mQuat;
626
      }
627

    
628
///////////////////////////////////////////////////////////////////////////////////////////////////
629

    
630
  public void recomputeScaleFactor(int scrWidth)
631
    {
632
    mNodeScale.set(scrWidth,NODE_RATIO*scrWidth,scrWidth);
633
    }
634

    
635
///////////////////////////////////////////////////////////////////////////////////////////////////
636

    
637
  public void savePreferences(SharedPreferences.Editor editor)
638
    {
639
    for(int i=0; i<NUM_CUBITS; i++) CUBITS[i].savePreferences(editor);
640
    }
641

    
642
///////////////////////////////////////////////////////////////////////////////////////////////////
643

    
644
  public synchronized void restorePreferences(SharedPreferences preferences)
645
    {
646
    boolean error = false;
647

    
648
    for(int i=0; i<NUM_CUBITS; i++)
649
      {
650
      mQuatDebug[i] = CUBITS[i].restorePreferences(preferences);
651

    
652
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<QUATS.length)
653
        {
654
        CUBITS[i].modifyCurrentPosition(QUATS[mQuatDebug[i]]);
655
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),mQuatDebug[i]);
656
        }
657
      else
658
        {
659
        error = true;
660
        }
661
      }
662

    
663
    if( error )
664
      {
665
      for(int i=0; i<NUM_CUBITS; i++)
666
        {
667
        CUBITS[i].solve();
668
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),0);
669
        }
670
      recordQuatsState("Failed to restorePreferences");
671
      }
672
    }
673

    
674
///////////////////////////////////////////////////////////////////////////////////////////////////
675

    
676
  public void recordQuatsState(String message)
677
    {
678
    StringBuilder quats = new StringBuilder();
679

    
680
    for(int j=0; j<NUM_CUBITS; j++)
681
      {
682
      quats.append(mQuatDebug[j]);
683
      quats.append(" ");
684
      }
685

    
686
    if( BuildConfig.DEBUG )
687
      {
688
      android.util.Log.e("quats" , quats.toString());
689
      android.util.Log.e("object", mList.name()+"_"+mNumLayers);
690
      }
691
    else
692
      {
693
      Exception ex = new Exception(message);
694
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
695
      crashlytics.setCustomKey("quats" , quats.toString());
696
      crashlytics.setCustomKey("object", mList.name()+"_"+mNumLayers );
697
      crashlytics.recordException(ex);
698
      }
699
    }
700

    
701
///////////////////////////////////////////////////////////////////////////////////////////////////
702

    
703
  public void releaseResources()
704
    {
705
    mTexture.markForDeletion();
706
    mMesh.markForDeletion();
707
    mEffects.markForDeletion();
708

    
709
    for(int j=0; j<NUM_CUBITS; j++)
710
      {
711
      CUBITS[j].releaseResources();
712
      }
713
    }
714

    
715
///////////////////////////////////////////////////////////////////////////////////////////////////
716

    
717
  public void apply(Effect effect, int position)
718
    {
719
    mEffects.apply(effect, position);
720
    }
721

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

    
724
  public void remove(long effectID)
725
    {
726
    mEffects.abortById(effectID);
727
    }
728

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

    
731
  public synchronized void solve()
732
    {
733
    for(int i=0; i<NUM_CUBITS; i++)
734
      {
735
      CUBITS[i].solve();
736
      mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
737
      }
738
    }
739

    
740
///////////////////////////////////////////////////////////////////////////////////////////////////
741

    
742
  public void resetAllTextureMaps()
743
    {
744
    final float ratioW = 1.0f/mNumTexCols;
745
    final float ratioH = 1.0f/mNumTexRows;
746
    int color, row, col;
747

    
748
    for(int cubit=0; cubit<NUM_CUBITS; cubit++)
749
      {
750
      final Static4D[] maps = new Static4D[mNumCubitFaces];
751

    
752
      for(int cubitface=0; cubitface<mNumCubitFaces; cubitface++)
753
        {
754
        color = getFaceColor(cubit,cubitface,mNumLayers);
755
        row = (mNumTexRows-1) - color/mNumTexCols;
756
        col = color%mNumTexCols;
757
        maps[cubitface] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
758
        }
759

    
760
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
761
      }
762
    }
763

    
764
///////////////////////////////////////////////////////////////////////////////////////////////////
765

    
766
  public void setTextureMap(int cubit, int face, int newColor)
767
    {
768
    final float ratioW = 1.0f/mNumTexCols;
769
    final float ratioH = 1.0f/mNumTexRows;
770
    final Static4D[] maps = new Static4D[mNumCubitFaces];
771
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
772
    int col = newColor%mNumTexCols;
773

    
774
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
775
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
776
    }
777

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

    
780
  public synchronized void beginNewRotation(int axis, int row )
781
    {
782
    if( axis<0 || axis>=NUM_AXIS )
783
      {
784
      android.util.Log.e("object", "invalid rotation axis: "+axis);
785
      return;
786
      }
787
    if( row<0 || row>=mNumLayers )
788
      {
789
      android.util.Log.e("object", "invalid rotation row: "+row);
790
      return;
791
      }
792

    
793
    mRotAxis     = axis;
794
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
795
    mRotationAngleStatic.set0(0.0f);
796
    mRotationAxis.set( mAxis[axis] );
797
    mRotationAngle.add(mRotationAngleStatic);
798
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis* ObjectList.MAX_OBJECT_SIZE) , -1);
799
    }
800

    
801
///////////////////////////////////////////////////////////////////////////////////////////////////
802

    
803
  public synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
804
    {
805
    if( wasRotateApplied() )
806
      {
807
      mRotAxis     = axis;
808
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
809

    
810
      mRotationAngleStatic.set0(0.0f);
811
      mRotationAxis.set( mAxis[axis] );
812
      mRotationAngle.setDuration(durationMillis);
813
      mRotationAngle.resetToBeginning();
814
      mRotationAngle.add(new Static1D(0));
815
      mRotationAngle.add(new Static1D(angle));
816
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis* ObjectList.MAX_OBJECT_SIZE) , -1);
817
      mRotateEffect.notifyWhenFinished(listener);
818

    
819
      return mRotateEffect.getID();
820
      }
821

    
822
    return 0;
823
    }
824

    
825
///////////////////////////////////////////////////////////////////////////////////////////////////
826

    
827
  public long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
828
    {
829
    if( wasRotateApplied() )
830
      {
831
      float angle = getAngle();
832
      mRotationAngleStatic.set0(angle);
833
      mRotationAngleFinal.set0(nearestAngleInDegrees);
834
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
835

    
836
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
837
      mRotationAngle.resetToBeginning();
838
      mRotationAngle.removeAll();
839
      mRotationAngle.add(mRotationAngleStatic);
840
      mRotationAngle.add(mRotationAngleMiddle);
841
      mRotationAngle.add(mRotationAngleFinal);
842
      mRotateEffect.notifyWhenFinished(listener);
843

    
844
      return mRotateEffect.getID();
845
      }
846

    
847
    return 0;
848
    }
849

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

    
852
  private float getAngle()
853
    {
854
    int pointNum = mRotationAngle.getNumPoints();
855

    
856
    if( pointNum>=1 )
857
      {
858
      return mRotationAngle.getPoint(pointNum-1).get0();
859
      }
860
    else
861
      {
862
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
863
      crashlytics.log("points in RotationAngle: "+pointNum);
864
      return 0;
865
      }
866
    }
867

    
868
///////////////////////////////////////////////////////////////////////////////////////////////////
869

    
870
  public synchronized void removeRotationNow()
871
    {
872
    float angle = getAngle();
873
    double nearestAngleInRadians = angle*Math.PI/180;
874
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
875
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
876
    float axisX = mAxis[mRotAxis].get0();
877
    float axisY = mAxis[mRotAxis].get1();
878
    float axisZ = mAxis[mRotAxis].get2();
879
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
880

    
881
    mRotationAngle.removeAll();
882
    mRotationAngleStatic.set0(0);
883

    
884
    for(int i=0; i<NUM_CUBITS; i++)
885
      if( belongsToRotation(i,mRotAxis,mRotRowBitmap) )
886
        {
887
        int index = CUBITS[i].removeRotationNow(quat);
888
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),index);
889
        }
890
    }
891

    
892
///////////////////////////////////////////////////////////////////////////////////////////////////
893

    
894
  public void initializeObject(int[][] moves)
895
    {
896
    solve();
897
    setupPosition(moves);
898
    }
899

    
900
///////////////////////////////////////////////////////////////////////////////////////////////////
901

    
902
  public int getCubit(float[] point3D)
903
    {
904
    float dist, minDist = Float.MAX_VALUE;
905
    int currentBest=-1;
906
    float multiplier = returnMultiplier();
907

    
908
    point3D[0] *= multiplier;
909
    point3D[1] *= multiplier;
910
    point3D[2] *= multiplier;
911

    
912
    for(int i=0; i<NUM_CUBITS; i++)
913
      {
914
      dist = CUBITS[i].getDistSquared(point3D);
915
      if( dist<minDist )
916
        {
917
        minDist = dist;
918
        currentBest = i;
919
        }
920
      }
921

    
922
    return currentBest;
923
    }
924

    
925
///////////////////////////////////////////////////////////////////////////////////////////////////
926

    
927
  public int computeNearestAngle(int axis, float angle, float speed)
928
    {
929
    final int NEAREST = 360/getBasicAngle()[axis];
930

    
931
    int tmp = (int)((angle+NEAREST/2)/NEAREST);
932
    if( angle< -(NEAREST*0.5) ) tmp-=1;
933

    
934
    if( tmp!=0 ) return NEAREST*tmp;
935

    
936
    return speed> 1.2f ? NEAREST*(angle>0 ? 1:-1) : 0;
937
    }
938

    
939
///////////////////////////////////////////////////////////////////////////////////////////////////
940

    
941
  public float getCameraDist()
942
    {
943
    return mCameraDist;
944
    }
945

    
946
///////////////////////////////////////////////////////////////////////////////////////////////////
947

    
948
  public int getNodeSize()
949
    {
950
    return mNodeSize;
951
    }
952

    
953
///////////////////////////////////////////////////////////////////////////////////////////////////
954

    
955
  public ObjectList getObjectList()
956
    {
957
    return mList;
958
    }
959

    
960
///////////////////////////////////////////////////////////////////////////////////////////////////
961

    
962
  abstract float getScreenRatio();
963
  abstract float[][] getCubitPositions(int numLayers);
964
  abstract Static4D[] getQuats();
965
  abstract int getNumFaces();
966
  abstract int getNumStickerTypes(int numLayers);
967
  abstract int getNumCubitFaces();
968
  abstract MeshBase createCubitMesh(int cubit, int numLayers);
969
  abstract void createFaceTexture(Canvas canvas, Paint paint, int face, int left, int top);
970
  abstract int getFaceColor(int cubit, int cubitface, int numLayers);
971
  abstract float returnMultiplier();
972
  abstract float[][] getCuts(int numLayers);
973
  abstract boolean shouldResetTextureMaps();
974
  abstract Static3D[] getRotationAxis();
975

    
976
  public abstract boolean isSolved();
977
  public abstract int[] getBasicAngle();
978
  public abstract String retObjectString();
979
  public abstract void randomizeNewScramble(int[][] scramble, Random rnd, int numScramble);
980
  public abstract int getObjectName(int numLayers);
981
  public abstract int getInventor(int numLayers);
982
  public abstract int getComplexity(int numLayers);
983
  }
(31-31/37)