Project

General

Profile

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

distorted-objectlib / src / main / java / org / distorted / objectlib / main / TwistyObject.java @ 3ee1d662

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.ObjectFaceShape;
55
import org.distorted.objectlib.helpers.ObjectLibInterface;
56
import org.distorted.objectlib.helpers.ObjectShape;
57
import org.distorted.objectlib.helpers.ObjectSticker;
58
import org.distorted.objectlib.helpers.ScrambleState;
59
import org.distorted.objectlib.json.JsonReader;
60
import org.distorted.objectlib.touchcontrol.*;
61

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

    
64
///////////////////////////////////////////////////////////////////////////////////////////////////
65

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

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

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

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

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

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

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

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

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

    
143
  //////////////////// SOLVED1 ////////////////////////
144

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

    
149
///////////////////////////////////////////////////////////////////////////////////////////////////
150

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

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

    
162
///////////////////////////////////////////////////////////////////////////////////////////////////
163

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

    
171
///////////////////////////////////////////////////////////////////////////////////////////////////
172

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

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

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

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

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

    
203
    boolean bandaged=false;
204

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

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

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

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

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

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

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

    
238
    mEffects = new DistortedEffects();
239

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

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

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

    
255
///////////////////////////////////////////////////////////////////////////////////////////////////
256

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

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

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

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

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

    
286
      adjustStickerCoords();
287
      }
288

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

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

    
298
///////////////////////////////////////////////////////////////////////////////////////////////////
299

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

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

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

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

    
321
///////////////////////////////////////////////////////////////////////////////////////////////////
322

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

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

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

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

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

    
362
///////////////////////////////////////////////////////////////////////////////////////////////////
363

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

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

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

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

    
388
    return mesh;
389
    }
390

    
391
///////////////////////////////////////////////////////////////////////////////////////////////////
392

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

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

    
404
///////////////////////////////////////////////////////////////////////////////////////////////////
405

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

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

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

    
421
    return mQuatMult[index1][index2];
422
    }
423

    
424
///////////////////////////////////////////////////////////////////////////////////////////////////
425

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

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

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

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

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

    
456
    if( numNonBlack==0 ) return -1;
457
    if( numNonBlack>=2 ) return -2;
458

    
459
    return nonBlackIndex;
460
    }
461

    
462
///////////////////////////////////////////////////////////////////////////////////////////////////
463

    
464
  public boolean shouldResetTextureMaps()
465
    {
466
    return false;
467
    }
468

    
469
///////////////////////////////////////////////////////////////////////////////////////////////////
470

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

    
480
    int len = quats.length;
481
    int place = 0;
482

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

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

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

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

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

    
511
    return null;
512
    }
513

    
514
///////////////////////////////////////////////////////////////////////////////////////////////////
515

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

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

    
526
      if( q1==q ) continue;
527

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

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

    
541
      if( !skip ) return false;
542
      }
543

    
544
    return true;
545
    }
546

    
547
///////////////////////////////////////////////////////////////////////////////////////////////////
548

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

    
556
    float x = result.get0();
557
    float y = result.get1();
558
    float z = result.get2();
559

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

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

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

    
573
    return -1;
574
    }
575

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

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

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

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

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

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

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

    
613
    return false;
614
    }
615

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

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

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

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

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

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

    
662
    if( CUBITS[1].mQuatIndex!=index ) return false;
663

    
664
    boolean solved = true;
665

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

    
675
    if( solved ) return true;
676

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

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

    
685
    return true;
686
    }
687

    
688
///////////////////////////////////////////////////////////////////////////////////////////////////
689

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

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

    
706
    return ret;
707
    }
708

    
709
///////////////////////////////////////////////////////////////////////////////////////////////////
710

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

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

    
720
    return (1<<num);
721
    }
722

    
723
///////////////////////////////////////////////////////////////////////////////////////////////////
724

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

    
730
///////////////////////////////////////////////////////////////////////////////////////////////////
731

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

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

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

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

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

    
754
///////////////////////////////////////////////////////////////////////////////////////////////////
755

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

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

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

    
781
///////////////////////////////////////////////////////////////////////////////////////////////////
782

    
783
  public int getScrambleType()
784
    {
785
    return 0;
786
    }
