Project

General

Profile

Download (45 KB) Statistics
| Branch: | Revision:

distorted-objectlib / src / main / java / org / distorted / objectlib / main / TwistyObject.java @ a75ae1ee

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.objectlib.main;
21

    
22
import android.content.SharedPreferences;
23
import android.content.res.Resources;
24
import android.graphics.Bitmap;
25
import android.graphics.Canvas;
26
import android.graphics.Paint;
27

    
28
import com.google.firebase.crashlytics.FirebaseCrashlytics;
29

    
30
import org.distorted.library.effect.Effect;
31
import org.distorted.library.effect.MatrixEffectMove;
32
import org.distorted.library.effect.MatrixEffectQuaternion;
33
import org.distorted.library.effect.MatrixEffectScale;
34
import org.distorted.library.effect.VertexEffectQuaternion;
35
import org.distorted.library.effect.VertexEffectRotate;
36
import org.distorted.library.main.DistortedEffects;
37
import org.distorted.library.main.DistortedLibrary;
38
import org.distorted.library.main.DistortedNode;
39
import org.distorted.library.main.DistortedTexture;
40
import org.distorted.library.main.QuatHelper;
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

    
51
import org.distorted.objectlib.BuildConfig;
52
import org.distorted.objectlib.helpers.FactoryCubit;
53
import org.distorted.objectlib.helpers.FactorySticker;
54
import org.distorted.objectlib.helpers.ObjectShape;
55
import org.distorted.objectlib.helpers.ObjectSticker;
56
import org.distorted.objectlib.helpers.ScrambleState;
57

    
58
import java.io.DataInputStream;
59
import java.io.IOException;
60
import java.io.InputStream;
61
import java.util.Random;
62

    
63
import static org.distorted.objectlib.main.Movement.MOVEMENT_TETRAHEDRON;
64
import static org.distorted.objectlib.main.Movement.MOVEMENT_HEXAHEDRON;
65
import static org.distorted.objectlib.main.Movement.MOVEMENT_OCTAHEDRON;
66
import static org.distorted.objectlib.main.Movement.MOVEMENT_DODECAHEDRON;
67
import static org.distorted.objectlib.main.Movement.MOVEMENT_SHAPECHANGE;
68

    
69
///////////////////////////////////////////////////////////////////////////////////////////////////
70

    
71
public abstract class TwistyObject extends DistortedNode
72
  {
73
  public static final int COLOR_YELLOW = 0xffffff00;
74
  public static final int COLOR_WHITE  = 0xffffffff;
75
  public static final int COLOR_BLUE   = 0xff0000ff;
76
  public static final int COLOR_GREEN  = 0xff00bb00;
77
  public static final int COLOR_RED    = 0xff990000;
78
  public static final int COLOR_ORANGE = 0xffff6200;
79
  public static final int COLOR_GREY   = 0xff727c7b;
80
  public static final int COLOR_VIOLET = 0xff7700bb;
81
  public static final int COLOR_BLACK  = 0xff000000;
82

    
83
  public static final int TEXTURE_HEIGHT = 256;
84
  static final int NUM_STICKERS_IN_ROW = 4;
85

    
86
  public static final float SQ2 = (float)Math.sqrt(2);
87
  public static final float SQ3 = (float)Math.sqrt(3);
88
  public static final float SQ5 = (float)Math.sqrt(5);
89
  public static final float SQ6 = (float)Math.sqrt(6);
90

    
91
  private static final float MAX_SIZE_CHANGE = 1.35f;
92
  private static final float MIN_SIZE_CHANGE = 0.75f;
93

    
94
  private static final Static3D CENTER = new Static3D(0,0,0);
95
  private static final int POST_ROTATION_MILLISEC = 500;
96

    
97
  protected final int NUM_FACE_COLORS;
98
  protected final int NUM_TEXTURES;
99
  protected final Cubit[] CUBITS;
100

    
101
  MeshBase[] mMeshes;
102
  final Static4D[] OBJECT_QUATS;
103
  final int NUM_CUBITS;
104
  final int NUM_AXIS;
105
  final int NUM_QUATS;
106

    
107
  private final int mNumCubitFaces;
108
  private final Static3D[] mAxis;
109
  private final float[][] mCuts;
110
  private final int[] mNumCuts;
111
  private final int mNodeW, mNodeH;
112
  private final float[][] mOrigPos;
113
  private final Static3D mNodeScale;
114
  private final Static4D mQuat;
115
  private final int[] mNumLayers;
116
  private final float mSize;
117
  private final DistortedEffects mEffects;
118
  private final VertexEffectRotate mRotateEffect;
119
  private final Dynamic1D mRotationAngle;
120
  private final Static3D mRotationAxis;
121
  private final Static3D mObjectScale;
122
  private final int[] mQuatDebug;
123
  private final float mCameraDist;
124
  private final Static1D mRotationAngleStatic, mRotationAngleMiddle, mRotationAngleFinal;
125
  private final DistortedTexture mTexture;
126
  private final float mInitScreenRatio;
127
  private final int mSolvedFunctionIndex;
128
  private final boolean mIsBandaged;
129
  private float mObjectScreenRatio;
130
  private int[][] mSolvedQuats;
131
  private int[][] mQuatMult;
132
  private int[] mTmpQuats;
133
  private int mNumTexRows, mNumTexCols;
134
  private int mRotRowBitmap;
135
  private int mCurrentRotAxis;
136
  private MeshBase mMesh;
137
  private final TwistyObjectScrambler mScrambler;
138
  private Movement mMovement;
139
  private boolean[][] mLayerRotatable;
140
  private int[][][] mEnabled;
141

    
142
  //////////////////// SOLVED1 ////////////////////////
143

    
144
  private int[] mFaceMap;
145
  private int[][] mScramble;
146
  private int[] mColors;
147

    
148
///////////////////////////////////////////////////////////////////////////////////////////////////
149

    
150
  TwistyObject(int[] numLayers, float size, Static4D quat, Static3D move, DistortedTexture nodeTexture,
151
               MeshSquare nodeMesh, DistortedEffects nodeEffects, Resources res, int surfaceW, int surfaceH)
152
    {
153
    super(nodeTexture,nodeEffects,nodeMesh);
154

    
155
    mNodeW = surfaceW;
156
    mNodeH = surfaceH;
157

    
158
    resizeFBO(mNodeW,mNodeH);
159

    
160
    mNumLayers = numLayers;
161
    mSize = size;
162
    mOrigPos = getCubitPositions(mNumLayers);
163
    mAxis = getRotationAxis();
164
    mInitScreenRatio = getScreenRatio();
165
    mNumCubitFaces = getNumCubitFaces();
166
    mSolvedFunctionIndex = getSolvedFunctionIndex();
167

    
168
    mCuts = getCuts(mNumLayers);
169
    mNumCuts = new int[mAxis.length];
170
    for(int i=0; i<mAxis.length; i++)
171
      {
172
      mNumCuts[i] = (mCuts==null || mCuts[i]==null ? 0 : mCuts[i].length);
173
      }
174

    
175
    OBJECT_QUATS = getQuats();
176
    NUM_CUBITS  = mOrigPos.length;
177
    NUM_FACE_COLORS = getNumFaceColors();
178
    NUM_TEXTURES = getNumStickerTypes(mNumLayers)*NUM_FACE_COLORS;
179
    NUM_AXIS = mAxis.length;
180
    NUM_QUATS = OBJECT_QUATS.length;
181

    
182
    int scramblingType = getScrambleType();
183
    ScrambleState[] states = getScrambleStates();
184
    mScrambler = new TwistyObjectScrambler(scramblingType,NUM_AXIS,numLayers,states);
185

    
186
    boolean bandaged=false;
187

    
188
    for(int c=0; c<NUM_CUBITS; c++)
189
      {
190
      if( mOrigPos[c].length>3 )
191
        {
192
        bandaged=true;
193
        break;
194
        }
195
      }
196

    
197
    mIsBandaged = bandaged;
198

    
199
    mQuatDebug = new int[NUM_CUBITS];
200

    
201
    mNodeScale= new Static3D(surfaceW,surfaceH,surfaceW);
202
    mQuat = quat;
203

    
204
    mRotationAngle= new Dynamic1D();
205
    mRotationAxis = new Static3D(1,0,0);
206
    mRotateEffect = new VertexEffectRotate(mRotationAngle, mRotationAxis, CENTER);
207

    
208
    mRotationAngleStatic = new Static1D(0);
209
    mRotationAngleMiddle = new Static1D(0);
210
    mRotationAngleFinal  = new Static1D(0);
211

    
212
    mObjectScale = new Static3D(1,1,1);
213
    setObjectRatioNow(1.0f);
214

    
215
    MatrixEffectScale scaleEffect = new MatrixEffectScale(mObjectScale);
216
    MatrixEffectQuaternion quatEffect  = new MatrixEffectQuaternion(quat, CENTER);
217
    MatrixEffectMove moveEffect = new MatrixEffectMove(move);
218

    
219
    MatrixEffectScale nodeScaleEffect = new MatrixEffectScale(mNodeScale);
220
    nodeEffects.apply(nodeScaleEffect);
221

    
222
    mNumTexCols = NUM_STICKERS_IN_ROW;
223
    mNumTexRows = (NUM_TEXTURES+1)/NUM_STICKERS_IN_ROW;
224

    
225
    if( mNumTexCols*mNumTexRows < NUM_TEXTURES+1 ) mNumTexRows++;
226

    
227
    CUBITS = new Cubit[NUM_CUBITS];
228
    createMeshAndCubits(res);
229
    createDataStructuresForSolved(numLayers);
230

    
231
    mTexture = new DistortedTexture();
232
    mEffects = new DistortedEffects();
233

    
234
    createTexture();
235

    
236
    for(int q=0; q<NUM_QUATS; q++)
237
      {
238
      VertexEffectQuaternion vq = new VertexEffectQuaternion(OBJECT_QUATS[q],CENTER);
239
      vq.setMeshAssociation(0,q);
240
      mEffects.apply(vq);
241
      }
242

    
243
    mEffects.apply(mRotateEffect);
244
    mEffects.apply(quatEffect);
245
    mEffects.apply(scaleEffect);
246
    mEffects.apply(moveEffect);
247

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

    
252
    attach( new DistortedNode(mTexture,mEffects,mMesh) );
253

    
254
    float fov = getFOV();
255
    double halfFOV = fov * (Math.PI/360);
256
    mCameraDist = (0.5f*mNodeH) / ((float)Math.tan(halfFOV)*mNodeW);
257

    
258
    setProjection( fov, 0.1f);
259
    }
260

    
261
///////////////////////////////////////////////////////////////////////////////////////////////////
262

    
263
  private Static3D getPos(float[] origPos)
264
    {
265
    int len = origPos.length/3;
266
    float sumX = 0.0f;
267
    float sumY = 0.0f;
268
    float sumZ = 0.0f;
269

    
270
    for(int i=0; i<len; i++)
271
      {
272
      sumX += origPos[3*i  ];
273
      sumY += origPos[3*i+1];
274
      sumZ += origPos[3*i+2];
275
      }
276

    
277
    sumX /= len;
278
    sumY /= len;
279
    sumZ /= len;
280

    
281
    return new Static3D(sumX,sumY,sumZ);
282
    }
283

    
284
///////////////////////////////////////////////////////////////////////////////////////////////////
285

    
286
  private void createMeshAndCubits(Resources res)
287
    {
288
    int resourceID= getResource(mNumLayers);
289

    
290
    if( resourceID!=0 && !ObjectControl.isInCreateMesh() )
291
      {
292
      InputStream is = res.openRawResource(resourceID);
293
      DataInputStream dos = new DataInputStream(is);
294
      mMesh = new MeshFile(dos);
295

    
296
      try
297
        {
298
        is.close();
299
        }
300
      catch(IOException e)
301
        {
302
        android.util.Log.e("meshFile", "Error closing InputStream: "+e.toString());
303
        }
304

    
305
      for(int i=0; i<NUM_CUBITS; i++)
306
        {
307
        CUBITS[i] = new Cubit(this,mOrigPos[i], NUM_AXIS);
308
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
309
        }
310

    
311
      if( shouldResetTextureMaps() ) resetAllTextureMaps();
312
      }
313
    else
314
      {
315
      MeshBase[] cubitMesh = new MeshBase[NUM_CUBITS];
316

    
317
      for(int i=0; i<NUM_CUBITS; i++)
318
        {
319
        CUBITS[i] = new Cubit(this,mOrigPos[i], NUM_AXIS);
320
        cubitMesh[i] = createCubitMesh(i,mNumLayers);
321
        Static3D pos = getPos(mOrigPos[i]);
322
        cubitMesh[i].apply(new MatrixEffectMove(pos),1,0);
323
        cubitMesh[i].setEffectAssociation(0, CUBITS[i].computeAssociation(), 0);
324
        }
325

    
326
      mMesh = new MeshJoined(cubitMesh);
327
      resetAllTextureMaps();
328
      }
329
    }
330

    
331
///////////////////////////////////////////////////////////////////////////////////////////////////
332

    
333
  private MeshBase createCubitMesh(int cubit, int[] numLayers)
334
    {
335
    int variant = getCubitVariant(cubit,numLayers);
336

    
337
    if( mMeshes==null )
338
      {
339
      FactoryCubit factory = FactoryCubit.getInstance();
340
      factory.clear();
341
      mMeshes = new MeshBase[getNumCubitVariants(numLayers)];
342
      }
343

    
344
    if( mMeshes[variant]==null )
345
      {
346
      ObjectShape shape = getObjectShape(variant);
347
      FactoryCubit factory = FactoryCubit.getInstance();
348
      factory.createNewFaceTransform(shape);
349
      mMeshes[variant] = factory.createRoundedSolid(shape);
350
      }
351

    
352
    MeshBase mesh = mMeshes[variant].copy(true);
353
    MatrixEffectQuaternion quat = new MatrixEffectQuaternion( getQuat(cubit,numLayers), new Static3D(0,0,0) );
354
    mesh.apply(quat,0xffffffff,0);
355

    
356
    return mesh;
357
    }
358

    
359
///////////////////////////////////////////////////////////////////////////////////////////////////
360

    
361
  private void createDataStructuresForSolved(int[] numLayers)
362
    {
363
    mTmpQuats = new int[NUM_QUATS];
364
    mSolvedQuats = new int[NUM_CUBITS][];
365

    
366
    for(int c=0; c<NUM_CUBITS; c++)
367
      {
368
      mSolvedQuats[c] = getSolvedQuats(c,numLayers);
369
      }
370
    }
371

    
372
///////////////////////////////////////////////////////////////////////////////////////////////////
373

    
374
  private int getMultQuat(int index1, int index2)
375
    {
376
    if( mQuatMult==null )
377
      {
378
      mQuatMult = new int[NUM_QUATS][NUM_QUATS];
379

    
380
      for(int i=0; i<NUM_QUATS; i++)
381
        for(int j=0; j<NUM_QUATS; j++) mQuatMult[i][j] = -1;
382
      }
383

    
384
    if( mQuatMult[index1][index2]==-1 )
385
      {
386
      mQuatMult[index1][index2] = mulQuat(index1,index2);
387
      }
388

    
389
    return mQuatMult[index1][index2];
390
    }
391

    
392
///////////////////////////////////////////////////////////////////////////////////////////////////
393
// This is used to build internal data structures for the generic 'isSolved()'
394
//
395
// if this is an internal cubit (all faces black): return -1
396
// if this is a face cubit (one non-black face): return the color index of the only non-black face.
397
// Color index, i.e. the index into the 'FACE_COLORS' table.
398
// else (edge or corner cubit, more than one non-black face): return -2.
399

    
400
  protected int retCubitSolvedStatus(int cubit, int[] numLayers)
401
    {
402
    int numNonBlack=0, nonBlackIndex=-1, varColor, cubColor;
403
    int variant = getCubitVariant(cubit,numLayers);
404

    
405
    for(int face=0; face<mNumCubitFaces; face++)
406
      {
407
      varColor = getVariantFaceColor(variant,face,numLayers);
408
      cubColor = getCubitFaceColor(cubit,face,numLayers);
409

    
410
      if( varColor>=0 && cubColor>=0 )
411
        {
412
        numNonBlack++;
413
        nonBlackIndex = cubColor;
414
        }
415
      }
416

    
417
    if( numNonBlack==0 ) return -1;
418
    if( numNonBlack>=2 ) return -2;
419

    
420
    return nonBlackIndex;
421
    }
422

    
423
///////////////////////////////////////////////////////////////////////////////////////////////////
424

    
425
  protected boolean shouldResetTextureMaps()
426
    {
427
    return false;
428
    }
429

    
430
///////////////////////////////////////////////////////////////////////////////////////////////////
431

    
432
  protected int[] buildSolvedQuats(Static3D faceAx, Static4D[] quats)
433
    {
434
    final float MAXD = 0.0001f;
435
    float x = faceAx.get0();
436
    float y = faceAx.get1();
437
    float z = faceAx.get2();
438
    float a,dx,dy,dz,qx,qy,qz;
439
    Static4D quat;
440

    
441
    int len = quats.length;
442
    int place = 0;
443

    
444
    for(int q=1; q<len; q++)
445
      {
446
      quat = quats[q];
447
      qx = quat.get0();
448
      qy = quat.get1();
449
      qz = quat.get2();
450

    
451
           if( x!=0.0f ) { a = qx/x; }
452
      else if( y!=0.0f ) { a = qy/y; }
453
      else               { a = qz/z; }
454

    
455
      dx = a*x-qx;
456
      dy = a*y-qy;
457
      dz = a*z-qz;
458

    
459
      if( dx>-MAXD && dx<MAXD && dy>-MAXD && dy<MAXD && dz>-MAXD && dz<MAXD )
460
        {
461
        mTmpQuats[place++] = q;
462
        }
463
      }
464

    
465
    if( place!=0 )
466
      {
467
      int[] ret = new int[place];
468
      System.arraycopy(mTmpQuats,0,ret,0,place);
469
      return ret;
470
      }
471

    
472
    return null;
473
    }
474

    
475
///////////////////////////////////////////////////////////////////////////////////////////////////
476

    
477
  private boolean isSolved0()
478
    {
479
    int len, q1,q = CUBITS[0].mQuatIndex;
480
    int[] solved;
481
    boolean skip;
482

    
483
    for(int c=1; c<NUM_CUBITS; c++)
484
      {
485
      q1 = CUBITS[c].mQuatIndex;
486

    
487
      if( q1==q ) continue;
488

    
489
      skip = false;
490
      solved = mSolvedQuats[c];
491
      len = solved==null ? 0:solved.length;
492

    
493
      for(int i=0; i<len; i++)
494
        {
495
        if( q1==getMultQuat(q,solved[i]) )
496
          {
497
          skip = true;
498
          break;
499
          }
500
        }
501

    
502
      if( !skip ) return false;
503
      }
504

    
505
    return true;
506
    }
507

    
508
///////////////////////////////////////////////////////////////////////////////////////////////////
509

    
510
  private int computeScramble(int quatNum, int centerNum)
511
    {
512
    float MAXDIFF = 0.01f;
513
    float[] center= mOrigPos[centerNum];
514
    Static4D sc = new Static4D(center[0], center[1], center[2], 1.0f);
515
    Static4D result = QuatHelper.rotateVectorByQuat(sc,OBJECT_QUATS[quatNum]);
516

    
517
    float x = result.get0();
518
    float y = result.get1();
519
    float z = result.get2();
520

    
521
    for(int c=0; c<NUM_CUBITS; c++)
522
      {
523
      float[] cent = mOrigPos[c];
524

    
525
      float qx = cent[0] - x;
526
      float qy = cent[1] - y;
527
      float qz = cent[2] - z;
528

    
529
      if( qx>-MAXDIFF && qx<MAXDIFF &&
530
          qy>-MAXDIFF && qy<MAXDIFF &&
531
          qz>-MAXDIFF && qz<MAXDIFF  ) return c;
532
      }
533

    
534
    return -1;
535
    }
536

    
537
///////////////////////////////////////////////////////////////////////////////////////////////////
538
// Dino4 uses this. It is solved if and only if groups of cubits
539
// (0,3,7), (1,2,5), (4,8,9), (6,10,11)
540
// or
541
// (0,1,4), (2,3,6), (5,9,10), (7,8,11)
542
// are all the same color.
543

    
544
  private boolean isSolved1()
545
    {
546
    if( mScramble==null )
547
      {
548
      mScramble = new int[NUM_QUATS][NUM_CUBITS];
549
      mColors   = new int[NUM_CUBITS];
550

    
551
      for(int q=0; q<NUM_QUATS; q++)
552
        for(int c=0; c<NUM_CUBITS; c++) mScramble[q][c] = computeScramble(q,c);
553
      }
554

    
555
    if( mFaceMap==null )
556
      {
557
      mFaceMap = new int[] { 4, 2, 2, 4, 0, 2, 1, 4, 0, 0, 1, 1 };
558
      }
559

    
560
    for(int c=0; c<NUM_CUBITS; c++)
561
      {
562
      int index = mScramble[CUBITS[c].mQuatIndex][c];
563
      mColors[index] = mFaceMap[c];
564
      }
565

    
566
    if( mColors[0]==mColors[3] && mColors[0]==mColors[7] &&
567
        mColors[1]==mColors[2] && mColors[1]==mColors[5] &&
568
        mColors[4]==mColors[8] && mColors[4]==mColors[9]  ) return true;
569

    
570
    if( mColors[0]==mColors[1] && mColors[0]==mColors[4] &&
571
        mColors[2]==mColors[3] && mColors[2]==mColors[6] &&
572
        mColors[5]==mColors[9] && mColors[5]==mColors[10] ) return true;
573

    
574
    return false;
575
    }
576

    
577
///////////////////////////////////////////////////////////////////////////////////////////////////
578
// Dino6 uses this. It is solved if and only if:
579
//
580
// All four 'X' cubits (i.e. those whose longest edge goes along the X axis) are rotated
581
// by the same quaternion qX, similarly all four 'Y' cubits by the same qY and all four 'Z'
582
// by the same qZ, and then either:
583
//
584
// a) qX = qY = qZ
585
// b) qY = qX*Q2 and qZ = qX*Q8  (i.e. swap of WHITE and YELLOW faces)
586
// c) qX = qY*Q2 and qZ = qY*Q10 (i.e. swap of BLUE and GREEN faces)
587
// d) qX = qZ*Q8 and qY = qZ*Q10 (i.e. swap of RED and BROWN faces)
588
//
589
// BUT: cases b), c) and d) are really the same - it's all just a mirror image of the original.
590
//
591
// X cubits: 0, 2, 8, 10
592
// Y cubits: 1, 3, 9, 11
593
// Z cubits: 4, 5, 6, 7
594

    
595
  private boolean isSolved2()
596
    {
597
    int qX = CUBITS[0].mQuatIndex;
598
    int qY = CUBITS[1].mQuatIndex;
599
    int qZ = CUBITS[4].mQuatIndex;
600

    
601
    if( CUBITS[2].mQuatIndex != qX || CUBITS[8].mQuatIndex != qX || CUBITS[10].mQuatIndex != qX ||
602
        CUBITS[3].mQuatIndex != qY || CUBITS[9].mQuatIndex != qY || CUBITS[11].mQuatIndex != qY ||
603
        CUBITS[5].mQuatIndex != qZ || CUBITS[6].mQuatIndex != qZ || CUBITS[ 7].mQuatIndex != qZ  )
604
      {
605
      return false;
606
      }
607

    
608
    return ( qX==qY && qX==qZ ) || ( qY==mulQuat(qX,2) && qZ==mulQuat(qX,8) );
609
    }
610

    
611
///////////////////////////////////////////////////////////////////////////////////////////////////
612
// Square-2 is solved iff
613
// a) all of its cubits are rotated with the same quat
614
// b) its two 'middle' cubits are rotated with the same quat, the 6 'front' and 6 'back'
615
// edges and corners with this quat multiplied by QUATS[18] (i.e. those are upside down)
616
// and all the 12 left and right edges and corners also with the same quat multiplied by
617
// QUATS[12] - i.e. also upside down.
618

    
619
  private boolean isSolved3()
620
    {
621
    int index = CUBITS[0].mQuatIndex;
622

    
623
    if( CUBITS[1].mQuatIndex!=index ) return false;
624

    
625
    boolean solved = true;
626

    
627
    for(int i=2; i<NUM_CUBITS; i++)
628
      {
629
      if( CUBITS[i].mQuatIndex!=index )
630
        {
631
        solved = false;
632
        break;
633
        }
634
      }
635

    
636
    if( solved ) return true;
637

    
638
    int indexX = mulQuat(index,12);  // QUATS[12] = 180deg (1,0,0)
639
    int indexZ = mulQuat(index,18);  // QUATS[18] = 180deg (0,0,1)
640

    
641
    for(int i= 2; i<        18; i+=2) if( CUBITS[i].mQuatIndex != indexZ ) return false;
642
    for(int i= 3; i<        18; i+=2) if( CUBITS[i].mQuatIndex != indexX ) return false;
643
    for(int i=18; i<NUM_CUBITS; i+=2) if( CUBITS[i].mQuatIndex != indexX ) return false;
644
    for(int i=19; i<NUM_CUBITS; i+=2) if( CUBITS[i].mQuatIndex != indexZ ) return false;
645

    
646
    return true;
647
    }
648

    
649
///////////////////////////////////////////////////////////////////////////////////////////////////
650

    
651
  int computeRow(float[] pos, int axisIndex)
652
    {
653
    int ret=0;
654
    int len = pos.length / 3;
655
    Static3D axis = mAxis[axisIndex];
656
    float axisX = axis.get0();
657
    float axisY = axis.get1();
658
    float axisZ = axis.get2();
659
    float casted;
660

    
661
    for(int i=0; i<len; i++)
662
      {
663
      casted = pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ;
664
      ret |= computeSingleRow(axisIndex,casted);
665
      }
666

    
667
    return ret;
668
    }
669

    
670
///////////////////////////////////////////////////////////////////////////////////////////////////
671

    
672
  private int computeSingleRow(int axisIndex,float casted)
673
    {
674
    int num = mNumCuts[axisIndex];
675

    
676
    for(int i=0; i<num; i++)
677
      {
678
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
679
      }
680

    
681
    return (1<<num);
682
    }
683

    
684
///////////////////////////////////////////////////////////////////////////////////////////////////
685

    
686
  private boolean wasRotateApplied()
687
    {
688
    return mEffects.exists(mRotateEffect.getID());
689
    }
690

    
691
///////////////////////////////////////////////////////////////////////////////////////////////////
692

    
693
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
694
    {
695
    return (CUBITS[cubit].getRotRow(axis) & rowBitmap) != 0;
696
    }
697

    
698
///////////////////////////////////////////////////////////////////////////////////////////////////
699
// note the minus in front of the sin() - we rotate counterclockwise
700
// when looking towards the direction where the axis increases in values.
701

    
702
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
703
    {
704
    Static3D axis = mAxis[axisIndex];
705

    
706
    while( angleInDegrees<0 ) angleInDegrees += 360;
707
    angleInDegrees %= 360;
708
    
709
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
710
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
711

    
712
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
713
    }
714

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

    
717
  private synchronized void setupPosition(int[][] moves)
718
    {
719
    if( moves!=null )
720
      {
721
      Static4D quat;
722
      int index, axis, rowBitmap, angle;
723
      int[] basic = getBasicAngle();
724

    
725
      for(int[] move: moves)
726
        {
727
        axis     = move[0];
728
        rowBitmap= move[1];
729
        angle    = move[2]*(360/basic[axis]);
730
        quat     = makeQuaternion(axis,angle);
731

    
732
        for(int j=0; j<NUM_CUBITS; j++)
733
          if( belongsToRotation(j,axis,rowBitmap) )
734
            {
735
            index = CUBITS[j].removeRotationNow(quat);
736
            mMesh.setEffectAssociation(j, CUBITS[j].computeAssociation(),index);
737
            }
738
        }
739
      }
740
    }
741

    
742
///////////////////////////////////////////////////////////////////////////////////////////////////
743

    
744
  public int getScrambleType()
745
    {
746
    return 0;
747
    }
748

    
749
///////////////////////////////////////////////////////////////////////////////////////////////////
750

    
751
  int computeBitmapFromRow(int rowBitmap, int axis)
752
    {
753
    if( mIsBandaged )
754
      {
755
      int bitmap, initBitmap=0;
756

    
757
      while( initBitmap!=rowBitmap )
758
        {
759
        initBitmap = rowBitmap;
760

    
761
        for(int cubit=0; cubit<NUM_CUBITS; cubit++)
762
          {
763
          bitmap = CUBITS[cubit].getRotRow(axis);
764
          if( (rowBitmap & bitmap) != 0 ) rowBitmap |= bitmap;
765
          }
766
        }
767
      }
768

    
769
    return rowBitmap;
770
    }
771

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

    
776
  void clampPos(float[] pos, int offset)
777
    {
778
    float currError, minError = Float.MAX_VALUE;
779
    int minErrorIndex1 = -1;
780
    int minErrorIndex2 = -1;
781

    
782
    float x = pos[offset  ];
783
    float y = pos[offset+1];
784
    float z = pos[offset+2];
785

    
786
    float xo,yo,zo;
787

    
788
    for(int i=0; i<NUM_CUBITS; i++)
789
      {
790
      int len = mOrigPos[i].length / 3;
791

    
792
      for(int j=0; j<len; j++)
793
        {
794
        xo = mOrigPos[i][3*j  ];
795
        yo = mOrigPos[i][3*j+1];
796
        zo = mOrigPos[i][3*j+2];
797

    
798
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
799

    
800
        if( currError<minError )
801
          {
802
          minError = currError;
803
          minErrorIndex1 = i;
804
          minErrorIndex2 = j;
805
          }
806
        }
807
      }
808

    
809
    if( minError< 0.1f ) // TODO: 0.1 ?
810
      {
811
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
812
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
813
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
814
      }
815
    }
816

    
817
///////////////////////////////////////////////////////////////////////////////////////////////////
818
// remember about the double cover or unit quaternions!
819

    
820
  int mulQuat(int q1, int q2)
821
    {
822
    Static4D result = QuatHelper.quatMultiply(OBJECT_QUATS[q1],OBJECT_QUATS[q2]);
823

    
824
    float rX = result.get0();
825
    float rY = result.get1();
826
    float rZ = result.get2();
827
    float rW = result.get3();
828

    
829
    final float MAX_ERROR = 0.1f;
830
    float dX,dY,dZ,dW;
831

    
832
    for(int i=0; i<NUM_QUATS; i++)
833
      {
834
      dX = OBJECT_QUATS[i].get0() - rX;
835
      dY = OBJECT_QUATS[i].get1() - rY;
836
      dZ = OBJECT_QUATS[i].get2() - rZ;
837
      dW = OBJECT_QUATS[i].get3() - rW;
838

    
839
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
840
          dY<MAX_ERROR && dY>-MAX_ERROR &&
841
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
842
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
843

    
844
      dX = OBJECT_QUATS[i].get0() + rX;
845
      dY = OBJECT_QUATS[i].get1() + rY;
846
      dZ = OBJECT_QUATS[i].get2() + rZ;
847
      dW = OBJECT_QUATS[i].get3() + rW;
848

    
849
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
850
          dY<MAX_ERROR && dY>-MAX_ERROR &&
851
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
852
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
853
      }
854

    
855
    return -1;
856
    }
857

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

    
860
  private float getAngle()
861
    {
862
    int pointNum = mRotationAngle.getNumPoints();
863

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

    
876
///////////////////////////////////////////////////////////////////////////////////////////////////
877

    
878
  private void recordQuatsState(String message)
879
    {
880
    StringBuilder quats = new StringBuilder();
881

    
882
    for(int j=0; j<NUM_CUBITS; j++)
883
      {
884
      quats.append(mQuatDebug[j]);
885
      quats.append(" ");
886
      }
887

    
888
    String name = intGetObjectType(mNumLayers).name();
889

    
890
    if( BuildConfig.DEBUG )
891
      {
892
      android.util.Log.e("quats" , quats.toString());
893
      android.util.Log.e("object", name);
894
      }
895
    else
896
      {
897
      Exception ex = new Exception(message);
898
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
899
      crashlytics.setCustomKey("quats" , quats.toString());
900
      crashlytics.setCustomKey("object", name);
901
      crashlytics.recordException(ex);
902
      }
903
    }
904

    
905
///////////////////////////////////////////////////////////////////////////////////////////////////
906

    
907
  void initializeObject(int[][] moves)
908
    {
909
    solve();
910
    setupPosition(moves);
911
    }
912

    
913
///////////////////////////////////////////////////////////////////////////////////////////////////
914

    
915
  synchronized void removeRotationNow()
916
    {
917
    float angle = getAngle();
918
    double nearestAngleInRadians = angle*Math.PI/180;
919
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
920
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
921
    float axisX = mAxis[mCurrentRotAxis].get0();
922
    float axisY = mAxis[mCurrentRotAxis].get1();
923
    float axisZ = mAxis[mCurrentRotAxis].get2();
924
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
925

    
926
    mRotationAngle.removeAll();
927
    mRotationAngleStatic.set0(0);
928

    
929
    for(int i=0; i<NUM_CUBITS; i++)
930
      if( belongsToRotation(i, mCurrentRotAxis,mRotRowBitmap) )
931
        {
932
        int index = CUBITS[i].removeRotationNow(quat);
933
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),index);
934
        }
935
    }
