Project

General

Profile

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

magiccube / src / main / java / org / distorted / objects / TwistyObject.java @ 47d98cd5

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

    
55
import java.io.DataInputStream;
56
import java.io.IOException;
57
import java.io.InputStream;
58
import java.util.Random;
59

    
60
///////////////////////////////////////////////////////////////////////////////////////////////////
61

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

    
74
  public static final int TEXTURE_HEIGHT = 256;
75
  static final int NUM_STICKERS_IN_ROW = 4;
76

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

    
82
  private static final float NODE_RATIO = 1.40f;
83
  private static final float MAX_SIZE_CHANGE = 1.35f;
84
  private static final float MIN_SIZE_CHANGE = 0.75f;
85

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

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

    
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 final float mInitScreenRatio;
119
  private float mObjectScreenRatio;
120
  private int mNumTexRows, mNumTexCols;
121
  private int mRotRowBitmap;
122
  private int mRotAxis;
123
  private MeshBase mMesh;
124

    
125
///////////////////////////////////////////////////////////////////////////////////////////////////
126

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

    
132
    mNodeSize = screenWidth;
133

    
134
    resizeFBO(mNodeSize, (int)(NODE_RATIO*mNodeSize));
135

    
136
    mNumLayers = numLayers;
137
    mRealSize = realSize;
138
    mList = list;
139
    mOrigPos = getCubitPositions(mNumLayers);
140
    mAxis = getRotationAxis();
141
    mInitScreenRatio = getScreenRatio();
142
    mObjectScreenRatio = 1.0f;
143
    mNumCubitFaces = getNumCubitFaces();
144

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

    
150
    QUATS = getQuats();
151
    NUM_CUBITS  = mOrigPos.length;
152
    NUM_FACES = getNumFaces();
153
    NUM_TEXTURES = getNumStickerTypes(mNumLayers)*NUM_FACES;
154
    NUM_AXIS = mAxis.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
    mRotationAngle= new Dynamic1D();
165
    mRotationAxis = new Static3D(1,0,0);
166
    mRotateEffect = new VertexEffectRotate(mRotationAngle, mRotationAxis, CENTER);
167

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

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

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

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

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

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

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

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

    
199
    mEffects.apply(mRotateEffect);
200
    mEffects.apply(quatEffect);
201
    mEffects.apply(scaleEffect);
202

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

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

    
209
    setupPosition(moves);
210

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

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

    
218
///////////////////////////////////////////////////////////////////////////////////////////////////
219

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

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

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

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

    
241
///////////////////////////////////////////////////////////////////////////////////////////////////
242

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

    
248
    if( resourceID!=0 )
249
      {
250
      InputStream is = res.openRawResource(resourceID);
251
      DataInputStream dos = new DataInputStream(is);
252
      mMesh = new MeshFile(dos);
253

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

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

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

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

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

    
289
///////////////////////////////////////////////////////////////////////////////////////////////////
290

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

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

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

    
302
///////////////////////////////////////////////////////////////////////////////////////////////////
303

    
304
  public float getObjectRatio()
305
    {
306
    return mObjectScreenRatio*mInitScreenRatio;
307
    }
308

    
309
///////////////////////////////////////////////////////////////////////////////////////////////////
310

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

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

    
327
    return ret;
328
    }
329

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

    
332
  private int computeSingleRow(int axisIndex,float casted)
333
    {
334
    int num = mNumCuts[axisIndex];
335

    
336
    for(int i=0; i<num; i++)
337
      {
338
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
339
      }
340

    
341
    return (1<<num);
342
    }
