Project

General

Profile

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

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

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 java.io.DataInputStream;
23
import java.io.IOException;
24
import java.io.InputStream;
25
import java.util.Random;
26

    
27
import android.content.SharedPreferences;
28
import android.graphics.Bitmap;
29
import android.graphics.Canvas;
30
import android.graphics.Paint;
31

    
32
import org.distorted.library.effect.Effect;
33
import org.distorted.library.effect.MatrixEffectMove;
34
import org.distorted.library.effect.MatrixEffectQuaternion;
35
import org.distorted.library.effect.MatrixEffectScale;
36
import org.distorted.library.effect.VertexEffectQuaternion;
37
import org.distorted.library.effect.VertexEffectRotate;
38
import org.distorted.library.main.DistortedEffects;
39
import org.distorted.library.main.DistortedLibrary;
40
import org.distorted.library.main.DistortedNode;
41
import org.distorted.library.main.DistortedTexture;
42
import org.distorted.library.main.QuatHelper;
43
import org.distorted.library.mesh.MeshBase;
44
import org.distorted.library.mesh.MeshFile;
45
import org.distorted.library.mesh.MeshJoined;
46
import org.distorted.library.message.EffectListener;
47
import org.distorted.library.type.Dynamic1D;
48
import org.distorted.library.type.Static1D;
49
import org.distorted.library.type.Static3D;
50
import org.distorted.library.type.Static4D;
51

    
52
import org.distorted.objectlib.helpers.FactoryCubit;
53
import org.distorted.objectlib.helpers.FactorySticker;
54
import org.distorted.objectlib.helpers.ObjectLibInterface;
55
import org.distorted.objectlib.helpers.ObjectShape;
56
import org.distorted.objectlib.helpers.ObjectSticker;
57
import org.distorted.objectlib.helpers.ScrambleState;
58
import org.distorted.objectlib.json.JsonReader;
59
import org.distorted.objectlib.touchcontrol.*;
60

    
61
import static org.distorted.objectlib.touchcontrol.TouchControl.*;
62

    
63
///////////////////////////////////////////////////////////////////////////////////////////////////
64

    
65
public abstract class TwistyObject
66
  {
67
  public static final int MESH_NICE = 0;
68
  public static final int MESH_FAST = 1;
69

    
70
  public static final int COLOR_YELLOW  = 0xffffff00;
71
  public static final int COLOR_WHITE   = 0xffffffff;
72
  public static final int COLOR_BLUE    = 0xff0000ff;
73
  public static final int COLOR_GREEN   = 0xff00bb00;
74
  public static final int COLOR_RED     = 0xff990000;
75
  public static final int COLOR_ORANGE  = 0xffff6200;
76
  public static final int COLOR_GREY    = 0xff727c7b;
77
  public static final int COLOR_VIOLET  = 0xff7700bb;
78
  public static final int COLOR_INTERNAL= 0xff000000;
79

    
80
  public static final int TEXTURE_HEIGHT = 256;
81
  static final int NUM_STICKERS_IN_ROW = 4;
82

    
83
  public static final float SQ2 = (float)Math.sqrt(2);
84
  public static final float SQ3 = (float)Math.sqrt(3);
85
  public static final float SQ5 = (float)Math.sqrt(5);
86
  public static final float SQ6 = (float)Math.sqrt(6);
87

    
88
  private static final float MAX_SIZE_CHANGE = 1.35f;
89
  private static final float MIN_SIZE_CHANGE = 0.75f;
90

    
91
  private static final Static3D CENTER = new Static3D(0,0,0);
92
  private static final int POST_ROTATION_MILLISEC = 500;
93

    
94
  protected int NUM_FACE_COLORS;
95
  protected int NUM_TEXTURES;
96
  protected Cubit[] CUBITS;
97
  protected float[][] mStickerCoords;
98
  protected int[][] mStickerVariants;
99
  protected float[] mStickerScales;
100

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

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

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

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

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

    
150
  TwistyObject(InputStream jsonStream, int meshState, Static4D quat, Static3D move, float scale, InputStream meshStream)
151
    {
152
    JsonReader reader = new JsonReader();
153
    reader.parseJsonFile(jsonStream);
154
    setReader(reader);
155

    
156
    mNumLayers = reader.getNumLayers();
157
    mSize      = reader.getSize();
158
    initialize(meshState,quat,move,scale,meshStream,true);
159
    }
160

    
161
///////////////////////////////////////////////////////////////////////////////////////////////////
162

    
163
  TwistyObject(int[] numLayers, int meshState, float size, Static4D quat, Static3D move, float scale, InputStream meshStream)
164
    {
165
    mNumLayers = numLayers;
166
    mSize      = size;
167
    initialize(meshState,quat,move,scale,meshStream,false);
168
    }
169

    
170
///////////////////////////////////////////////////////////////////////////////////////////////////
171

    
172
  private void initialize(int meshState,Static4D quat, Static3D move, float scale, InputStream stream, boolean fromJSON)
173
    {
174
    mQuat = quat;
175
    mOrigPos = getCubitPositions(mNumLayers);
176
    mAxis = getRotationAxis();
177
    mInitScreenRatio = getScreenRatio();
178
    mNumCubitFaces = getNumCubitFaces();
179
    mSolvedFunctionIndex = getSolvedFunctionIndex();
180

    
181
    int numAxis = mAxis.length;
182
    SHIFT = -1;
183

    
184
    mCuts = getCuts(mNumLayers);
185
    mNumCuts = new int[numAxis];
186
    for(int i=0; i<numAxis; i++)
187
      {
188
      if( SHIFT<mNumLayers[i] ) SHIFT = mNumLayers[i];
189
      mNumCuts[i] = (mCuts==null || mCuts[i]==null ? 0 : mCuts[i].length);
190
      }
191

    
192
    OBJECT_QUATS = getQuats();
193
    NUM_CUBITS  = mOrigPos.length;
194
    NUM_FACE_COLORS = getNumFaceColors();
195
    NUM_AXIS = mAxis.length;
196
    NUM_QUATS = OBJECT_QUATS.length;
197

    
198
    int scramblingType = getScrambleType();
199
    ScrambleState[] states = getScrambleStates();
200
    mScrambler = new TwistyObjectScrambler(scramblingType,NUM_AXIS,mNumLayers,states);
201

    
202
    boolean bandaged=false;
203

    
204
    for(int c=0; c<NUM_CUBITS; c++)
205
      {
206
      if( mOrigPos[c].length>3 )
207
        {
208
        bandaged=true;
209
        break;
210
        }
211
      }
212

    
213
    mIsBandaged = bandaged;
214
    mQuatDebug = new int[NUM_CUBITS];
215

    
216
    mRotationAngle= new Dynamic1D();
217
    mRotationAxis = new Static3D(1,0,0);
218
    mRotateEffect = new VertexEffectRotate(mRotationAngle, mRotationAxis, CENTER);
219

    
220
    mRotationAngleStatic = new Static1D(0);
221
    mRotationAngleMiddle = new Static1D(0);
222
    mRotationAngleFinal  = new Static1D(0);
223

    
224
    mObjectScale = new Static3D(scale,scale,scale);
225
    setObjectRatioNow(scale,720);
226

    
227
    MatrixEffectScale scaleEffect = new MatrixEffectScale(mObjectScale);
228
    MatrixEffectQuaternion quatEffect = new MatrixEffectQuaternion(mQuat, CENTER);
229
    MatrixEffectMove moveEffect = new MatrixEffectMove(move);
230

    
231
    CUBITS = new Cubit[NUM_CUBITS];
232
    boolean fromDMESH = (stream!=null && meshState==MESH_NICE);
233
    createMeshAndCubits(stream,meshState,fromDMESH);
234
    setUpTextures(fromDMESH,fromJSON);
235
    createDataStructuresForSolved(mNumLayers);
236

    
237
    mEffects = new DistortedEffects();
238

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

    
246
    mEffects.apply(mRotateEffect);
247
    mEffects.apply(quatEffect);
248
    mEffects.apply(scaleEffect);
249
    mEffects.apply(moveEffect);
250

    
251
    mNode = new DistortedNode(mTexture,mEffects,mMesh);
252
    }
253

    
254
///////////////////////////////////////////////////////////////////////////////////////////////////
255

    
256
  private void setUpTextures(boolean fromDMESH, boolean fromJSON)
257
    {
258
    mTexture = new DistortedTexture();
259

    
260
    if( fromJSON )
261
      {
262
      mNumStickerTypes = getNumStickerTypes();
263
      }
264
    else
265
      {
266
      FactoryCubit factory = FactoryCubit.getInstance();
267

    
268
      if( fromDMESH )
269
        {
270
        factory.clear();
271
        int numVariants = getNumCubitVariants(mNumLayers);
272

    
273
        for(int i=0; i<numVariants; i++)
274
          {
275
          ObjectShape shape = getObjectShape(i);
276
          factory.createNewFaceTransform(shape);
277
          }
278
        }
279

    
280
      mStickerCoords   = factory.getOuterStickerCoords();
281
      mStickerVariants = factory.getStickerVariants();
282
      mStickerScales   = factory.getOuterStickerScales();
283
      mNumStickerTypes = mStickerCoords.length;
284

    
285
      adjustStickerCoords();
286
      }
287

    
288
    NUM_TEXTURES = NUM_FACE_COLORS*mNumStickerTypes;
289
    mNumTexCols = NUM_STICKERS_IN_ROW;
290
    mNumTexRows = (NUM_TEXTURES+1)/NUM_STICKERS_IN_ROW;
291
    if( mNumTexCols*mNumTexRows < NUM_TEXTURES+1 ) mNumTexRows++;
292

    
293
    if( !fromDMESH || shouldResetTextureMaps() ) resetAllTextureMaps();
294
    setTexture();
295
    }
296

    
297
///////////////////////////////////////////////////////////////////////////////////////////////////
298

    
299
  private Static3D getPos(float[] origPos)
300
    {
301
    int len = origPos.length/3;
302
    float sumX = 0.0f;
303
    float sumY = 0.0f;
304
    float sumZ = 0.0f;
305

    
306
    for(int i=0; i<len; i++)
307
      {
308
      sumX += origPos[3*i  ];
309
      sumY += origPos[3*i+1];
310
      sumZ += origPos[3*i+2];
311
      }
312

    
313
    sumX /= len;
314
    sumY /= len;
315
    sumZ /= len;
316

    
317
    return new Static3D(sumX,sumY,sumZ);
318
    }
319

    
320
///////////////////////////////////////////////////////////////////////////////////////////////////
321

    
322
  private void createMeshAndCubits(InputStream stream, int meshState, boolean fromDMESH)
323
    {
324
    if( fromDMESH )
325
      {
326
      DataInputStream dos = new DataInputStream(stream);
327
      mMesh = new MeshFile(dos);
328

    
329
      try
330
        {
331
        stream.close();
332
        }
333
      catch(IOException e)
334
        {
335
        android.util.Log.e("meshFile", "Error closing InputStream: "+e.toString());
336
        }
337

    
338
      for(int i=0; i<NUM_CUBITS; i++)
339
        {
340
        CUBITS[i] = new Cubit(this,mOrigPos[i], NUM_AXIS);
341
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
342
        }
343
      }
344
    else
345
      {
346
      MeshBase[] cubitMesh = new MeshBase[NUM_CUBITS];
347

    
348
      for(int i=0; i<NUM_CUBITS; i++)
349
        {
350
        CUBITS[i] = new Cubit(this,mOrigPos[i], NUM_AXIS);
351
        cubitMesh[i] = createCubitMesh(i,mNumLayers,meshState);
352
        Static3D pos = getPos(mOrigPos[i]);
353
        cubitMesh[i].apply(new MatrixEffectMove(pos),1,0);
354
        cubitMesh[i].setEffectAssociation(0, CUBITS[i].computeAssociation(), 0);
355
        }
356

    
357
      mMesh = new MeshJoined(cubitMesh);
358
      }
359
    }
360

    
361
///////////////////////////////////////////////////////////////////////////////////////////////////
362

    
363
  private MeshBase createCubitMesh(int cubit, int[] numLayers, int meshState)
364
    {
365
    int variant = getCubitVariant(cubit,numLayers);
366

    
367
    if( mMeshes==null )
368
      {
369
      FactoryCubit factory = FactoryCubit.getInstance();
370
      factory.clear();
371
      mMeshes = new MeshBase[getNumCubitVariants(numLayers)];
372
      }
373

    
374
    if( mMeshes[variant]==null )
375
      {
376
      ObjectShape shape = getObjectShape(variant);
377
      FactoryCubit factory = FactoryCubit.getInstance();
378
      factory.createNewFaceTransform(shape);
379
      mMeshes[variant] = factory.createRoundedSolid(shape,meshState);
380
      }
381

    
382
    MeshBase mesh = mMeshes[variant].copy(true);
383
    MatrixEffectQuaternion quat = new MatrixEffectQuaternion( getQuat(cubit,numLayers), new Static3D(0,0,0) );
384
    mesh.apply(quat,0xffffffff,0);
385

    
386
    return mesh;
387
    }
388

    
389
///////////////////////////////////////////////////////////////////////////////////////////////////
390

    
391
  private void createDataStructuresForSolved(int[] numLayers)
392
    {
393
    mTmpQuats = new int[NUM_QUATS];
394
    mSolvedQuats = new int[NUM_CUBITS][];
395

    
396
    for(int c=0; c<NUM_CUBITS; c++)
397
      {
398
      mSolvedQuats[c] = getSolvedQuats(c,numLayers);
399
      }
400
    }
401

    
402
///////////////////////////////////////////////////////////////////////////////////////////////////
403

    
404
  private int getMultQuat(int index1, int index2)
405
    {
406
    if( mQuatMult==null )
407
      {
408
      mQuatMult = new int[NUM_QUATS][NUM_QUATS];
409

    
410
      for(int i=0; i<NUM_QUATS; i++)
411
        for(int j=0; j<NUM_QUATS; j++) mQuatMult[i][j] = -1;
412
      }
413

    
414
    if( mQuatMult[index1][index2]==-1 )
415
      {
416
      mQuatMult[index1][index2] = mulQuat(index1,index2);
417
      }
418

    
419
    return mQuatMult[index1][index2];
420
    }
421

    
422
///////////////////////////////////////////////////////////////////////////////////////////////////
423

    
424
  public int getVariantFaceColor(int variant, int face)
425
    {
426
    return face>=mStickerVariants[variant].length ? -1 : mStickerVariants[variant][face];
427
    }
428

    
429
///////////////////////////////////////////////////////////////////////////////////////////////////
430
// This is used to build internal data structures for the generic 'isSolved()'
431
//
432
// if this is an internal cubit (all faces black): return -1
433
// if this is a face cubit (one non-black face): return the color index of the only non-black face.
434
// Color index, i.e. the index into the 'FACE_COLORS' table.
435
// else (edge or corner cubit, more than one non-black face): return -2.
436

    
437
  protected int retCubitSolvedStatus(int cubit, int[] numLayers)
438
    {
439
    int numNonBlack=0, nonBlackIndex=-1, varColor, cubColor;
440
    int variant = getCubitVariant(cubit,numLayers);
441

    
442
    for(int face=0; face<mNumCubitFaces; face++)
443
      {
444
      varColor = getVariantFaceColor(variant,face);
445
      cubColor = getCubitFaceColor(cubit,face,numLayers);
446

    
447
      if( varColor>=0 && cubColor>=0 )
448
        {
449
        numNonBlack++;
450
        nonBlackIndex = cubColor;
451
        }
452
      }
453

    
454
    if( numNonBlack==0 ) return -1;
455
    if( numNonBlack>=2 ) return -2;
456

    
457
    return nonBlackIndex;
458
    }
459

    
460
///////////////////////////////////////////////////////////////////////////////////////////////////
461

    
462
  public boolean shouldResetTextureMaps()
463
    {
464
    return false;
465
    }
466

    
467
///////////////////////////////////////////////////////////////////////////////////////////////////
468

    
469
  protected int[] buildSolvedQuats(Static3D faceAx, Static4D[] quats)
470
    {
471
    final float MAXD = 0.0001f;
472
    float x = faceAx.get0();
473
    float y = faceAx.get1();
474
    float z = faceAx.get2();
475
    float a,dx,dy,dz,qx,qy,qz;
476
    Static4D quat;
477

    
478
    int len = quats.length;
479
    int place = 0;
480

    
481
    for(int q=1; q<len; q++)
482
      {
483
      quat = quats[q];
484
      qx = quat.get0();
485
      qy = quat.get1();
486
      qz = quat.get2();
487

    
488
           if( x!=0.0f ) { a = qx/x; }
489
      else if( y!=0.0f ) { a = qy/y; }
490
      else               { a = qz/z; }
491

    
492
      dx = a*x-qx;
493
      dy = a*y-qy;
494
      dz = a*z-qz;
495

    
496
      if( dx>-MAXD && dx<MAXD && dy>-MAXD && dy<MAXD && dz>-MAXD && dz<MAXD )
497
        {
498
        mTmpQuats[place++] = q;
499
        }
500
      }
501

    
502
    if( place!=0 )
503
      {
504
      int[] ret = new int[place];
505
      System.arraycopy(mTmpQuats,0,ret,0,place);
506
      return ret;
507
      }
508

    
509
    return null;
510
    }
511

    
512
///////////////////////////////////////////////////////////////////////////////////////////////////
513

    
514
  private boolean isSolved0()
515
    {
516
    int len, q1,q = CUBITS[0].mQuatIndex;
517
    int[] solved;
518
    boolean skip;
519

    
520
    for(int c=1; c<NUM_CUBITS; c++)
521
      {
522
      q1 = CUBITS[c].mQuatIndex;
523

    
524
      if( q1==q ) continue;
525

    
526
      skip = false;
527
      solved = mSolvedQuats[c];
528
      len = solved==null ? 0:solved.length;
529

    
530
      for(int i=0; i<len; i++)
531
        {
532
        if( q1==getMultQuat(q,solved[i]) )
533
          {
534
          skip = true;
535
          break;
536
          }
537
        }
538

    
539
      if( !skip ) return false;
540
      }
541

    
542
    return true;
543
    }
544

    
545
///////////////////////////////////////////////////////////////////////////////////////////////////
546

    
547
  private int computeScramble(int quatNum, int centerNum)
548
    {
549
    float MAXDIFF = 0.01f;
550
    float[] center= mOrigPos[centerNum];
551
    Static4D sc = new Static4D(center[0], center[1], center[2], 1.0f);
552
    Static4D result = QuatHelper.rotateVectorByQuat(sc,OBJECT_QUATS[quatNum]);
553

    
554
    float x = result.get0();
555
    float y = result.get1();
556
    float z = result.get2();
557

    
558
    for(int c=0; c<NUM_CUBITS; c++)
559
      {
560
      float[] cent = mOrigPos[c];
561

    
562
      float qx = cent[0] - x;
563
      float qy = cent[1] - y;
564
      float qz = cent[2] - z;
565

    
566
      if( qx>-MAXDIFF && qx<MAXDIFF &&
567
          qy>-MAXDIFF && qy<MAXDIFF &&
568
          qz>-MAXDIFF && qz<MAXDIFF  ) return c;
569
      }
570

    
571
    return -1;
572
    }
573

    
574
///////////////////////////////////////////////////////////////////////////////////////////////////
575
// Dino4 uses this. It is solved if and only if groups of cubits
576
// (0,3,7), (1,2,5), (4,8,9), (6,10,11)
577
// or
578
// (0,1,4), (2,3,6), (5,9,10), (7,8,11)
579
// are all the same color.
580

    
581
  private boolean isSolved1()
582
    {
583
    if( mScramble==null )
584
      {
585
      mScramble = new int[NUM_QUATS][NUM_CUBITS];
586
      mColors   = new int[NUM_CUBITS];
587

    
588
      for(int q=0; q<NUM_QUATS; q++)
589
        for(int c=0; c<NUM_CUBITS; c++) mScramble[q][c] = computeScramble(q,c);
590
      }
591

    
592
    if( mFaceMap==null )
593
      {
594
      mFaceMap = new int[] { 4, 2, 2, 4, 0, 2, 1, 4, 0, 0, 1, 1 };
595
      }
596

    
597
    for(int c=0; c<NUM_CUBITS; c++)
598
      {
599
      int index = mScramble[CUBITS[c].mQuatIndex][c];
600
      mColors[index] = mFaceMap[c];
601
      }
602

    
603
    if( mColors[0]==mColors[3] && mColors[0]==mColors[7] &&
604
        mColors[1]==mColors[2] && mColors[1]==mColors[5] &&
605
        mColors[4]==mColors[8] && mColors[4]==mColors[9]  ) return true;
606

    
607
    if( mColors[0]==mColors[1] && mColors[0]==mColors[4] &&
608
        mColors[2]==mColors[3] && mColors[2]==mColors[6] &&
609
        mColors[5]==mColors[9] && mColors[5]==mColors[10] ) return true;
610

    
611
    return false;
612
    }
613

    
614
///////////////////////////////////////////////////////////////////////////////////////////////////
615
// Dino6 uses this. It is solved if and only if:
616
//
617
// All four 'X' cubits (i.e. those whose longest edge goes along the X axis) are rotated
618
// by the same quaternion qX, similarly all four 'Y' cubits by the same qY and all four 'Z'
619
// by the same qZ, and then either:
620
//
621
// a) qX = qY = qZ
622
// b) qY = qX*Q2 and qZ = qX*Q8  (i.e. swap of WHITE and YELLOW faces)
623
// c) qX = qY*Q2 and qZ = qY*Q10 (i.e. swap of BLUE and GREEN faces)
624
// d) qX = qZ*Q8 and qY = qZ*Q10 (i.e. swap of RED and BROWN faces)
625
//
626
// BUT: cases b), c) and d) are really the same - it's all just a mirror image of the original.
627
//
628
// X cubits: 0, 2, 8, 10
629
// Y cubits: 1, 3, 9, 11
630
// Z cubits: 4, 5, 6, 7
631

    
632
  private boolean isSolved2()
633
    {
634
    int qX = CUBITS[0].mQuatIndex;
635
    int qY = CUBITS[1].mQuatIndex;
636
    int qZ = CUBITS[4].mQuatIndex;
637

    
638
    if( CUBITS[2].mQuatIndex != qX || CUBITS[8].mQuatIndex != qX || CUBITS[10].mQuatIndex != qX ||
639
        CUBITS[3].mQuatIndex != qY || CUBITS[9].mQuatIndex != qY || CUBITS[11].mQuatIndex != qY ||
640
        CUBITS[5].mQuatIndex != qZ || CUBITS[6].mQuatIndex != qZ || CUBITS[ 7].mQuatIndex != qZ  )
641
      {
642
      return false;
643
      }
644

    
645
    return ( qX==qY && qX==qZ ) || ( qY==mulQuat(qX,2) && qZ==mulQuat(qX,8) );
646
    }
647

    
648
///////////////////////////////////////////////////////////////////////////////////////////////////
649
// Square-2 is solved iff
650
// a) all of its cubits are rotated with the same quat
651
// b) its two 'middle' cubits are rotated with the same quat, the 6 'front' and 6 'back'
652
// edges and corners with this quat multiplied by QUATS[18] (i.e. those are upside down)
653
// and all the 12 left and right edges and corners also with the same quat multiplied by
654
// QUATS[12] - i.e. also upside down.
655

    
656
  private boolean isSolved3()
657
    {
658
    int index = CUBITS[0].mQuatIndex;
659

    
660
    if( CUBITS[1].mQuatIndex!=index ) return false;
661

    
662
    boolean solved = true;
663

    
664
    for(int i=2; i<NUM_CUBITS; i++)
665
      {
666
      if( CUBITS[i].mQuatIndex!=index )
667
        {
668
        solved = false;
669
        break;
670
        }
671
      }
672

    
673
    if( solved ) return true;
674

    
675
    int indexX = mulQuat(index,12);  // QUATS[12] = 180deg (1,0,0)
676
    int indexZ = mulQuat(index,18);  // QUATS[18] = 180deg (0,0,1)
677

    
678
    for(int i= 2; i<        18; i+=2) if( CUBITS[i].mQuatIndex != indexZ ) return false;
679
    for(int i= 3; i<        18; i+=2) if( CUBITS[i].mQuatIndex != indexX ) return false;
680
    for(int i=18; i<NUM_CUBITS; i+=2) if( CUBITS[i].mQuatIndex != indexX ) return false;
681
    for(int i=19; i<NUM_CUBITS; i+=2) if( CUBITS[i].mQuatIndex != indexZ ) return false;
682

    
683
    return true;
684
    }
685

    
686
///////////////////////////////////////////////////////////////////////////////////////////////////
687

    
688
  int computeRow(float[] pos, int axisIndex)
689
    {
690
    int ret=0;
691
    int len = pos.length / 3;
692
    Static3D axis = mAxis[axisIndex];
693
    float axisX = axis.get0();
694
    float axisY = axis.get1();
695
    float axisZ = axis.get2();
696
    float casted;
697

    
698
    for(int i=0; i<len; i++)
699
      {
700
      casted = pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ;
701
      ret |= computeSingleRow(axisIndex,casted);
702
      }
703

    
704
    return ret;
705
    }
706

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

    
709
  private int computeSingleRow(int axisIndex,float casted)
710
    {
711
    int num = mNumCuts[axisIndex];
712

    
713
    for(int i=0; i<num; i++)
714
      {
715
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
716
      }
717

    
718
    return (1<<num);
719
    }
720

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

    
723
  private boolean wasRotateApplied()
724
    {
725
    return mEffects.exists(mRotateEffect.getID());
726
    }
727

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

    
730
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
731
    {
732
    return (CUBITS[cubit].getRotRow(axis) & rowBitmap) != 0;
733
    }
734

    
735
///////////////////////////////////////////////////////////////////////////////////////////////////
736
// note the minus in front of the sin() - we rotate counterclockwise
737
// when looking towards the direction where the axis increases in values.
738

    
739
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
740
    {
741
    Static3D axis = mAxis[axisIndex];
742

    
743
    while( angleInDegrees<0 ) angleInDegrees += 360;
744
    angleInDegrees %= 360;
745
    
746
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
747
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
748

    
749
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
750
    }
751

    
752
///////////////////////////////////////////////////////////////////////////////////////////////////
753

    
754
  private synchronized void setupPosition(int[][] moves)
755
    {
756
    if( moves!=null )
757
      {
758
      Static4D quat;
759
      int index, axis, rowBitmap, angle;
760
      int[] basic = getBasicAngle();
761

    
762
      for(int[] move: moves)
763
        {
764
        axis     = move[0];
765
        rowBitmap= move[1];
766
        angle    = move[2]*(360/basic[axis]);
767
        quat     = makeQuaternion(axis,angle);
768

    
769
        for(int j=0; j<NUM_CUBITS; j++)
770
          if( belongsToRotation(j,axis,rowBitmap) )
771
            {
772
            index = CUBITS[j].removeRotationNow(quat);
773
            mMesh.setEffectAssociation(j, CUBITS[j].computeAssociation(),index);
774
            }
775
        }
776
      }
777
    }
778

    
779
///////////////////////////////////////////////////////////////////////////////////////////////////
780

    
781
  public int getScrambleType()
782
    {
783
    return 0;
784
    }
785

    
786
///////////////////////////////////////////////////////////////////////////////////////////////////
787

    
788
  int computeBitmapFromRow(int rowBitmap, int axis)
789
    {
790
    if( mIsBandaged )
791
      {
792
      int bitmap, initBitmap=0;
793

    
794
      while( initBitmap!=rowBitmap )
795
        {
796
        initBitmap = rowBitmap;
797

    
798
        for(int cubit=0; cubit<NUM_CUBITS; cubit++)
799
          {
800
          bitmap = CUBITS[cubit].getRotRow(axis);
801
          if( (rowBitmap & bitmap) != 0 ) rowBitmap |= bitmap;
802
          }
803
        }
804
      }
805

    
806
    return rowBitmap;
807
    }
808

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

    
813
  void clampPos(float[] pos, int offset)
814
    {
815
    float currError, minError = Float.MAX_VALUE;
816
    int minErrorIndex1 = -1;
817
    int minErrorIndex2 = -1;
818

    
819
    float x = pos[offset  ];
820
    float y = pos[offset+1];
821
    float z = pos[offset+2];
822

    
823
    float xo,yo,zo;
824

    
825
    for(int i=0; i<NUM_CUBITS; i++)
826
      {
827
      int len = mOrigPos[i].length / 3;
828

    
829
      for(int j=0; j<len; j++)
830
        {
831
        xo = mOrigPos[i][3*j  ];
832
        yo = mOrigPos[i][3*j+1];
833
        zo = mOrigPos[i][3*j+2];
834

    
835
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
836

    
837
        if( currError<minError )
838
          {
839
          minError = currError;
840
          minErrorIndex1 = i;
841
          minErrorIndex2 = j;
842
          }
843
        }
844
      }
845

    
846
    if( minError< 0.1f ) // TODO: 0.1 ?
847
      {
848
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
849
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
850
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
851
      }
852
    }
853

    
854
///////////////////////////////////////////////////////////////////////////////////////////////////
855
// remember about the double cover or unit quaternions!
856

    
857
  int mulQuat(int q1, int q2)
858
    {
859
    Static4D result = QuatHelper.quatMultiply(OBJECT_QUATS[q1],OBJECT_QUATS[q2]);
860

    
861
    float rX = result.get0();
862
    float rY = result.get1();
863
    float rZ = result.get2();
864
    float rW = result.get3();
865

    
866
    final float MAX_ERROR = 0.1f;
867
    float dX,dY,dZ,dW;
868

    
869
    for(int i=0; i<NUM_QUATS; i++)
870
      {
871
      dX = OBJECT_QUATS[i].get0() - rX;
872
      dY = OBJECT_QUATS[i].get1() - rY;
873
      dZ = OBJECT_QUATS[i].get2() - rZ;
874
      dW = OBJECT_QUATS[i].get3() - rW;
875

    
876
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
877
          dY<MAX_ERROR && dY>-MAX_ERROR &&
878
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
879
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
880

    
881
      dX = OBJECT_QUATS[i].get0() + rX;
882
      dY = OBJECT_QUATS[i].get1() + rY;
883
      dZ = OBJECT_QUATS[i].get2() + rZ;
884
      dW = OBJECT_QUATS[i].get3() + rW;
885

    
886
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
887
          dY<MAX_ERROR && dY>-MAX_ERROR &&
888
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
889
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
890
      }
891

    
892
    return -1;
893
    }
894

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

    
897
  private float getAngle()
898
    {
899
    int pointNum = mRotationAngle.getNumPoints();
900

    
901
    if( pointNum>=1 )
902
      {
903
      return mRotationAngle.getPoint(pointNum-1).get0();
904
      }
905
    else
906
      {
907
      mInterface.reportProblem("points in RotationAngle: "+pointNum, false);
908
      return 0;
909
      }
910
    }
911

    
912
///////////////////////////////////////////////////////////////////////////////////////////////////
913

    
914
  void setLibInterface(ObjectLibInterface inter)
915
    {
916
    mInterface = inter;
917
    }
918

    
919
///////////////////////////////////////////////////////////////////////////////////////////////////
920

    
921
  void initializeObject(int[][] moves)
922
    {
923
    solve();
924
    setupPosition(moves);
925
    }
926

    
927
///////////////////////////////////////////////////////////////////////////////////////////////////
928

    
929
  synchronized void removeRotationNow()
930
    {
931
    float angle = getAngle();
932
    double nearestAngleInRadians = angle*Math.PI/180;
933
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
934
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
935
    float axisX = mAxis[mCurrentRotAxis].get0();
936
    float axisY = mAxis[mCurrentRotAxis].get1();
937
    float axisZ = mAxis[mCurrentRotAxis].get2();
938
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
939

    
940
    mRotationAngle.removeAll();
941
    mRotationAngleStatic.set0(0);
942

    
943
    for(int i=0; i<NUM_CUBITS; i++)
944
      if( belongsToRotation(i, mCurrentRotAxis,mRotRowBitmap) )
945
        {
946
        int index = CUBITS[i].removeRotationNow(quat);
947
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),index);
948
        }
