Project

General

Profile

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

magiccube / src / main / java / org / distorted / objects / TwistyObject.java @ 169219a7

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

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

    
61
///////////////////////////////////////////////////////////////////////////////////////////////////
62

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

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

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

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

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

    
90
  MeshBase[] mMeshes;
91
  final Static4D[] QUATS;
92
  final Cubit[] CUBITS;
93
  final int NUM_FACES;
94
  final int NUM_TEXTURES;
95
  final int NUM_CUBITS;
96
  final int NUM_AXIS;
97

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

    
128
  //////////////////// SOLVED1 ////////////////////////
129

    
130
  private static final int[] mFaceMap = { 4, 2, 2, 4, 0, 2, 1, 4, 0, 0, 1, 1 };
131
  private static int[][] mScramble;
132
  private int[] mColors;
133

    
134
///////////////////////////////////////////////////////////////////////////////////////////////////
135

    
136
  TwistyObject(int numLayers, int realSize, Static4D quat, DistortedTexture nodeTexture, MeshSquare nodeMesh,
137
               DistortedEffects nodeEffects, int[][] moves, ObjectList list, Resources res, int screenWidth)
138
    {
139
    super(nodeTexture,nodeEffects,nodeMesh);
140

    
141
    mNodeSize = screenWidth;
142

    
143
    resizeFBO(mNodeSize, (int)(NODE_RATIO*mNodeSize));
144

    
145
    mNumLayers = numLayers;
146
    mRealSize = realSize;
147
    mList = list;
148
    mOrigPos = getCubitPositions(mNumLayers);
149
    mAxis = getRotationAxis();
150
    mInitScreenRatio = getScreenRatio();
151
    mObjectScreenRatio = 1.0f;
152
    mNumCubitFaces = getNumCubitFaces();
153
    mSolvedFunctionIndex = getSolvedFunctionIndex();
154

    
155
    mCuts = getCuts(mNumLayers);
156
    mNumCuts = new int[mAxis.length];
157
    if( mCuts==null ) for(int i=0; i<mAxis.length; i++) mNumCuts[i] = 0;
158
    else              for(int i=0; i<mAxis.length; i++) mNumCuts[i] = mCuts[i].length;
159

    
160
    QUATS = getQuats();
161
    NUM_CUBITS  = mOrigPos.length;
162
    NUM_FACES = getNumFaces();
163
    NUM_TEXTURES = getNumStickerTypes(mNumLayers)*NUM_FACES;
164
    NUM_AXIS = mAxis.length;
165

    
166
    mQuatDebug = new int[NUM_CUBITS];
167

    
168
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
169
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
170

    
171
    mNodeScale= new Static3D(1,NODE_RATIO,1);
172
    mQuat = quat;
173

    
174
    mRotationAngle= new Dynamic1D();
175
    mRotationAxis = new Static3D(1,0,0);
176
    mRotateEffect = new VertexEffectRotate(mRotationAngle, mRotationAxis, CENTER);
177

    
178
    mRotationAngleStatic = new Static1D(0);
179
    mRotationAngleMiddle = new Static1D(0);
180
    mRotationAngleFinal  = new Static1D(0);
181

    
182
    float scale  = mObjectScreenRatio*mInitScreenRatio*mNodeSize/mRealSize;
183
    mObjectScale = new Static3D(scale,scale,scale);
184
    MatrixEffectScale scaleEffect = new MatrixEffectScale(mObjectScale);
185
    MatrixEffectQuaternion quatEffect  = new MatrixEffectQuaternion(quat, CENTER);
186

    
187
    MatrixEffectScale nodeScaleEffect = new MatrixEffectScale(mNodeScale);
188
    nodeEffects.apply(nodeScaleEffect);
189

    
190
    mNumTexCols = NUM_STICKERS_IN_ROW;
191
    mNumTexRows = (NUM_TEXTURES+1)/NUM_STICKERS_IN_ROW;
192

    
193
    if( mNumTexCols*mNumTexRows < NUM_TEXTURES+1 ) mNumTexRows++;
194

    
195
    CUBITS = new Cubit[NUM_CUBITS];
196
    createMeshAndCubits(list,res);
197
    createDataStructuresForSolved(numLayers);
198

    
199
    mTexture = new DistortedTexture();
200
    mEffects = new DistortedEffects();
201

    
202
    int num_quats = QUATS.length;
203
    for(int q=0; q<num_quats; q++)
204
      {
205
      VertexEffectQuaternion vq = new VertexEffectQuaternion(QUATS[q],CENTER);
206
      vq.setMeshAssociation(0,q);
207
      mEffects.apply(vq);
208
      }
209

    
210
    mEffects.apply(mRotateEffect);
211
    mEffects.apply(quatEffect);
212
    mEffects.apply(scaleEffect);
213

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

    
218
    attach( new DistortedNode(mTexture,mEffects,mMesh) );
219

    
220
    setupPosition(moves);
221

    
222
    float fov = list.getFOV();
223
    double halfFOV = fov * (Math.PI/360);
224
    mCameraDist = 0.5f*NODE_RATIO / (float)Math.tan(halfFOV);
225

    
226
    setProjection( fov, 0.1f);
227
    }