787

    
788
///////////////////////////////////////////////////////////////////////////////////////////////////
789

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

    
796
      while( initBitmap!=rowBitmap )
797
        {
798
        initBitmap = rowBitmap;
799

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

    
808
    return rowBitmap;
809
    }
810

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

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

    
821
    float x = pos[offset  ];
822
    float y = pos[offset+1];
823
    float z = pos[offset+2];
824

    
825
    float xo,yo,zo;
826

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

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

    
837
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
838

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

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

    
856
///////////////////////////////////////////////////////////////////////////////////////////////////
857
// remember about the double cover or unit quaternions!
858

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

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

    
868
    final float MAX_ERROR = 0.1f;
869
    float dX,dY,dZ,dW;
870

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

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

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

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

    
894
    return -1;
895
    }
896

    
897
///////////////////////////////////////////////////////////////////////////////////////////////////
898

    
899
  private float getAngle()
900
    {
901
    int pointNum = mRotationAngle.getNumPoints();
902

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

    
914
///////////////////////////////////////////////////////////////////////////////////////////////////
915

    
916
  void setLibInterface(ObjectLibInterface inter)
917
    {
918
    mInterface = inter;
919
    }
920

    
921
///////////////////////////////////////////////////////////////////////////////////////////////////
922

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

    
929
///////////////////////////////////////////////////////////////////////////////////////////////////
930

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

    
942
    mRotationAngle.removeAll();
943
    mRotationAngleStatic.set0(0);
944

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

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

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

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

    
972
      return mRotateEffect.getID();
973
      }
974

    
975
    return 0;
976
    }
977

    
978
///////////////////////////////////////////////////////////////////////////////////////////////////
979

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

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

    
996
      return mRotateEffect.getID();
997
      }
998

    
999
    return 0;
1000
    }
1001

    
1002
///////////////////////////////////////////////////////////////////////////////////////////////////
1003

    
1004
  void continueRotation(float angleInDegrees)
1005
    {
1006
    mRotationAngleStatic.set0(angleInDegrees);
1007
    }
1008

    
1009
///////////////////////////////////////////////////////////////////////////////////////////////////
1010

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

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

    
1032
///////////////////////////////////////////////////////////////////////////////////////////////////
1033

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

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

    
1046
///////////////////////////////////////////////////////////////////////////////////////////////////
1047

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

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

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

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

    
1070
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1071
      }
1072
    }
1073

    
1074
///////////////////////////////////////////////////////////////////////////////////////////////////
1075

    
1076
  void releaseResources()
1077
    {
1078
    mTexture.markForDeletion();
1079
    mMesh.markForDeletion();
1080
    mEffects.markForDeletion();
1081

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

    
1088
///////////////////////////////////////////////////////////////////////////////////////////////////
1089

    
1090
  synchronized void restorePreferences(SharedPreferences preferences)
1091
    {
1092
    boolean error = false;
1093

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

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

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

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

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

    
1126
///////////////////////////////////////////////////////////////////////////////////////////////////
1127

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

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

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

    
1140
    float len1= v1x*v1x+v1y*v1y;
1141
    float len2= v2x*v2x+v2y*v2y;
1142

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

    
1145
    return 1-A*cos;
1146
    }
1147

    
1148
///////////////////////////////////////////////////////////////////////////////////////////////////
1149

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

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

    
1172
    return mStickers[sticker];
1173
    }
1174

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

    
1178
  public void adjustStickerCoords()
1179
    {
1180

    
1181
    }
1182

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

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

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

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

    
1199
    int texture = 0;
1200
    FactorySticker factory = FactorySticker.getInstance();
1201

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

    
1213
///////////////////////////////////////////////////////////////////////////////////////////////////
1214

    
1215
  void setTexture()
1216
    {
1217
    if( mBitmap==null ) createTexture();
1218

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

    
1226
///////////////////////////////////////////////////////////////////////////////////////////////////
1227

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

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

    
1238
///////////////////////////////////////////////////////////////////////////////////////////////////
1239

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

    
1244
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
1245
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
1246

    
1247
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1248
    }
1249

    
1250
///////////////////////////////////////////////////////////////////////////////////////////////////
1251

    
1252
  void setNodeSize(int nodeSize)