949
    }
950

    
951
///////////////////////////////////////////////////////////////////////////////////////////////////
952

    
953
  long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
954
    {
955
    if( wasRotateApplied() )
956
      {
957
      float angle = getAngle();
958
      mRotationAngleStatic.set0(angle);
959
      mRotationAngleFinal.set0(nearestAngleInDegrees);
960
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
961

    
962
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
963
      mRotationAngle.resetToBeginning();
964
      mRotationAngle.removeAll();
965
      mRotationAngle.add(mRotationAngleStatic);
966
      mRotationAngle.add(mRotationAngleMiddle);
967
      mRotationAngle.add(mRotationAngleFinal);
968
      mRotateEffect.notifyWhenFinished(listener);
969

    
970
      return mRotateEffect.getID();
971
      }
972

    
973
    return 0;
974
    }
975

    
976
///////////////////////////////////////////////////////////////////////////////////////////////////
977

    
978
  synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
979
    {
980
    if( wasRotateApplied() )
981
      {
982
      mCurrentRotAxis = axis;
983
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
984

    
985
      mRotationAngleStatic.set0(0.0f);
986
      mRotationAxis.set( mAxis[axis] );
987
      mRotationAngle.setDuration(durationMillis);
988
      mRotationAngle.resetToBeginning();
989
      mRotationAngle.add(new Static1D(0));
990
      mRotationAngle.add(new Static1D(angle));
991
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*SHIFT) , -1);
992
      mRotateEffect.notifyWhenFinished(listener);