936

    
937
///////////////////////////////////////////////////////////////////////////////////////////////////
938

    
939
  long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
940
    {
941
    if( wasRotateApplied() )
942
      {
943
      float angle = getAngle();
944
      mRotationAngleStatic.set0(angle);
945
      mRotationAngleFinal.set0(nearestAngleInDegrees);
946
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
947

    
948
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
949
      mRotationAngle.resetToBeginning();
950
      mRotationAngle.removeAll();
951
      mRotationAngle.add(mRotationAngleStatic);
952
      mRotationAngle.add(mRotationAngleMiddle);
953
      mRotationAngle.add(mRotationAngleFinal);
954
      mRotateEffect.notifyWhenFinished(listener);
955

    
956
      return mRotateEffect.getID();
957
      }
958

    
959
    return 0;
960
    }
961

    
962
///////////////////////////////////////////////////////////////////////////////////////////////////
963

    
964
  synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
965
    {
966
    if( wasRotateApplied() )
967
      {
968
      mCurrentRotAxis = axis;
969
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
970

    
971
      mRotationAngleStatic.set0(0.0f);
972
      mRotationAxis.set( mAxis[axis] );
973
      mRotationAngle.setDuration(durationMillis);
974
      mRotationAngle.resetToBeginning();
975
      mRotationAngle.add(new Static1D(0));
976
      mRotationAngle.add(new Static1D(angle));
977
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*ObjectType.MAX_OBJECT_SIZE) , -1);
978
      mRotateEffect.notifyWhenFinished(listener);