228

    
229
///////////////////////////////////////////////////////////////////////////////////////////////////
230

    
231
  private Static3D getPos(float[] origPos)
232
    {
233
    int len = origPos.length/3;
234
    float sumX = 0.0f;
235
    float sumY = 0.0f;
236
    float sumZ = 0.0f;
237

    
238
    for(int i=0; i<len; i++)
239
      {
240
      sumX += origPos[3*i  ];
241
      sumY += origPos[3*i+1];
242
      sumZ += origPos[3*i+2];
243
      }
244

    
245
    sumX /= len;
246
    sumY /= len;
247
    sumZ /= len;
248

    
249
    return new Static3D(sumX,sumY,sumZ);
250
    }
251

    
252
///////////////////////////////////////////////////////////////////////////////////////////////////
253

    
254
  private void createMeshAndCubits(ObjectList list, Resources res)
255
    {
256
    int sizeIndex = ObjectList.getSizeIndex(list.ordinal(),mNumLayers);
257
    int resourceID= list.getResourceIDs()[sizeIndex];
258

    
259
    if( resourceID!=0 )
260
      {
261
      InputStream is = res.openRawResource(resourceID);
262
      DataInputStream dos = new DataInputStream(is);
263
      mMesh = new MeshFile(dos);
264

    
265
      try
266
        {
267
        is.close();
268
        }
269
      catch(IOException e)
270
        {
271
        android.util.Log.e("meshFile", "Error closing InputStream: "+e.toString());
272
        }
273

    
274
      for(int i=0; i<NUM_CUBITS; i++)
275
        {
276
        CUBITS[i] = new Cubit(this,mOrigPos[i], NUM_AXIS);
277
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
278
        }
279

    
280
      if( shouldResetTextureMaps() ) resetAllTextureMaps();
281
      }
282
    else
283
      {
284
      MeshBase[] cubitMesh = new MeshBase[NUM_CUBITS];
285

    
286
      for(int i=0; i<NUM_CUBITS; i++)
287
        {
288
        CUBITS[i] = new Cubit(this,mOrigPos[i], NUM_AXIS);
289
        cubitMesh[i] = createCubitMesh(i,mNumLayers);
290
        Static3D pos = getPos(mOrigPos[i]);
291
        cubitMesh[i].apply(new MatrixEffectMove(pos),1,0);
292
        cubitMesh[i].setEffectAssociation(0, CUBITS[i].computeAssociation(), 0);
293
        }
294

    
295
      mMesh = new MeshJoined(cubitMesh);
296
      resetAllTextureMaps();
297
      }
298
    }
299

    
300
///////////////////////////////////////////////////////////////////////////////////////////////////
301

    
302
  private MeshBase createCubitMesh(int cubit, int numLayers)
303
    {
304
    int variant = getCubitVariant(cubit,numLayers);
305

    
306
    if( mMeshes==null )
307
      {
308
      FactoryCubit factory = FactoryCubit.getInstance();
309
      factory.clear();
310
      mMeshes = new MeshBase[getNumCubitVariants(numLayers)];
311
      }
312

    
313
    if( mMeshes[variant]==null )
314
      {
315
      ObjectShape shape = getObjectShape(cubit,numLayers);
316
      FactoryCubit factory = FactoryCubit.getInstance();
317
      factory.createNewFaceTransform(shape);
318
      mMeshes[variant] = factory.createRoundedSolid(shape);
319
      }
320

    
321
    MeshBase mesh = mMeshes[variant].copy(true);
322
    MatrixEffectQuaternion quat = new MatrixEffectQuaternion( getQuat(cubit,numLayers), new Static3D(0,0,0) );
323
    mesh.apply(quat,0xffffffff,0);
324

    
325
    return mesh;
326
    }
327

    
328
///////////////////////////////////////////////////////////////////////////////////////////////////
329

    
330
  private void createDataStructuresForSolved(int numLayers)
331
    {
332
    mTmpQuats = new int[QUATS.length];
333
    mSolvedQuats = new int[NUM_CUBITS][];
334

    
335
    for(int c=0; c<NUM_CUBITS; c++)
336
      {
337
      mSolvedQuats[c] = getSolvedQuats(c,numLayers);
338
      }
339
    }