993

    
994
      return mRotateEffect.getID();
995
      }
996

    
997
    return 0;
998
    }
999

    
1000
///////////////////////////////////////////////////////////////////////////////////////////////////
1001

    
1002
  void continueRotation(float angleInDegrees)
1003
    {
1004
    mRotationAngleStatic.set0(angleInDegrees);
1005
    }
1006

    
1007
///////////////////////////////////////////////////////////////////////////////////////////////////
1008

    
1009
  synchronized void beginNewRotation(int axis, int row )
1010
    {
1011
    if( axis<0 || axis>=NUM_AXIS )
1012
      {
1013
      android.util.Log.e("object", "invalid rotation axis: "+axis);
1014
      return;
1015
      }
1016
    if( row<0 || row>=mNumLayers[axis] )
1017
      {
1018
      android.util.Log.e("object", "invalid rotation row: "+row);
1019
      return;
1020
      }
1021

    
1022
    mCurrentRotAxis = axis;
1023
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
1024
    mRotationAngleStatic.set0(0.0f);
1025
    mRotationAxis.set( mAxis[axis] );
1026
    mRotationAngle.add(mRotationAngleStatic);
1027
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*SHIFT) , -1);
1028
    }
1029

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

    
1032
  void setTextureMap(int cubit, int face, int newColor)