979

    
980
      return mRotateEffect.getID();
981
      }
982

    
983
    return 0;
984
    }
985

    
986
///////////////////////////////////////////////////////////////////////////////////////////////////
987

    
988
  void continueRotation(float angleInDegrees)
989
    {
990
    mRotationAngleStatic.set0(angleInDegrees);
991
    }
992

    
993
///////////////////////////////////////////////////////////////////////////////////////////////////
994

    
995
  synchronized void beginNewRotation(int axis, int row )
996
    {
997
    if( axis<0 || axis>=NUM_AXIS )
998
      {
999
      android.util.Log.e("object", "invalid rotation axis: "+axis);
1000
      return;
1001
      }
1002
    if( row<0 || row>=mNumLayers[axis] )
1003
      {
1004
      android.util.Log.e("object", "invalid rotation row: "+row);
1005
      return;
1006
      }
1007

    
1008
    mCurrentRotAxis = axis;
1009
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
1010
    mRotationAngleStatic.set0(0.0f);
1011
    mRotationAxis.set( mAxis[axis] );
1012
    mRotationAngle.add(mRotationAngleStatic);
1013
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*ObjectType.MAX_OBJECT_SIZE) , -1);
1014
    }
1015

    
1016
///////////////////////////////////////////////////////////////////////////////////////////////////
1017

    
1018
  void setTextureMap(int cubit, int face, int newColor)