1253
    {
1254
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1255
    }
1256

    
1257
///////////////////////////////////////////////////////////////////////////////////////////////////
1258

    
1259
  public float getRatio()
1260
    {
1261
    return mObjectScreenRatio;
1262
    }
1263

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

    
1266
  public float getObjectRatio()
1267
    {
1268
    return mObjectScreenRatio*mInitScreenRatio;
1269
    }
1270

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

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

    
1280
    return false;
1281
    }
1282

    
1283
///////////////////////////////////////////////////////////////////////////////////////////////////
1284

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

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

    
1294
    if( tmp!=0 ) return nearestAngle*tmp;
1295

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

    
1299
///////////////////////////////////////////////////////////////////////////////////////////////////
1300
// INTERNAL API - those are called from 'effects' package
1301
///////////////////////////////////////////////////////////////////////////////////////////////////
1302

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

    
1308
///////////////////////////////////////////////////////////////////////////////////////////////////
1309

    
1310
  public Static4D getRotationQuat()
1311
    {
1312
    return mQuat;
1313
    }
1314

    
1315
///////////////////////////////////////////////////////////////////////////////////////////////////
1316

    
1317
  public float getSize()
1318
    {
1319
    return mSize;
1320
    }
1321

    
1322
///////////////////////////////////////////////////////////////////////////////////////////////////
1323

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

    
1329
///////////////////////////////////////////////////////////////////////////////////////////////////
1330

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

    
1336
///////////////////////////////////////////////////////////////////////////////////////////////////
1337

    
1338
  public MeshBase getObjectMesh()
1339
    {
1340
    return mMesh;
1341
    }
1342

    
1343
///////////////////////////////////////////////////////////////////////////////////////////////////
1344

    
1345
  public DistortedEffects getObjectEffects()
1346
    {
1347
    return mEffects;
1348
    }
1349

    
1350
///////////////////////////////////////////////////////////////////////////////////////////////////
1351
// PUBLIC API
1352
///////////////////////////////////////////////////////////////////////////////////////////////////
1353

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

    
1358
    int x = (int)(texMap.get0()/texMap.get2());
1359
    int y = (int)(texMap.get1()/texMap.get3());
1360

    
1361
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
1362
    }
1363

    
1364
///////////////////////////////////////////////////////////////////////////////////////////////////
1365

    
1366
  public int[] getNumLayers()
1367
    {
1368
    return mNumLayers;
1369
    }
1370

    
1371
///////////////////////////////////////////////////////////////////////////////////////////////////
1372

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

    
1382
///////////////////////////////////////////////////////////////////////////////////////////////////
1383

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

    
1389
///////////////////////////////////////////////////////////////////////////////////////////////////
1390

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

    
1396
///////////////////////////////////////////////////////////////////////////////////////////////////
1397

    
1398
  public Bitmap getStickerBitmap()
1399
    {
1400
    return mBitmap;
1401
    }
1402

    
1403
///////////////////////////////////////////////////////////////////////////////////////////////////
1404

    
1405
  public DistortedNode getNode()
1406
    {
1407
    return mNode;
1408
    }
1409

    
1410
///////////////////////////////////////////////////////////////////////////////////////////////////
1411

    
1412
  public ObjectType getObjectType()
1413
    {
1414
    return intGetObjectType(mNumLayers);
1415
    }
1416

    
1417
///////////////////////////////////////////////////////////////////////////////////////////////////
1418

    
1419
  public int getNumStickerTypes()
1420
    {
1421
    return mNumStickerTypes;
1422
    }
1423

    
1424
///////////////////////////////////////////////////////////////////////////////////////////////////
1425

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

    
1452
///////////////////////////////////////////////////////////////////////////////////////////////////
1453

    
1454
  public String getShortName()
1455
    {
1456
    return getObjectType().name();
1457
    }
1458

    
1459
///////////////////////////////////////////////////////////////////////////////////////////////////
1460

    
1461
  protected void setReader(JsonReader reader)
1462
    {
1463
    // empty
1464
    }
1465

    
1466
///////////////////////////////////////////////////////////////////////////////////////////////////
1467

    
1468
  protected abstract ObjectType intGetObjectType(int[] numLayers);
1469

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

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