1033
    {
1034
    final float ratioW = 1.0f/mNumTexCols;
1035
    final float ratioH = 1.0f/mNumTexRows;
1036
    final Static4D[] maps = new Static4D[mNumCubitFaces];
1037
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
1038
    int col = newColor%mNumTexCols;
1039

    
1040
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1041
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1042
    }
1043

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

    
1046
  void resetAllTextureMaps()
1047
    {
1048
    final float ratioW = 1.0f/mNumTexCols;
1049
    final float ratioH = 1.0f/mNumTexRows;
1050
    int cubColor, varColor, color, variant, row, col;
1051

    
1052
    for(int cubit=0; cubit<NUM_CUBITS; cubit++)
1053
      {
1054
      final Static4D[] maps = new Static4D[mNumCubitFaces];
1055
      variant = getCubitVariant(cubit,mNumLayers);
1056

    
1057
      for(int face=0; face<mNumCubitFaces; face++)
1058
        {
1059
        cubColor = getCubitFaceColor(cubit,face,mNumLayers);
1060
        varColor = getVariantFaceColor(variant,face);
1061
        color    = cubColor<0 || varColor<0 ? NUM_TEXTURES : varColor*NUM_FACE_COLORS + cubColor;
1062
        row      = (mNumTexRows-1) - color/mNumTexCols;
1063
        col      = color%mNumTexCols;
1064

    
1065
        maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1066
        }
1067

    
1068
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1069
      }
1070
    }