1019
    {
1020
    final float ratioW = 1.0f/mNumTexCols;
1021
    final float ratioH = 1.0f/mNumTexRows;
1022
    final Static4D[] maps = new Static4D[mNumCubitFaces];
1023
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
1024
    int col = newColor%mNumTexCols;
1025

    
1026
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1027
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1028
    }
1029

    
1030
///////////////////////////////////////////////////////////////////////////////////////////////////
1031

    
1032
  void resetAllTextureMaps()
1033
    {
1034
    final float ratioW = 1.0f/mNumTexCols;
1035
    final float ratioH = 1.0f/mNumTexRows;
1036
    int cubColor, varColor, color, variant, row, col;
1037

    
1038
    for(int cubit=0; cubit<NUM_CUBITS; cubit++)
1039
      {
1040
      final Static4D[] maps = new Static4D[mNumCubitFaces];
1041
      variant = getCubitVariant(cubit,mNumLayers);
1042

    
1043
      for(int face=0; face<mNumCubitFaces; face++)
1044
        {
1045
        cubColor = getCubitFaceColor(cubit,face,mNumLayers);
1046
        varColor = getVariantFaceColor(variant,face,mNumLayers);
1047
        color    = cubColor<0 || varColor<0 ? NUM_TEXTURES : varColor*NUM_FACE_COLORS + cubColor;
1048
        row      = (mNumTexRows-1) - color/mNumTexCols;
1049
        col      = color%mNumTexCols;
1050

    
1051
        maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1052
        }
1053

    
1054
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1055
      }
1056
    }