340

    
341
///////////////////////////////////////////////////////////////////////////////////////////////////
342
// This is used to build internal data structures for the generic 'isSolved()'
343
//
344
// if this is an internal cubit (all faces black): return -1
345
// if this is a face cubit (one non-black face): return the color index of the only non-black face.
346
// Color index, i.e. the index into the 'FACE_COLORS' table.
347
// else (edge or corner cubit, more than one non-black face): return -2.
348

    
349
  int retCubitSolvedStatus(int cubit, int numLayers)
350
    {
351
    int numNonBlack=0, nonBlackIndex=-1, color;
352

    
353
    for(int face=0; face<mNumCubitFaces; face++)
354
      {
355
      color = getFaceColor(cubit,face,numLayers);
356

    
357
      if( color<NUM_TEXTURES )
358
        {
359
        numNonBlack++;
360
        nonBlackIndex = color%NUM_FACES;
361
        }
362
      }
363

    
364
    if( numNonBlack==0 ) return -1;
365
    if( numNonBlack>=2 ) return -2;
366

    
367
    return nonBlackIndex;
368
    }
369

    
370
///////////////////////////////////////////////////////////////////////////////////////////////////
371

    
372
  int[] buildSolvedQuats(Static3D faceAx, Static4D[] quats)
373
    {
374
    final float MAXD = 0.0001f;
375
    float x = faceAx.get0();
376
    float y = faceAx.get1();
377
    float z = faceAx.get2();
378
    float a,dx,dy,dz,qx,qy,qz;
379
    Static4D quat;
380

    
381
    int len = quats.length;
382
    int place = 0;
383

    
384
    for(int q=1; q<len; q++)
385
      {
386
      quat = quats[q];
387
      qx = quat.get0();
388
      qy = quat.get1();
389
      qz = quat.get2();
390

    
391
           if( x!=0.0f ) { a = qx/x; }
392
      else if( y!=0.0f ) { a = qy/y; }
393
      else               { a = qz/z; }
394

    
395
      dx = a*x-qx;
396
      dy = a*y-qy;
397
      dz = a*z-qz;
398

    
399
      if( dx>-MAXD && dx<MAXD && dy>-MAXD && dy<MAXD && dz>-MAXD && dz<MAXD )
400
        {
401
        mTmpQuats[place++] = q;
402
        }
403
      }
404

    
405
    if( place!=0 )
406
      {
407
      int[] ret = new int[place];
408
      System.arraycopy(mTmpQuats,0,ret,0,place);
409
      return ret;
410
      }
411

    
412
    return null;
413
    }
414

    
415
///////////////////////////////////////////////////////////////////////////////////////////////////
416

    
417
  private int getMultQuat(int index1, int index2)
418
    {
419
    if( mQuatMult==null )
420
      {
421
      int len = QUATS.length;
422
      mQuatMult = new int[len][len];
423

    
424
      for(int i=0; i<len; i++)
425
        for(int j=0; j<len; j++) mQuatMult[i][j] = -1;
426
      }
427

    
428
    if( mQuatMult[index1][index2]==-1 )
429
      {
430
      mQuatMult[index1][index2] = mulQuat(index1,index2);
431
      }
432

    
433
    return mQuatMult[index1][index2];
434
    }
435

    
436
///////////////////////////////////////////////////////////////////////////////////////////////////
437

    
438
  public boolean isSolved()
439
    {
440
    if( mSolvedFunctionIndex==0 ) return isSolved0();
441
    if( mSolvedFunctionIndex==1 ) return isSolved1();
442

    
443
    return false;
444
    }
445

    
446
///////////////////////////////////////////////////////////////////////////////////////////////////
447

    
448
  public boolean isSolved0()
449
    {
450
    int len, q1,q = CUBITS[0].mQuatIndex;
451
    int[] solved;
452
    boolean skip;
453

    
454
    for(int c=1; c<NUM_CUBITS; c++)
455
      {
456
      q1 = CUBITS[c].mQuatIndex;
457

    
458
      if( q1==q ) continue;
459

    
460
      skip = false;
461
      solved = mSolvedQuats[c];
462
      len = solved==null ? 0:solved.length;
463

    
464
      for(int i=0; i<len; i++)
465
        {
466
        if( q1==getMultQuat(q,solved[i]) )
467
          {
468
          skip = true;
469
          break;
470
          }
471
        }
472

    
473
      if( !skip ) return false;
474
      }
475

    
476
    return true;
477
    }
478

    
479
///////////////////////////////////////////////////////////////////////////////////////////////////
480

    
481
  private int computeScramble(int quatNum, int centerNum)