1071

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

    
1074
  void releaseResources()
1075
    {
1076
    mTexture.markForDeletion();
1077
    mMesh.markForDeletion();
1078
    mEffects.markForDeletion();
1079

    
1080
    for(int j=0; j<NUM_CUBITS; j++)
1081
      {
1082
      CUBITS[j].releaseResources();
1083
      }
1084
    }
1085

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

    
1088
  synchronized void restorePreferences(SharedPreferences preferences)
1089
    {
1090
    boolean error = false;
1091

    
1092
    for(int i=0; i<NUM_CUBITS; i++)
1093
      {
1094
      mQuatDebug[i] = CUBITS[i].restorePreferences(preferences);
1095

    
1096
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<NUM_QUATS)
1097
        {
1098
        CUBITS[i].modifyCurrentPosition(OBJECT_QUATS[mQuatDebug[i]]);
1099
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),mQuatDebug[i]);
1100
        }
1101
      else
1102
        {
1103
        error = true;
1104
        }
1105
      }
1106

    
1107
    if( error )
1108
      {
1109
      for(int i=0; i<NUM_CUBITS; i++)
1110
        {
1111
        CUBITS[i].solve();
1112
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),0);
1113
        }
1114
      }
1115
    }
1116

    
1117
///////////////////////////////////////////////////////////////////////////////////////////////////
1118

    
1119
  void savePreferences(SharedPreferences.Editor editor)