1057

    
1058
///////////////////////////////////////////////////////////////////////////////////////////////////
1059

    
1060
  void releaseResources()
1061
    {
1062
    mTexture.markForDeletion();
1063
    mMesh.markForDeletion();
1064
    mEffects.markForDeletion();
1065

    
1066
    for(int j=0; j<NUM_CUBITS; j++)
1067
      {
1068
      CUBITS[j].releaseResources();
1069
      }
1070
    }
1071

    
1072
///////////////////////////////////////////////////////////////////////////////////////////////////
1073

    
1074
  synchronized void restorePreferences(SharedPreferences preferences)
1075
    {
1076
    boolean error = false;
1077

    
1078
    for(int i=0; i<NUM_CUBITS; i++)
1079
      {
1080
      mQuatDebug[i] = CUBITS[i].restorePreferences(preferences);
1081

    
1082
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<NUM_QUATS)
1083
        {
1084
        CUBITS[i].modifyCurrentPosition(OBJECT_QUATS[mQuatDebug[i]]);
1085
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),mQuatDebug[i]);
1086
        }
1087
      else
1088
        {
1089
        error = true;
1090
        }
1091
      }
1092

    
1093
    if( error )
1094
      {
1095
      for(int i=0; i<NUM_CUBITS; i++)
1096
        {
1097
        CUBITS[i].solve();
1098
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),0);
1099
        }