482
    {
483
    float MAXDIFF = 0.01f;
484
    float[] center= mOrigPos[centerNum];
485
    Static4D sc = new Static4D(center[0], center[1], center[2], 1.0f);
486
    Static4D result = QuatHelper.rotateVectorByQuat(sc,QUATS[quatNum]);
487

    
488
    float x = result.get0();
489
    float y = result.get1();
490
    float z = result.get2();
491

    
492
    for(int c=0; c<NUM_CUBITS; c++)
493
      {
494
      float[] cent = mOrigPos[c];
495

    
496
      float qx = cent[0] - x;
497
      float qy = cent[1] - y;
498
      float qz = cent[2] - z;
499

    
500
      if( qx>-MAXDIFF && qx<MAXDIFF &&
501
          qy>-MAXDIFF && qy<MAXDIFF &&
502
          qz>-MAXDIFF && qz<MAXDIFF  ) return c;
503
      }
504

    
505
    return -1;
506
    }
507

    
508
///////////////////////////////////////////////////////////////////////////////////////////////////
509
// Dino4 uses this. It is solved if and only if groups of cubits
510
// (0,3,7), (1,2,5), (4,8,9), (6,10,11)
511
// or
512
// (0,1,4), (2,3,6), (5,9,10), (7,8,11)
513
// are all the same color.
514

    
515
  public boolean isSolved1()
516
    {
517
    if( mScramble==null )
518
      {
519
      int numQuats = QUATS.length;
520
      mScramble = new int[numQuats][NUM_CUBITS];
521
      mColors   = new int[NUM_CUBITS];
522

    
523
      for(int q=0; q<numQuats; q++)
524
        for(int c=0; c<NUM_CUBITS; c++) mScramble[q][c] = computeScramble(q,c);
525
      }
526

    
527
    for(int c=0; c<NUM_CUBITS; c++)
528
      {
529
      int index = mScramble[CUBITS[c].mQuatIndex][c];
530
      mColors[index] = mFaceMap[c];
531
      }
532

    
533
    if( mColors[0]==mColors[3] && mColors[0]==mColors[7] &&
534
        mColors[1]==mColors[2] && mColors[1]==mColors[5] &&
535
        mColors[4]==mColors[8] && mColors[4]==mColors[9]  ) return true;
536

    
537
    if( mColors[0]==mColors[1] && mColors[0]==mColors[4] &&
538
        mColors[2]==mColors[3] && mColors[2]==mColors[6] &&
539
        mColors[5]==mColors[9] && mColors[5]==mColors[10] ) return true;
540

    
541
    return false;
542
    }
543

    
544
///////////////////////////////////////////////////////////////////////////////////////////////////
545

    
546
  public void setObjectRatio(float sizeChange)
547
    {
548
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
549

    
550
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
551
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
552

    
553
    float scale = mObjectScreenRatio*mInitScreenRatio*mNodeSize/mRealSize;
554
    mObjectScale.set(scale,scale,scale);
555
    }
556

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

    
559
  public float getObjectRatio()
560
    {
561
    return mObjectScreenRatio*mInitScreenRatio;
562
    }
563

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

    
566
  int computeRow(float[] pos, int axisIndex)
567
    {
568
    int ret=0;
569
    int len = pos.length / 3;
570
    Static3D axis = mAxis[axisIndex];
571
    float axisX = axis.get0();
572
    float axisY = axis.get1();
573
    float axisZ = axis.get2();
574
    float casted;
575

    
576
    for(int i=0; i<len; i++)
577
      {
578
      casted = pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ;
579
      ret |= computeSingleRow(axisIndex,casted);
580
      }
581

    
582
    return ret;
583
    }
584

    
585
///////////////////////////////////////////////////////////////////////////////////////////////////
586

    
587
  private int computeSingleRow(int axisIndex,float casted)
588
    {
589
    int num = mNumCuts[axisIndex];
590

    
591
    for(int i=0; i<num; i++)
592
      {
593
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
594
      }
595

    
596
    return (1<<num);
597
    }
598

    
599
///////////////////////////////////////////////////////////////////////////////////////////////////
600

    
601
  private boolean wasRotateApplied()
602
    {
603
    return mEffects.exists(mRotateEffect.getID());
604
    }
605

    
606
///////////////////////////////////////////////////////////////////////////////////////////////////
607

    
608
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
609
    {
610
    return (CUBITS[cubit].mRotationRow[axis] & rowBitmap) != 0;
611
    }
612

    
613
///////////////////////////////////////////////////////////////////////////////////////////////////
614
// note the minus in front of the sin() - we rotate counterclockwise
615
// when looking towards the direction where the axis increases in values.
616

    
617
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
618
    {
619
    Static3D axis = mAxis[axisIndex];
620

    
621
    while( angleInDegrees<0 ) angleInDegrees += 360;
622
    angleInDegrees %= 360;
623
    
624
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
625
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
626

    
627
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
628
    }