1120
    {
1121
    for(int i=0; i<NUM_CUBITS; i++) CUBITS[i].savePreferences(editor);
1122
    }
1123

    
1124
///////////////////////////////////////////////////////////////////////////////////////////////////
1125

    
1126
  private float computeRadiusCorrection(float[] sticker, int curr, int len)
1127
    {
1128
    final float A = 0.8f;  // 0<A<1
1129

    
1130
    int prev = curr>0 ? curr-1 : len-1;
1131
    int next = curr<len-1 ? curr+1 : 0;
1132

    
1133
    float v1x = sticker[2*prev  ]-sticker[2*curr  ];
1134
    float v1y = sticker[2*prev+1]-sticker[2*curr+1];
1135
    float v2x = sticker[2*next  ]-sticker[2*curr  ];
1136
    float v2y = sticker[2*next+1]-sticker[2*curr+1];
1137

    
1138
    float len1= v1x*v1x+v1y*v1y;
1139
    float len2= v2x*v2x+v2y*v2y;
1140

    
1141
    float cos = (v1x*v2x+v1y*v2y) / ( (float)Math.sqrt(len1*len2) );
1142

    
1143
    return 1-A*cos;
1144
    }
1145

    
1146
///////////////////////////////////////////////////////////////////////////////////////////////////
1147

    
1148
  public ObjectSticker retSticker(int sticker)