1100
      recordQuatsState("Failed to restorePreferences");
1101
      }
1102
    }
1103

    
1104
///////////////////////////////////////////////////////////////////////////////////////////////////
1105

    
1106
  void savePreferences(SharedPreferences.Editor editor)
1107
    {
1108
    for(int i=0; i<NUM_CUBITS; i++) CUBITS[i].savePreferences(editor);
1109
    }
1110

    
1111
///////////////////////////////////////////////////////////////////////////////////////////////////
1112

    
1113
  void recomputeScaleFactor(int surfaceW, int surfaceH)
1114
    {
1115
    mNodeScale.set(surfaceW,surfaceH,surfaceW);
1116
    }
1117

    
1118
///////////////////////////////////////////////////////////////////////////////////////////////////
1119
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
1120

    
1121
  void createTexture()
1122
    {
1123
    Bitmap bitmap;
1124

    
1125
    Paint paint = new Paint();
1126
    bitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_8888);
1127
    Canvas canvas = new Canvas(bitmap);
1128

    
1129
    paint.setAntiAlias(true);
1130
    paint.setTextAlign(Paint.Align.CENTER);
1131
    paint.setStyle(Paint.Style.FILL);
1132

    
1133
    paint.setColor(COLOR_BLACK);
1134
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
1135

    
1136
    int texture = 0;