629

    
630
///////////////////////////////////////////////////////////////////////////////////////////////////
631

    
632
  private synchronized void setupPosition(int[][] moves)
633
    {
634
    if( moves!=null )
635
      {
636
      Static4D quat;
637
      int index, axis, rowBitmap, angle;
638
      int[] basic = getBasicAngle();
639

    
640
      for(int[] move: moves)
641
        {
642
        axis     = move[0];
643
        rowBitmap= move[1];
644
        angle    = move[2]*(360/basic[axis]);
645
        quat     = makeQuaternion(axis,angle);
646

    
647
        for(int j=0; j<NUM_CUBITS; j++)
648
          if( belongsToRotation(j,axis,rowBitmap) )
649
            {
650
            index = CUBITS[j].removeRotationNow(quat);
651
            mMesh.setEffectAssociation(j, CUBITS[j].computeAssociation(),index);
652
            }
653
        }
654
      }
655
    }
656

    
657
///////////////////////////////////////////////////////////////////////////////////////////////////
658
// normal, not bandaged, object.
659

    
660
  int computeBitmapFromRow(int rowBitmap, int axis)
661
    {
662
    return rowBitmap;
663
    }
664

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

    
669
  void clampPos(float[] pos, int offset)
670
    {
671
    float currError, minError = Float.MAX_VALUE;
672
    int minErrorIndex1 = -1;
673
    int minErrorIndex2 = -1;
674

    
675
    float x = pos[offset  ];
676
    float y = pos[offset+1];
677
    float z = pos[offset+2];
678

    
679
    float xo,yo,zo;
680

    
681
    for(int i=0; i<NUM_CUBITS; i++)
682
      {
683
      int len = mOrigPos[i].length / 3;
684

    
685
      for(int j=0; j<len; j++)
686
        {
687
        xo = mOrigPos[i][3*j  ];
688
        yo = mOrigPos[i][3*j+1];
689
        zo = mOrigPos[i][3*j+2];
690

    
691
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
692

    
693
        if( currError<minError )
694
          {
695
          minError = currError;
696
          minErrorIndex1 = i;
697
          minErrorIndex2 = j;
698
          }
699
        }
700
      }
701

    
702
    if( minError< 0.1f ) // TODO: 0.1 ?
703
      {
704
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
705
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
706
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
707
      }
708
    }
709

    
710
///////////////////////////////////////////////////////////////////////////////////////////////////
711
// remember about the double cover or unit quaternions!
712

    
713
  int mulQuat(int q1, int q2)
714
    {
715
    Static4D result = QuatHelper.quatMultiply(QUATS[q1],QUATS[q2]);
716

    
717
    float rX = result.get0();
718
    float rY = result.get1();
719
    float rZ = result.get2();
720
    float rW = result.get3();
721

    
722
    final float MAX_ERROR = 0.1f;
723
    float dX,dY,dZ,dW;
724

    
725
    for(int i=0; i<QUATS.length; i++)
726
      {
727
      dX = QUATS[i].get0() - rX;
728
      dY = QUATS[i].get1() - rY;
729
      dZ = QUATS[i].get2() - rZ;
730
      dW = QUATS[i].get3() - rW;
731

    
732
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
733
          dY<MAX_ERROR && dY>-MAX_ERROR &&
734
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
735
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
736

    
737
      dX = QUATS[i].get0() + rX;
738
      dY = QUATS[i].get1() + rY;
739
      dZ = QUATS[i].get2() + rZ;
740
      dW = QUATS[i].get3() + rW;
741

    
742
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
743
          dY<MAX_ERROR && dY>-MAX_ERROR &&
744
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
745
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
746
      }
747

    
748
    return -1;
749
    }
750

    
751
///////////////////////////////////////////////////////////////////////////////////////////////////
752

    
753
  public int getCubitFaceColorIndex(int cubit, int face)
754
    {
755
    Static4D texMap = mMesh.getTextureMap(NUM_FACES*cubit + face);
756

    
757
    int x = (int)(texMap.get0()/texMap.get2());
758
    int y = (int)(texMap.get1()/texMap.get3());
759

    
760
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
761
    }
762

    
763
///////////////////////////////////////////////////////////////////////////////////////////////////
764
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
765

    
766
  public void createTexture()
767
    {
768
    Bitmap bitmap;
769

    
770
    Paint paint = new Paint();
771
    bitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_8888);
772
    Canvas canvas = new Canvas(bitmap);