1149
    {
1150
    if( mStickers==null )
1151
      {
1152
      float rad = getStickerRadius();
1153
      float str = getStickerStroke();
1154
      float[][] angles = getStickerAngles();
1155
      int numStickers = mStickerCoords.length;
1156
      mStickers = new ObjectSticker[numStickers];
1157

    
1158
      for(int s=0; s<numStickers; s++)
1159
        {
1160
        float scale = mStickerScales[s];
1161
        float radius = rad / scale;
1162
        float stroke = str / scale;
1163
        int len = mStickerCoords[s].length/2;
1164
        float[] radii = new float[len];
1165
        for(int r=0; r<len; r++) radii[r] = radius*computeRadiusCorrection(mStickerCoords[s],r,len);
1166
        mStickers[s] = new ObjectSticker(mStickerCoords[s],angles==null ? null : angles[s],radii,stroke);
1167
        }
1168
      }
1169

    
1170
    return mStickers[sticker];
1171
    }
1172

    
1173
///////////////////////////////////////////////////////////////////////////////////////////////////
1174
// some objects (currently Kilominx,Ivy,Rex) might want to change the stickers.
1175

    
1176
  public void adjustStickerCoords()
1177
    {
1178

    
1179
    }
1180

    
1181
///////////////////////////////////////////////////////////////////////////////////////////////////
1182
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
1183

    
1184
  private void createTexture()
1185
    {
1186
    Paint paint = new Paint();
1187
    mBitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_8888);
1188
    Canvas canvas = new Canvas(mBitmap);
1189

    
1190
    paint.setAntiAlias(true);
1191
    paint.setTextAlign(Paint.Align.CENTER);
1192
    paint.setStyle(Paint.Style.FILL);
1193

    
1194
    paint.setColor(COLOR_INTERNAL);
1195
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
1196

    
1197
    int texture = 0;
1198
    FactorySticker factory = FactorySticker.getInstance();
1199

    
1200
    for(int row=0; row<mNumTexRows; row++)
1201
      for(int col=0; col<mNumTexCols; col++)
1202
        {
1203
        if( texture>=NUM_TEXTURES ) break;
1204
        ObjectSticker sticker = retSticker(texture/NUM_FACE_COLORS);
1205
        int color = getColor(texture%NUM_FACE_COLORS);
1206
        factory.drawRoundedPolygon(canvas, paint, col*TEXTURE_HEIGHT, row*TEXTURE_HEIGHT, color, sticker);
1207
        texture++;
1208
        }
1209
    }
1210

    
1211
///////////////////////////////////////////////////////////////////////////////////////////////////
1212

    
1213
  void setTexture()
1214
    {
1215
    if( mBitmap==null ) createTexture();
1216

    
1217
    if( !mTexture.setTexture(mBitmap) )
1218
      {
1219
      int max = DistortedLibrary.getMaxTextureSize();
1220
      mInterface.reportProblem("failed to set texture of size "+mBitmap.getWidth()+"x"+mBitmap.getHeight()+" max is "+max, true);
1221
      }
1222
    }
1223

    
1224
///////////////////////////////////////////////////////////////////////////////////////////////////
1225

    
1226
  void setObjectRatioNow(float sc, int nodeSize)
1227
    {
1228
    mObjectScreenRatio = sc;
1229
    float scale = mObjectScreenRatio*mInitScreenRatio*nodeSize/mSize;
1230
    mObjectScale.set(scale,scale,scale);
1231

    
1232
    if( mTouchControl ==null ) mTouchControl = getTouchControl();
1233
    mTouchControl.setObjectRatio(mObjectScreenRatio*mInitScreenRatio);
1234
    }
1235

    
1236
///////////////////////////////////////////////////////////////////////////////////////////////////
1237

    
1238
  void setObjectRatio(float sizeChange, int nodeSize)
1239
    {
1240
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
1241

    
1242
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
1243
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
1244

    
1245
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1246
    }
1247

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

    
1250
  void setNodeSize(int nodeSize)
1251
    {
1252
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1253
    }
1254

    
1255
///////////////////////////////////////////////////////////////////////////////////////////////////
1256

    
1257
  public float getRatio()
1258
    {
1259
    return mObjectScreenRatio;
1260
    }
1261

    
1262
///////////////////////////////////////////////////////////////////////////////////////////////////
1263

    
1264
  public float getObjectRatio()
1265
    {
1266
    return mObjectScreenRatio*mInitScreenRatio;
1267
    }
1268

    
1269
///////////////////////////////////////////////////////////////////////////////////////////////////
1270

    
1271
  boolean isSolved()
1272
    {
1273
    if( mSolvedFunctionIndex==0 ) return isSolved0();
1274
    if( mSolvedFunctionIndex==1 ) return isSolved1();
1275
    if( mSolvedFunctionIndex==2 ) return isSolved2();
1276
    if( mSolvedFunctionIndex==3 ) return isSolved3();
1277

    
1278
    return false;
1279
    }
1280

    
1281
///////////////////////////////////////////////////////////////////////////////////////////////////
1282

    
1283
  int computeNearestAngle(int axis, float angle, float speed)
1284
    {
1285
    int[] basicArray = getBasicAngle();
1286
    int basicAngle   = basicArray[axis>=basicArray.length ? 0 : axis];
1287
    int nearestAngle = 360/basicAngle;
1288

    
1289
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
1290
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
1291

    
1292
    if( tmp!=0 ) return nearestAngle*tmp;
1293

    
1294
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
1295
    }
1296

    
1297
///////////////////////////////////////////////////////////////////////////////////////////////////
1298
// INTERNAL API - those are called from 'effects' package
1299
///////////////////////////////////////////////////////////////////////////////////////////////////
1300

    
1301
  public void randomizeNewScramble(int[][] scramble, Random rnd, int curr, int total)
1302
    {
1303
    mScrambler.randomizeNewScramble(scramble,rnd,curr,total);
1304
    }
1305

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

    
1308
  public Static4D getRotationQuat()
1309
    {
1310
    return mQuat;
1311
    }
1312

    
1313
///////////////////////////////////////////////////////////////////////////////////////////////////
1314

    
1315
  public float getSize()
1316
    {
1317
    return mSize;
1318
    }
1319

    
1320
///////////////////////////////////////////////////////////////////////////////////////////////////
1321

    
1322
  public void apply(Effect effect, int position)
1323
    {
1324
    mEffects.apply(effect, position);
1325
    }