1137
    FactorySticker factory = FactorySticker.getInstance();
1138

    
1139
    for(int row=0; row<mNumTexRows; row++)
1140
      for(int col=0; col<mNumTexCols; col++)
1141
        {
1142
        if( texture>=NUM_TEXTURES ) break;
1143
        ObjectSticker sticker = retSticker(texture/NUM_FACE_COLORS);
1144
        int color = getColor(texture%NUM_FACE_COLORS);
1145
        factory.drawRoundedPolygon(canvas, paint, col*TEXTURE_HEIGHT, row*TEXTURE_HEIGHT, color, sticker);
1146
        texture++;
1147
        }
1148

    
1149
    if( !mTexture.setTexture(bitmap) )
1150
      {
1151
      int max = DistortedLibrary.getMaxTextureSize();
1152
      FirebaseCrashlytics crashlytics = FirebaseCrashlytics.getInstance();
1153
      crashlytics.log("failed to set texture of size "+bitmap.getWidth()+"x"+bitmap.getHeight()+" max is "+max);
1154
      }
1155
    }
1156

    
1157
///////////////////////////////////////////////////////////////////////////////////////////////////
1158

    
1159
  void setObjectRatioNow(float sc)
1160
    {
1161
    mObjectScreenRatio = sc;
1162
    int nodeMinSize = Math.min(mNodeW,mNodeH);
1163
    float scale = mObjectScreenRatio*mInitScreenRatio*nodeMinSize/mSize;
1164
    mObjectScale.set(scale,scale,scale);
1165
    }
1166

    
1167
///////////////////////////////////////////////////////////////////////////////////////////////////
1168

    
1169
  void setObjectRatio(float sizeChange)
1170
    {
1171
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
1172

    
1173
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
1174
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
1175

    
1176
    setObjectRatioNow(mObjectScreenRatio);
1177
    }
1178

    
1179
///////////////////////////////////////////////////////////////////////////////////////////////////
1180

    
1181
  float getObjectRatio()
1182
    {
1183
    return mObjectScreenRatio*mInitScreenRatio;
1184
    }
1185

    
1186
///////////////////////////////////////////////////////////////////////////////////////////////////
1187

    
1188
  public float getRatio()
1189
    {
1190
    return mObjectScreenRatio;
1191
    }
1192

    
1193
///////////////////////////////////////////////////////////////////////////////////////////////////
1194

    
1195
  boolean isSolved()
1196
    {
1197
    if( mSolvedFunctionIndex==0 ) return isSolved0();
1198
    if( mSolvedFunctionIndex==1 ) return isSolved1();
1199
    if( mSolvedFunctionIndex==2 ) return isSolved2();
1200
    if( mSolvedFunctionIndex==3 ) return isSolved3();
1201

    
1202
    return false;
1203
    }
1204

    
1205
///////////////////////////////////////////////////////////////////////////////////////////////////
1206
// only called with figuring out which cubit was touched in MODE_REPLACE, which is only used in
1207
// during setting up the initial position in the solver.
1208

    
1209
  int getCubit(float[] point3D)
1210
    {
1211
    float dist, minDist = Float.MAX_VALUE;
1212
    int currentBest=-1;
1213
    float multiplier = mNumLayers[0];
1214

    
1215
    point3D[0] *= multiplier;
1216
    point3D[1] *= multiplier;
1217
    point3D[2] *= multiplier;
1218

    
1219
    for(int i=0; i<NUM_CUBITS; i++)
1220
      {
1221
      dist = CUBITS[i].getDistSquared(point3D);
1222
      if( dist<minDist )
1223
        {
1224
        minDist = dist;
1225
        currentBest = i;
1226
        }
1227
      }
1228

    
1229
    return currentBest;
1230
    }
1231

    
1232
///////////////////////////////////////////////////////////////////////////////////////////////////
1233

    
1234
  int computeNearestAngle(int axis, float angle, float speed)
1235
    {
1236
    int[] basicArray = getBasicAngle();
1237
    int basicAngle   = basicArray[axis>=basicArray.length ? 0 : axis];
1238
    int nearestAngle = 360/basicAngle;
1239

    
1240
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
1241
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
1242

    
1243
    if( tmp!=0 ) return nearestAngle*tmp;
1244

    
1245
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
1246
    }
1247

    
1248
///////////////////////////////////////////////////////////////////////////////////////////////////
1249

    
1250
  float getCameraDist()
1251
    {
1252
    return mCameraDist;
1253
    }
1254

    
1255
///////////////////////////////////////////////////////////////////////////////////////////////////
1256
// INTERNAL API - those are called from 'effects' package
1257
///////////////////////////////////////////////////////////////////////////////////////////////////
1258

    
1259
  public void randomizeNewScramble(int[][] scramble, Random rnd, int curr, int total)
1260
    {
1261
    mScrambler.randomizeNewScramble(scramble,rnd,curr,total);
1262
    }
1263

    
1264
///////////////////////////////////////////////////////////////////////////////////////////////////
1265

    
1266
  public int getNodeWidth()