343

    
344
///////////////////////////////////////////////////////////////////////////////////////////////////
345

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

    
351
///////////////////////////////////////////////////////////////////////////////////////////////////
352

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

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

    
362
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
363
    {
364
    Static3D axis = mAxis[axisIndex];
365

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

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

    
375
///////////////////////////////////////////////////////////////////////////////////////////////////
376

    
377
  private synchronized void setupPosition(int[][] moves)
378
    {
379
    if( moves!=null )
380
      {
381
      Static4D quat;
382
      int index, axis, rowBitmap, angle;
383
      int[] basic = getBasicAngle();
384

    
385
      for(int[] move: moves)
386
        {
387
        axis     = move[0];
388
        rowBitmap= move[1];
389
        angle    = move[2]*(360/basic[axis]);
390
        quat     = makeQuaternion(axis,angle);
391

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

    
402
///////////////////////////////////////////////////////////////////////////////////////////////////
403
// normal, not bandaged, object.
404

    
405
  int computeBitmapFromRow(int rowBitmap, int axis)
406
    {
407
    return rowBitmap;
408
    }
409

    
410
///////////////////////////////////////////////////////////////////////////////////////////////////
411
// Clamp all rotated positions to one of those original ones to avoid accumulating errors.
412
// Do so only if minimal Error is appropriately low (shape-shifting puzzles - Square-1)
413

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

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

    
424
    float xo,yo,zo;
425

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

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

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

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

    
447
    if( minError< 0.1f ) // TODO: 0.1 ?
448
      {
449
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
450
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
451
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
452
      }
453
    }
454

    
455
///////////////////////////////////////////////////////////////////////////////////////////////////
456
// remember about the double cover or unit quaternions!
457

    
458
  int mulQuat(int q1, int q2)
459
    {
460
    Static4D result = QuatHelper.quatMultiply(QUATS[q1],QUATS[q2]);
461

    
462
    float rX = result.get0();
463
    float rY = result.get1();
464
    float rZ = result.get2();
465
    float rW = result.get3();
466

    
467
    final float MAX_ERROR = 0.1f;
468
    float dX,dY,dZ,dW;
469

    
470
    for(int i=0; i<QUATS.length; i++)
471
      {
472
      dX = QUATS[i].get0() - rX;
473
      dY = QUATS[i].get1() - rY;
474
      dZ = QUATS[i].get2() - rZ;
475
      dW = QUATS[i].get3() - rW;
476

    
477
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
478
          dY<MAX_ERROR && dY>-MAX_ERROR &&
479
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
480
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
481

    
482
      dX = QUATS[i].get0() + rX;
483
      dY = QUATS[i].get1() + rY;
484
      dZ = QUATS[i].get2() + rZ;
485
      dW = QUATS[i].get3() + rW;
486

    
487
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
488
          dY<MAX_ERROR && dY>-MAX_ERROR &&
489
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
490
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
491
      }
492

    
493
    return -1;
494
    }
495

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

    
506
  boolean thereIsVisibleDifference(Cubit cubit, int quatIndex)
507
    {
508
    if ( cubit.mQuatIndex == quatIndex ) return false;
509

    
510
    int belongsToHowManyFaces = 0;
511
    int bitmap = (1<<(getNumLayers()-1)) + 1;
512

    
513
    for(int i = 0; i< NUM_AXIS; i++)
514
      {
515
      if( (cubit.mRotationRow[i] & bitmap) != 0 ) belongsToHowManyFaces++;
516
      }
517

    
518
    switch(belongsToHowManyFaces)
519
      {
520
      case 0 : return false;  // 'inside' cubit that does not lie on any face
521
      case 1 :                // cubit that lies inside one of the faces
522
               float[] orig   = cubit.getOrigPosition();
523
               Static4D quat1 = QUATS[quatIndex];
524
               Static4D quat2 = QUATS[cubit.mQuatIndex];
525

    
526
               Static4D cubitCenter = new Static4D( orig[0], orig[1], orig[2], 0);              // not used for bandaged objects,
527
               Static4D rotated1 = QuatHelper.rotateVectorByQuat( cubitCenter, quat1 );   // only check the first position
528
               Static4D rotated2 = QuatHelper.rotateVectorByQuat( cubitCenter, quat2 );
529

    
530
               rotated1.get(mTmp1, 0, 0, 0);
531
               rotated2.get(mTmp2, 0, 0, 0);
532

    
533
               for(int i = 0; i< NUM_AXIS; i++)
534
                 {
535
                 if( (computeRow(mTmp1,i) & computeRow(mTmp2,i) & bitmap) != 0 ) return false;
536
                 }
537
               return true;
538

    
539
      default: return true;  // edge or corner
540
      }
541
    }
542

    
543
///////////////////////////////////////////////////////////////////////////////////////////////////
544
// create StickerCoord and FaceTransform data structures
545

    
546
  void createFaceDataStructures(double[][][] verts, int[][][] indices)
547
    {
548
    int numCubitTypes = verts.length;
549
    FactoryCubit factory = FactoryCubit.getInstance();
550
    factory.clear();
551

    
552
    for(int cubit=0; cubit<numCubitTypes; cubit++)
553
      {
554
      double[][] vertices = verts[cubit];
555
      int[][] vertIndices = indices[cubit];
556
      factory.createNewFaceTransform(vertices,vertIndices);
557
      }
558

    
559
    factory.printFaceTransform();
560
    factory.printStickerCoords();
561
    }
562

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

    
565
  public int getCubitFaceColorIndex(int cubit, int face)
566
    {
567
    Static4D texMap = mMesh.getTextureMap(NUM_FACES*cubit + face);
568

    
569
    int x = (int)(texMap.get0()/texMap.get2());
570
    int y = (int)(texMap.get1()/texMap.get3());
571

    
572
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
573
    }
574

    
575
///////////////////////////////////////////////////////////////////////////////////////////////////
576
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
577

    
578
  public void createTexture()
579
    {
580
    Bitmap bitmap;
581

    
582
    Paint paint = new Paint();
583
    bitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_8888);
584
    Canvas canvas = new Canvas(bitmap);
585

    
586
    paint.setAntiAlias(true);
587
    paint.setTextAlign(Paint.Align.CENTER);
588
    paint.setStyle(Paint.Style.FILL);
589

    
590
    paint.setColor(COLOR_BLACK);
591
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
592

    
593
    int face = 0;
594
    FactorySticker factory = FactorySticker.getInstance();
595

    
596
    for(int row=0; row<mNumTexRows; row++)
597
      for(int col=0; col<mNumTexCols; col++)
598
        {
599
        if( face>=NUM_TEXTURES ) break;
600
        ObjectSticker sticker = retSticker(face);
601
        factory.drawRoundedPolygon(canvas, paint, col*TEXTURE_HEIGHT, row*TEXTURE_HEIGHT, getColor(face%NUM_FACES), sticker);
602
        face++;
603
        }
604

    
605
    if( !mTexture.setTexture(bitmap) )
606
      {
607
      int max = DistortedLibrary.getMaxTextureSize();
608
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
609
      crashlytics.log("failed to set texture of size "+bitmap.getWidth()+"x"+bitmap.getHeight()+" max is "+max);
610
      }
611
    }
612

    
613
///////////////////////////////////////////////////////////////////////////////////////////////////
614

    
615
  public int getNumLayers()
616
    {
617
    return mNumLayers;
618
    }
619

    
620
///////////////////////////////////////////////////////////////////////////////////////////////////
621

    
622
  public void continueRotation(float angleInDegrees)
623
    {
624
    mRotationAngleStatic.set0(angleInDegrees);
625
    }
626

    
627
///////////////////////////////////////////////////////////////////////////////////////////////////
628

    
629
  public Static4D getRotationQuat()
630
      {
631
      return mQuat;
632
      }
633

    
634
///////////////////////////////////////////////////////////////////////////////////////////////////
635

    
636
  public void recomputeScaleFactor(int scrWidth)
637
    {
638
    mNodeScale.set(scrWidth,NODE_RATIO*scrWidth,scrWidth);
639
    }
640

    
641
///////////////////////////////////////////////////////////////////////////////////////////////////
642

    
643
  public void savePreferences(SharedPreferences.Editor editor)
644
    {
645
    for(int i=0; i<NUM_CUBITS; i++) CUBITS[i].savePreferences(editor);
646
    }
647

    
648
///////////////////////////////////////////////////////////////////////////////////////////////////
649

    
650
  public synchronized void restorePreferences(SharedPreferences preferences)
651
    {
652
    boolean error = false;
653

    
654
    for(int i=0; i<NUM_CUBITS; i++)
655
      {
656
      mQuatDebug[i] = CUBITS[i].restorePreferences(preferences);
657

    
658
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<QUATS.length)
659
        {
660
        CUBITS[i].modifyCurrentPosition(QUATS[mQuatDebug[i]]);
661
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),mQuatDebug[i]);
662
        }
663
      else
664
        {
665
        error = true;
666
        }
667
      }