1326

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

    
1329
  public void remove(long effectID)
1330
    {
1331
    mEffects.abortById(effectID);
1332
    }
1333

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

    
1336
  public MeshBase getObjectMesh()
1337
    {
1338
    return mMesh;
1339
    }
1340

    
1341
///////////////////////////////////////////////////////////////////////////////////////////////////
1342

    
1343
  public DistortedEffects getObjectEffects()
1344
    {
1345
    return mEffects;
1346
    }
1347

    
1348
///////////////////////////////////////////////////////////////////////////////////////////////////
1349
// PUBLIC API
1350
///////////////////////////////////////////////////////////////////////////////////////////////////
1351

    
1352
  public int getCubitFaceColorIndex(int cubit, int face)
1353
    {
1354
    Static4D texMap = mMesh.getTextureMap(NUM_FACE_COLORS*cubit + face);
1355

    
1356
    int x = (int)(texMap.get0()/texMap.get2());
1357
    int y = (int)(texMap.get1()/texMap.get3());
1358

    
1359
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
1360
    }
1361

    
1362
///////////////////////////////////////////////////////////////////////////////////////////////////
1363

    
1364
  public int[] getNumLayers()
1365
    {
1366
    return mNumLayers;
1367
    }
1368

    
1369
///////////////////////////////////////////////////////////////////////////////////////////////////
1370

    
1371
  public synchronized void solve()
1372
    {
1373
    for(int i=0; i<NUM_CUBITS; i++)
1374
      {
1375
      CUBITS[i].solve();
1376
      mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
1377
      }
1378
    }
1379

    
1380
///////////////////////////////////////////////////////////////////////////////////////////////////
1381

    
1382
  public int getCubitQuatIndex(int cubit)
1383
    {
1384
    return CUBITS[cubit].mQuatIndex;
1385
    }
1386

    
1387
///////////////////////////////////////////////////////////////////////////////////////////////////
1388

    
1389
  public int getCubitRotRow(int cubit, int axis)
1390
    {
1391
    return CUBITS[cubit].getRotRow(axis);
1392
    }
1393

    
1394
///////////////////////////////////////////////////////////////////////////////////////////////////
1395

    
1396
  public Bitmap getStickerBitmap()
1397
    {
1398
    return mBitmap;
1399
    }
1400

    
1401
///////////////////////////////////////////////////////////////////////////////////////////////////
1402

    
1403
  public DistortedNode getNode()
1404
    {
1405
    return mNode;
1406
    }
1407

    
1408
///////////////////////////////////////////////////////////////////////////////////////////////////
1409

    
1410
  public ObjectType getObjectType()
1411
    {
1412
    return intGetObjectType(mNumLayers);
1413
    }
1414

    
1415
///////////////////////////////////////////////////////////////////////////////////////////////////
1416

    
1417
  public int getNumStickerTypes()
1418
    {
1419
    return mNumStickerTypes;
1420
    }
1421

    
1422
///////////////////////////////////////////////////////////////////////////////////////////////////
1423

    
1424
  public TouchControl getTouchControl()
1425
    {
1426
    if( mTouchControl==null )
1427
      {
1428
      switch(getTouchControlType())
1429
        {
1430
        case TC_TETRAHEDRON    : mTouchControl = new TouchControlTetrahedron(this);
1431
                                 break;
1432
        case TC_HEXAHEDRON     : mTouchControl = new TouchControlHexahedron(this);
1433
                                 break;
1434
        case TC_OCTAHEDRON     : mTouchControl = new TouchControlOctahedron(this);
1435
                                 break;
1436
        case TC_DODECAHEDRON   : mTouchControl = new TouchControlDodecahedron(this);
1437
                                 break;
1438
        case TC_CUBOID         : int[] numLayers = getNumLayers();
1439
                                 mTouchControl = new TouchControlCuboids(this,getDist3D(numLayers));
1440
                                 break;
1441
        case TC_CHANGING_MIRROR: mTouchControl = new TouchControlMirror(this);
1442
                                 break;
1443
        case TC_CHANGING_SQUARE: mTouchControl = new TouchControlSquare(this);
1444
                                 break;
1445
        }
1446
      }
1447
    return mTouchControl;
1448
    }
1449

    
1450
///////////////////////////////////////////////////////////////////////////////////////////////////
1451

    
1452
  public String getShortName()
1453
    {
1454
    return getObjectType().name();
1455
    }
1456

    
1457
///////////////////////////////////////////////////////////////////////////////////////////////////
1458

    
1459
  protected void setReader(JsonReader reader)
1460
    {
1461
    // empty
1462
    }
1463

    
1464
///////////////////////////////////////////////////////////////////////////////////////////////////
1465

    
1466
  protected abstract ObjectType intGetObjectType(int[] numLayers);
1467

    
1468
  // for JSON only
1469
  public abstract int getSolvedFunctionIndex();
1470
  public abstract int getTouchControlType();
1471
  public abstract int getTouchControlSplit();
1472
  public abstract boolean[][] getLayerRotatable(int[] numLayers);
1473
  public abstract int[][][] getEnabled();
1474
  public abstract float[] getDist3D(int[] numLayers);
1475
  public abstract ScrambleState[] getScrambleStates();
1476
  public abstract float[][] getCuts(int[] numLayers);
1477
  public abstract Static4D[] getQuats();
1478
  public abstract float getStickerRadius();
1479
  public abstract float getStickerStroke();
1480
  public abstract float[][] getStickerAngles();
1481
  public abstract int getCubitVariant(int cubit, int[] numLayers);
1482
  public abstract ObjectShape getObjectShape(int variant);
1483
  public abstract int getNumCubitVariants(int[] numLayers);
1484
  public abstract float[][] getCubitPositions(int[] numLayers);
1485
  public abstract Static4D getQuat(int cubit, int[] numLayers);
1486
  public abstract int[] getSolvedQuats(int cubit, int[] numLayers);
1487
  public abstract int getCubitFaceColor(int cubit, int face, int[] numLayers);
1488
  public abstract int getNumFaceColors();
1489
  public abstract int getNumCubitFaces();
1490
  public abstract float getScreenRatio();
1491
  public abstract int getColor(int face);
1492

    
1493
  // not only for JSON
1494
  public abstract Static3D[] getRotationAxis();
1495
  public abstract int[] getBasicAngle();
1496
  public abstract int getNumFaces();
1497
  public abstract String getObjectName();
1498
  public abstract String getInventor();
1499
  public abstract int getYearOfInvention();
1500
  public abstract int getComplexity();
1501
  public abstract int getFOV();
1502
  }
(11-11/13)