1267
    {
1268
    return mNodeW;
1269
    }
1270

    
1271
///////////////////////////////////////////////////////////////////////////////////////////////////
1272

    
1273
  public Static4D getRotationQuat()
1274
    {
1275
    return mQuat;
1276
    }
1277

    
1278
///////////////////////////////////////////////////////////////////////////////////////////////////
1279

    
1280
  public float getSize()
1281
    {
1282
    return mSize;
1283
    }
1284

    
1285
///////////////////////////////////////////////////////////////////////////////////////////////////
1286

    
1287
  public void apply(Effect effect, int position)
1288
    {
1289
    mEffects.apply(effect, position);
1290
    }
1291

    
1292
///////////////////////////////////////////////////////////////////////////////////////////////////
1293

    
1294
  public void remove(long effectID)
1295
    {
1296
    mEffects.abortById(effectID);
1297
    }
1298

    
1299
///////////////////////////////////////////////////////////////////////////////////////////////////
1300

    
1301
  public MeshBase getObjectMesh()
1302
    {
1303
    return mMesh;
1304
    }
1305

    
1306
///////////////////////////////////////////////////////////////////////////////////////////////////
1307

    
1308
  public DistortedEffects getObjectEffects()
1309
    {
1310
    return mEffects;
1311
    }
1312

    
1313
///////////////////////////////////////////////////////////////////////////////////////////////////
1314
// PUBLIC API
1315
///////////////////////////////////////////////////////////////////////////////////////////////////
1316

    
1317
  public int getCubitFaceColorIndex(int cubit, int face)
1318
    {
1319
    Static4D texMap = mMesh.getTextureMap(NUM_FACE_COLORS*cubit + face);
1320

    
1321
    int x = (int)(texMap.get0()/texMap.get2());
1322
    int y = (int)(texMap.get1()/texMap.get3());
1323

    
1324
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
1325
    }
1326

    
1327
///////////////////////////////////////////////////////////////////////////////////////////////////
1328

    
1329
  public int[] getNumLayers()
1330
    {
1331
    return mNumLayers;
1332
    }
1333

    
1334
///////////////////////////////////////////////////////////////////////////////////////////////////
1335

    
1336
  public synchronized void solve()
1337
    {
1338
    for(int i=0; i<NUM_CUBITS; i++)
1339
      {
1340
      CUBITS[i].solve();
1341
      mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
1342
      }
1343
    }
1344

    
1345
///////////////////////////////////////////////////////////////////////////////////////////////////
1346

    
1347
  public ObjectType getObjectType()
1348
    {
1349
    return intGetObjectType(mNumLayers);
1350
    }
1351

    
1352
///////////////////////////////////////////////////////////////////////////////////////////////////
1353

    
1354
  public Movement getMovement()
1355
    {
1356
    if( mMovement==null )
1357
      {
1358
      int[] numLayers = getNumLayers();
1359
      if( mCuts==null ) getCuts(numLayers);
1360
      if( mLayerRotatable==null ) mLayerRotatable = getLayerRotatable(numLayers);
1361
      if( mEnabled==null ) mEnabled = getEnabled();
1362

    
1363
      int movementType = getMovementType();
1364
      int movementSplit= getMovementSplit();
1365

    
1366
      switch(movementType)
1367
        {
1368
        case MOVEMENT_TETRAHEDRON : mMovement = new Movement4(mAxis,mCuts,mLayerRotatable,mSize,movementSplit,mEnabled);
1369
                                    break;
1370
        case MOVEMENT_HEXAHEDRON  : mMovement = new Movement6(mAxis,mCuts,mLayerRotatable,mSize,movementSplit,mEnabled);
1371
                                    break;
1372
        case MOVEMENT_OCTAHEDRON  : mMovement = new Movement8(mAxis,mCuts,mLayerRotatable,mSize,movementSplit,mEnabled);
1373
                                    break;
1374
        case MOVEMENT_DODECAHEDRON: mMovement = new Movement12(mAxis,mCuts,mLayerRotatable,mSize,movementSplit,mEnabled);
1375
                                    break;
1376
        case MOVEMENT_SHAPECHANGE : float[] dist3D = getDist3D(numLayers);
1377
                                    mMovement = new MovementC(mAxis,mCuts,mLayerRotatable,mSize,movementSplit,mEnabled,dist3D);
1378
                                    break;
1379
        }
1380
      }
1381
    return mMovement;
1382
    }
1383

    
1384
///////////////////////////////////////////////////////////////////////////////////////////////////
1385

    
1386
  protected abstract int getFOV();
1387
  protected abstract float getScreenRatio();
1388
  protected abstract int getColor(int face);
1389
  protected abstract int getResource(int[] numLayers);
1390
  protected abstract ObjectType intGetObjectType(int[] numLayers);
1391

    
1392
  // for JSON only
1393
  public abstract int getSolvedFunctionIndex();
1394
  public abstract int getMovementType();
1395
  public abstract int getMovementSplit();
1396
  public abstract boolean[][] getLayerRotatable(int[] numLayers);
1397
  public abstract int[][][] getEnabled();
1398
  public abstract float[] getDist3D(int[] numLayers);
1399
  public abstract ScrambleState[] getScrambleStates();
1400
  public abstract float[][] getCuts(int[] numLayers);
1401
  public abstract Static4D[] getQuats();
1402
  public abstract int getNumStickerTypes(int[] numLayers);
1403
  public abstract ObjectSticker retSticker(int sticker);
1404
  public abstract int getCubitVariant(int cubit, int[] numLayers);
1405
  public abstract ObjectShape getObjectShape(int variant);
1406
  public abstract int getNumCubitVariants(int[] numLayers);
1407
  public abstract float[][] getCubitPositions(int[] numLayers);
1408
  public abstract Static4D getQuat(int cubit, int[] numLayers);
1409
  public abstract int[] getSolvedQuats(int cubit, int[] numLayers);
1410
  public abstract int getCubitFaceColor(int cubit, int face, int[] numLayers);
1411
  public abstract int getVariantFaceColor(int variant, int face, int[] numLayers);
1412
  public abstract int getNumFaceColors();
1413
  public abstract int getNumCubitFaces();
1414

    
1415
  // not only for JSON
1416
  public abstract Static3D[] getRotationAxis();
1417
  public abstract int[] getBasicAngle();
1418
  public abstract int getNumFaces();
1419
  public abstract int getObjectName(int[] numLayers);
1420
  public abstract int getInventor(int[] numLayers);
1421
  public abstract int getYearOfInvention(int[] numLayers);
1422
  public abstract int getComplexity(int[] numLayers);
1423
  }
(15-15/16)