668

    
669
    if( error )
670
      {
671
      for(int i=0; i<NUM_CUBITS; i++)
672
        {
673
        CUBITS[i].solve();
674
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),0);
675
        }
676
      recordQuatsState("Failed to restorePreferences");
677
      }
678
    }
679

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

    
682
  public void recordQuatsState(String message)
683
    {
684
    StringBuilder quats = new StringBuilder();
685

    
686
    for(int j=0; j<NUM_CUBITS; j++)
687
      {
688
      quats.append(mQuatDebug[j]);
689
      quats.append(" ");
690
      }
691

    
692
    if( BuildConfig.DEBUG )
693
      {
694
      android.util.Log.e("quats" , quats.toString());
695
      android.util.Log.e("object", mList.name()+"_"+mNumLayers);
696
      }
697
    else
698
      {
699
      Exception ex = new Exception(message);
700
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
701
      crashlytics.setCustomKey("quats" , quats.toString());
702
      crashlytics.setCustomKey("object", mList.name()+"_"+mNumLayers );
703
      crashlytics.recordException(ex);
704
      }
705
    }
706

    
707
///////////////////////////////////////////////////////////////////////////////////////////////////
708

    
709
  public void releaseResources()
710
    {
711
    mTexture.markForDeletion();
712
    mMesh.markForDeletion();
713
    mEffects.markForDeletion();
714

    
715
    for(int j=0; j<NUM_CUBITS; j++)
716
      {
717
      CUBITS[j].releaseResources();
718
      }
719
    }