773

    
774
    paint.setAntiAlias(true);
775
    paint.setTextAlign(Paint.Align.CENTER);
776
    paint.setStyle(Paint.Style.FILL);
777

    
778
    paint.setColor(COLOR_BLACK);
779
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
780

    
781
    int face = 0;
782
    FactorySticker factory = FactorySticker.getInstance();
783

    
784
    for(int row=0; row<mNumTexRows; row++)
785
      for(int col=0; col<mNumTexCols; col++)
786
        {
787
        if( face>=NUM_TEXTURES ) break;
788
        ObjectSticker sticker = retSticker(face);
789
        factory.drawRoundedPolygon(canvas, paint, col*TEXTURE_HEIGHT, row*TEXTURE_HEIGHT, getColor(face%NUM_FACES), sticker);
790
        face++;
791
        }
792

    
793
    if( !mTexture.setTexture(bitmap) )
794
      {
795
      int max = DistortedLibrary.getMaxTextureSize();
796
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
797
      crashlytics.log("failed to set texture of size "+bitmap.getWidth()+"x"+bitmap.getHeight()+" max is "+max);
798
      }
799
    }
800

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

    
803
  public int getNumLayers()
804
    {
805
    return mNumLayers;
806
    }
807

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

    
810
  public void continueRotation(float angleInDegrees)
811
    {
812
    mRotationAngleStatic.set0(angleInDegrees);
813
    }
814

    
815
///////////////////////////////////////////////////////////////////////////////////////////////////
816

    
817
  public Static4D getRotationQuat()
818
      {
819
      return mQuat;
820
      }
821

    
822
///////////////////////////////////////////////////////////////////////////////////////////////////
823

    
824
  public void recomputeScaleFactor(int scrWidth)
825
    {
826
    mNodeScale.set(scrWidth,NODE_RATIO*scrWidth,scrWidth);
827
    }
828

    
829
///////////////////////////////////////////////////////////////////////////////////////////////////
830

    
831
  public void savePreferences(SharedPreferences.Editor editor)
832
    {
833
    for(int i=0; i<NUM_CUBITS; i++) CUBITS[i].savePreferences(editor);
834
    }
835

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

    
838
  public synchronized void restorePreferences(SharedPreferences preferences)
839
    {
840
    boolean error = false;
841

    
842
    for(int i=0; i<NUM_CUBITS; i++)
843
      {
844
      mQuatDebug[i] = CUBITS[i].restorePreferences(preferences);
845

    
846
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<QUATS.length)
847
        {
848
        CUBITS[i].modifyCurrentPosition(QUATS[mQuatDebug[i]]);
849
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),mQuatDebug[i]);
850
        }
851
      else
852
        {
853
        error = true;
854
        }
855
      }
856

    
857
    if( error )
858
      {
859
      for(int i=0; i<NUM_CUBITS; i++)
860
        {
861
        CUBITS[i].solve();
862
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),0);
863
        }
864
      recordQuatsState("Failed to restorePreferences");
865
      }
866
    }
867

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

    
870
  public void recordQuatsState(String message)
871
    {
872
    StringBuilder quats = new StringBuilder();
873

    
874
    for(int j=0; j<NUM_CUBITS; j++)
875
      {
876
      quats.append(mQuatDebug[j]);
877
      quats.append(" ");
878
      }
879

    
880
    if( BuildConfig.DEBUG )
881
      {
882
      android.util.Log.e("quats" , quats.toString());
883
      android.util.Log.e("object", mList.name()+"_"+mNumLayers);
884
      }
885
    else
886
      {
887
      Exception ex = new Exception(message);
888
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
889
      crashlytics.setCustomKey("quats" , quats.toString());
890
      crashlytics.setCustomKey("object", mList.name()+"_"+mNumLayers );
891
      crashlytics.recordException(ex);
892
      }
893
    }
894

    
895
///////////////////////////////////////////////////////////////////////////////////////////////////
896

    
897
  public void releaseResources()
898
    {
899
    mTexture.markForDeletion();
900
    mMesh.markForDeletion();
901
    mEffects.markForDeletion();
902

    
903
    for(int j=0; j<NUM_CUBITS; j++)
904
      {
905
      CUBITS[j].releaseResources();
906
      }
907
    }
908

    
909
///////////////////////////////////////////////////////////////////////////////////////////////////
910

    
911
  public void apply(Effect effect, int position)
912
    {
913
    mEffects.apply(effect, position);
914
    }
915

    
916
///////////////////////////////////////////////////////////////////////////////////////////////////
917

    
918
  public void remove(long effectID)
919
    {
920
    mEffects.abortById(effectID);
921
    }
922

    
923
///////////////////////////////////////////////////////////////////////////////////////////////////
924

    
925
  public synchronized void solve()
926
    {
927
    for(int i=0; i<NUM_CUBITS; i++)
928
      {
929
      CUBITS[i].solve();
930
      mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
931
      }
932
    }
933

    
934
///////////////////////////////////////////////////////////////////////////////////////////////////
935

    
936
  public void resetAllTextureMaps()
937
    {
938
    final float ratioW = 1.0f/mNumTexCols;
939
    final float ratioH = 1.0f/mNumTexRows;
940
    int color, row, col;
941

    
942
    for(int cubit=0; cubit<NUM_CUBITS; cubit++)
943
      {
944
      final Static4D[] maps = new Static4D[mNumCubitFaces];
945

    
946
      for(int cubitface=0; cubitface<mNumCubitFaces; cubitface++)
947
        {
948
        color = getFaceColor(cubit,cubitface,mNumLayers);
949
        row = (mNumTexRows-1) - color/mNumTexCols;
950
        col = color%mNumTexCols;
951
        maps[cubitface] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
952
        }
953

    
954
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
955
      }
956
    }
957

    
958
///////////////////////////////////////////////////////////////////////////////////////////////////
959

    
960
  public void setTextureMap(int cubit, int face, int newColor)
961
    {
962
    final float ratioW = 1.0f/mNumTexCols;
963
    final float ratioH = 1.0f/mNumTexRows;
964
    final Static4D[] maps = new Static4D[mNumCubitFaces];
965
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
966
    int col = newColor%mNumTexCols;
967

    
968
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
969
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
970
    }
971

    
972
///////////////////////////////////////////////////////////////////////////////////////////////////
973

    
974
  public synchronized void beginNewRotation(int axis, int row )
975
    {
976
    if( axis<0 || axis>=NUM_AXIS )
977
      {
978
      android.util.Log.e("object", "invalid rotation axis: "+axis);
979
      return;
980
      }
981
    if( row<0 || row>=mNumLayers )
982
      {
983
      android.util.Log.e("object", "invalid rotation row: "+row);
984
      return;
985
      }
986

    
987
    mRotAxis     = axis;
988
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
989
    mRotationAngleStatic.set0(0.0f);
990
    mRotationAxis.set( mAxis[axis] );
991
    mRotationAngle.add(mRotationAngleStatic);
992
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis* ObjectList.MAX_OBJECT_SIZE) , -1);
993
    }
994

    
995
///////////////////////////////////////////////////////////////////////////////////////////////////
996

    
997
  public synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
998
    {
999
    if( wasRotateApplied() )
1000
      {
1001
      mRotAxis     = axis;
1002
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
1003

    
1004
      mRotationAngleStatic.set0(0.0f);
1005
      mRotationAxis.set( mAxis[axis] );
1006
      mRotationAngle.setDuration(durationMillis);
1007
      mRotationAngle.resetToBeginning();
1008
      mRotationAngle.add(new Static1D(0));
1009
      mRotationAngle.add(new Static1D(angle));
1010
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis* ObjectList.MAX_OBJECT_SIZE) , -1);
1011
      mRotateEffect.notifyWhenFinished(listener);
1012

    
1013
      return mRotateEffect.getID();
1014
      }
1015

    
1016
    return 0;
1017
    }
1018

    
1019
///////////////////////////////////////////////////////////////////////////////////////////////////
1020

    
1021
  public long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
1022
    {
1023
    if( wasRotateApplied() )
1024
      {
1025
      float angle = getAngle();
1026
      mRotationAngleStatic.set0(angle);
1027
      mRotationAngleFinal.set0(nearestAngleInDegrees);
1028
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
1029

    
1030
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
1031
      mRotationAngle.resetToBeginning();
1032
      mRotationAngle.removeAll();
1033
      mRotationAngle.add(mRotationAngleStatic);
1034
      mRotationAngle.add(mRotationAngleMiddle);
1035
      mRotationAngle.add(mRotationAngleFinal);
1036
      mRotateEffect.notifyWhenFinished(listener);
1037

    
1038
      return mRotateEffect.getID();
1039
      }
1040

    
1041
    return 0;
1042
    }
1043

    
1044
///////////////////////////////////////////////////////////////////////////////////////////////////
1045

    
1046
  private float getAngle()
1047
    {
1048
    int pointNum = mRotationAngle.getNumPoints();
1049

    
1050
    if( pointNum>=1 )
1051
      {
1052
      return mRotationAngle.getPoint(pointNum-1).get0();
1053
      }
1054
    else
1055
      {
1056
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
1057
      crashlytics.log("points in RotationAngle: "+pointNum);
1058
      return 0;
1059
      }
1060
    }