720

    
721
///////////////////////////////////////////////////////////////////////////////////////////////////
722

    
723
  public void apply(Effect effect, int position)
724
    {
725
    mEffects.apply(effect, position);
726
    }
727

    
728
///////////////////////////////////////////////////////////////////////////////////////////////////
729

    
730
  public void remove(long effectID)
731
    {
732
    mEffects.abortById(effectID);
733
    }
734

    
735
///////////////////////////////////////////////////////////////////////////////////////////////////
736

    
737
  public synchronized void solve()
738
    {
739
    for(int i=0; i<NUM_CUBITS; i++)
740
      {
741
      CUBITS[i].solve();
742
      mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
743
      }
744
    }
745

    
746
///////////////////////////////////////////////////////////////////////////////////////////////////
747

    
748
  public void resetAllTextureMaps()
749
    {
750
    final float ratioW = 1.0f/mNumTexCols;
751
    final float ratioH = 1.0f/mNumTexRows;
752
    int color, row, col;
753

    
754
    for(int cubit=0; cubit<NUM_CUBITS; cubit++)
755
      {
756
      final Static4D[] maps = new Static4D[mNumCubitFaces];
757

    
758
      for(int cubitface=0; cubitface<mNumCubitFaces; cubitface++)
759
        {
760
        color = getFaceColor(cubit,cubitface,mNumLayers);
761
        row = (mNumTexRows-1) - color/mNumTexCols;
762
        col = color%mNumTexCols;
763
        maps[cubitface] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
764
        }
765

    
766
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
767
      }
768
    }
769

    
770
///////////////////////////////////////////////////////////////////////////////////////////////////
771

    
772
  public void setTextureMap(int cubit, int face, int newColor)
773
    {
774
    final float ratioW = 1.0f/mNumTexCols;
775
    final float ratioH = 1.0f/mNumTexRows;
776
    final Static4D[] maps = new Static4D[mNumCubitFaces];
777
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
778
    int col = newColor%mNumTexCols;
779

    
780
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
781
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
782
    }
783

    
784
///////////////////////////////////////////////////////////////////////////////////////////////////
785

    
786
  public synchronized void beginNewRotation(int axis, int row )
787
    {
788
    if( axis<0 || axis>=NUM_AXIS )
789
      {
790
      android.util.Log.e("object", "invalid rotation axis: "+axis);
791
      return;
792
      }
793
    if( row<0 || row>=mNumLayers )
794
      {
795
      android.util.Log.e("object", "invalid rotation row: "+row);
796
      return;
797
      }
798

    
799
    mRotAxis     = axis;
800
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
801
    mRotationAngleStatic.set0(0.0f);
802
    mRotationAxis.set( mAxis[axis] );
803
    mRotationAngle.add(mRotationAngleStatic);
804
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis* ObjectList.MAX_OBJECT_SIZE) , -1);
805
    }
806

    
807
///////////////////////////////////////////////////////////////////////////////////////////////////
808

    
809
  public synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
810
    {
811
    if( wasRotateApplied() )
812
      {
813
      mRotAxis     = axis;
814
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
815

    
816
      mRotationAngleStatic.set0(0.0f);
817
      mRotationAxis.set( mAxis[axis] );
818
      mRotationAngle.setDuration(durationMillis);
819
      mRotationAngle.resetToBeginning();
820
      mRotationAngle.add(new Static1D(0));
821
      mRotationAngle.add(new Static1D(angle));
822
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis* ObjectList.MAX_OBJECT_SIZE) , -1);
823
      mRotateEffect.notifyWhenFinished(listener);
824

    
825
      return mRotateEffect.getID();
826
      }
827

    
828
    return 0;
829
    }
830

    
831
///////////////////////////////////////////////////////////////////////////////////////////////////
832

    
833
  public long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
834
    {
835
    if( wasRotateApplied() )
836
      {
837
      float angle = getAngle();
838
      mRotationAngleStatic.set0(angle);
839
      mRotationAngleFinal.set0(nearestAngleInDegrees);
840
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
841

    
842
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
843
      mRotationAngle.resetToBeginning();
844
      mRotationAngle.removeAll();
845
      mRotationAngle.add(mRotationAngleStatic);
846
      mRotationAngle.add(mRotationAngleMiddle);
847
      mRotationAngle.add(mRotationAngleFinal);
848
      mRotateEffect.notifyWhenFinished(listener);
849

    
850
      return mRotateEffect.getID();
851
      }
852

    
853
    return 0;
854
    }
855

    
856
///////////////////////////////////////////////////////////////////////////////////////////////////
857

    
858
  private float getAngle()
859
    {
860
    int pointNum = mRotationAngle.getNumPoints();
861

    
862
    if( pointNum>=1 )
863
      {
864
      return mRotationAngle.getPoint(pointNum-1).get0();
865
      }
866
    else
867
      {
868
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
869
      crashlytics.log("points in RotationAngle: "+pointNum);
870
      return 0;
871
      }
872
    }
873

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

    
876
  public synchronized void removeRotationNow()
877
    {
878
    float angle = getAngle();
879
    double nearestAngleInRadians = angle*Math.PI/180;
880
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
881
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
882
    float axisX = mAxis[mRotAxis].get0();
883
    float axisY = mAxis[mRotAxis].get1();
884
    float axisZ = mAxis[mRotAxis].get2();
885
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
886

    
887
    mRotationAngle.removeAll();
888
    mRotationAngleStatic.set0(0);
889

    
890
    for(int i=0; i<NUM_CUBITS; i++)
891
      if( belongsToRotation(i,mRotAxis,mRotRowBitmap) )
892
        {
893
        int index = CUBITS[i].removeRotationNow(quat);
894
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),index);
895
        }
896
    }
897

    
898
///////////////////////////////////////////////////////////////////////////////////////////////////
899

    
900
  public void initializeObject(int[][] moves)
901
    {
902
    solve();
903
    setupPosition(moves);
904
    }
905

    
906
///////////////////////////////////////////////////////////////////////////////////////////////////
907

    
908
  public int getCubit(float[] point3D)
909
    {
910
    float dist, minDist = Float.MAX_VALUE;
911
    int currentBest=-1;
912
    float multiplier = returnMultiplier();
913

    
914
    point3D[0] *= multiplier;
915
    point3D[1] *= multiplier;
916
    point3D[2] *= multiplier;
917

    
918
    for(int i=0; i<NUM_CUBITS; i++)
919
      {
920
      dist = CUBITS[i].getDistSquared(point3D);
921
      if( dist<minDist )
922
        {
923
        minDist = dist;
924
        currentBest = i;
925
        }
926
      }
927

    
928
    return currentBest;
929
    }
930

    
931
///////////////////////////////////////////////////////////////////////////////////////////////////
932

    
933
  public int computeNearestAngle(int axis, float angle, float speed)
934
    {
935
    int[] basicArray = getBasicAngle();
936
    int basicAngle   = basicArray[axis>=basicArray.length ? 0 : axis];
937
    int nearestAngle = 360/basicAngle;
938

    
939
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
940
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
941

    
942
    if( tmp!=0 ) return nearestAngle*tmp;
943

    
944
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
945
    }
946

    
947
///////////////////////////////////////////////////////////////////////////////////////////////////
948

    
949
  public float getCameraDist()
950
    {
951
    return mCameraDist;
952
    }
953

    
954
///////////////////////////////////////////////////////////////////////////////////////////////////
955

    
956
  public int getNodeSize()
957
    {
958
    return mNodeSize;
959
    }
960

    
961
///////////////////////////////////////////////////////////////////////////////////////////////////
962

    
963
  public ObjectList getObjectList()
964
    {
965
    return mList;
966
    }
967

    
968
///////////////////////////////////////////////////////////////////////////////////////////////////
969

    
970
  abstract float getScreenRatio();
971
  abstract float[][] getCubitPositions(int numLayers);
972
  abstract Static4D[] getQuats();
973
  abstract int getNumFaces();
974
  abstract int getNumStickerTypes(int numLayers);
975
  abstract int getNumCubitFaces();
976
  abstract MeshBase createCubitMesh(int cubit, int numLayers);
977
  abstract ObjectSticker retSticker(int face);
978
  abstract int getColor(int face);
979
  abstract int getFaceColor(int cubit, int cubitface, int numLayers);
980
  abstract float returnMultiplier();
981
  abstract float[][] getCuts(int numLayers);
982
  abstract boolean shouldResetTextureMaps();
983

    
984
  public abstract Static3D[] getRotationAxis();
985
  public abstract boolean isSolved();
986
  public abstract int[] getBasicAngle();
987
  public abstract void randomizeNewScramble(int[][] scramble, Random rnd, int curScramble, int totScrambles);
988
  public abstract int getObjectName(int numLayers);
989
  public abstract int getInventor(int numLayers);
990
  public abstract int getComplexity(int numLayers);
991
  }
(33-33/41)