1061

    
1062
///////////////////////////////////////////////////////////////////////////////////////////////////
1063

    
1064
  public synchronized void removeRotationNow()
1065
    {
1066
    float angle = getAngle();
1067
    double nearestAngleInRadians = angle*Math.PI/180;
1068
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
1069
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
1070
    float axisX = mAxis[mRotAxis].get0();
1071
    float axisY = mAxis[mRotAxis].get1();
1072
    float axisZ = mAxis[mRotAxis].get2();
1073
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
1074

    
1075
    mRotationAngle.removeAll();
1076
    mRotationAngleStatic.set0(0);
1077

    
1078
    for(int i=0; i<NUM_CUBITS; i++)
1079
      if( belongsToRotation(i,mRotAxis,mRotRowBitmap) )
1080
        {
1081
        int index = CUBITS[i].removeRotationNow(quat);
1082
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),index);
1083
        }
1084
    }
1085

    
1086
///////////////////////////////////////////////////////////////////////////////////////////////////
1087

    
1088
  public void initializeObject(int[][] moves)
1089
    {
1090
    solve();
1091
    setupPosition(moves);
1092
    }
1093

    
1094
///////////////////////////////////////////////////////////////////////////////////////////////////
1095

    
1096
  public int getCubit(float[] point3D)
1097
    {
1098
    float dist, minDist = Float.MAX_VALUE;
1099
    int currentBest=-1;
1100
    float multiplier = returnMultiplier();
1101

    
1102
    point3D[0] *= multiplier;
1103
    point3D[1] *= multiplier;
1104
    point3D[2] *= multiplier;
1105

    
1106
    for(int i=0; i<NUM_CUBITS; i++)
1107
      {
1108
      dist = CUBITS[i].getDistSquared(point3D);
1109
      if( dist<minDist )
1110
        {
1111
        minDist = dist;
1112
        currentBest = i;
1113
        }
1114
      }
1115

    
1116
    return currentBest;
1117
    }
1118

    
1119
///////////////////////////////////////////////////////////////////////////////////////////////////
1120

    
1121
  public int computeNearestAngle(int axis, float angle, float speed)
1122
    {
1123
    int[] basicArray = getBasicAngle();
1124
    int basicAngle   = basicArray[axis>=basicArray.length ? 0 : axis];
1125
    int nearestAngle = 360/basicAngle;
1126

    
1127
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
1128
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
1129

    
1130
    if( tmp!=0 ) return nearestAngle*tmp;
1131

    
1132
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
1133
    }
1134

    
1135
///////////////////////////////////////////////////////////////////////////////////////////////////
1136

    
1137
  public float getCameraDist()
1138
    {
1139
    return mCameraDist;
1140
    }
1141

    
1142
///////////////////////////////////////////////////////////////////////////////////////////////////
1143

    
1144
  public int getNodeSize()
1145
    {
1146
    return mNodeSize;
1147
    }
1148

    
1149
///////////////////////////////////////////////////////////////////////////////////////////////////
1150

    
1151
  public ObjectList getObjectList()
1152
    {
1153
    return mList;
1154
    }
1155

    
1156
///////////////////////////////////////////////////////////////////////////////////////////////////
1157

    
1158
  abstract float getScreenRatio();
1159
  abstract float[][] getCubitPositions(int numLayers);
1160
  abstract Static4D[] getQuats();
1161
  abstract int getNumFaces();
1162
  abstract int getNumStickerTypes(int numLayers);
1163
  abstract int getNumCubitFaces();
1164
  abstract ObjectSticker retSticker(int face);
1165
  abstract int getColor(int face);
1166
  abstract int getFaceColor(int cubit, int cubitface, int numLayers);
1167
  abstract float returnMultiplier();
1168
  abstract float[][] getCuts(int numLayers);
1169
  abstract boolean shouldResetTextureMaps();
1170
  abstract int getCubitVariant(int cubit, int numLayers);
1171
  abstract int getNumCubitVariants(int numLayers);
1172
  abstract Static4D getQuat(int cubit, int numLayers);
1173
  abstract ObjectShape getObjectShape(int cubit, int numLayers);
1174
  abstract int[] getSolvedQuats(int cubit, int numLayers);
1175
  abstract int getSolvedFunctionIndex();
1176

    
1177
  public abstract Static3D[] getRotationAxis();
1178
  public abstract int[] getBasicAngle();
1179
  public abstract void randomizeNewScramble(int[][] scramble, Random rnd, int curScramble, int totScrambles);
1180
  public abstract int getObjectName(int numLayers);
1181
  public abstract int getInventor(int numLayers);
1182
  public abstract int getComplexity(int numLayers);
1183
  }
(33-33/41)