Project

General

Profile

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

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

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

    
141
  //////////////////// SOLVED1 ////////////////////////
142

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

    
147
///////////////////////////////////////////////////////////////////////////////////////////////////
148

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

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

    
160
///////////////////////////////////////////////////////////////////////////////////////////////////
161

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

    
169
///////////////////////////////////////////////////////////////////////////////////////////////////
170

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

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

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

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

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

    
201
    boolean bandaged=false;
202

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

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

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

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

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

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

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

    
236
    mEffects = new DistortedEffects();
237

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

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

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

    
253
///////////////////////////////////////////////////////////////////////////////////////////////////
254

    
255
  private void setUpTextures(boolean fromStream)
256
    {
257
    mTexture = new DistortedTexture();
258

    
259
    FactoryCubit factory = FactoryCubit.getInstance();
260
    mStickerCoords   = factory.getOuterStickerCoords();
261
    mStickerVariants = factory.getStickerVariants();
262
    mStickerScales   = factory.getOuterStickerScales();
263

    
264
    adjustStickerCoords();
265

    
266
      int len = mStickerVariants.length;
267

    
268
      for(int i=0; i<len; i++)
269
        {
270
        String str="variant "+i+" : ";
271
        int lenI = mStickerVariants[i].length;
272

    
273
        for(int j=0; j<lenI; j++)
274
          {
275
          str+= (mStickerVariants[i][j]+" ");
276
          }
277

    
278
        android.util.Log.e("D", str);
279
        }
280

    
281
    mNumStickerTypes = mStickerCoords.length;
282
    NUM_TEXTURES = NUM_FACE_COLORS*mNumStickerTypes;
283
    mNumTexCols = NUM_STICKERS_IN_ROW;
284
    mNumTexRows = (NUM_TEXTURES+1)/NUM_STICKERS_IN_ROW;
285
    if( mNumTexCols*mNumTexRows < NUM_TEXTURES+1 ) mNumTexRows++;
286

    
287
    if( !fromStream || shouldResetTextureMaps() ) resetAllTextureMaps();
288
    setTexture();
289
    }
290

    
291
///////////////////////////////////////////////////////////////////////////////////////////////////
292

    
293
  private Static3D getPos(float[] origPos)
294
    {
295
    int len = origPos.length/3;
296
    float sumX = 0.0f;
297
    float sumY = 0.0f;
298
    float sumZ = 0.0f;
299

    
300
    for(int i=0; i<len; i++)
301
      {
302
      sumX += origPos[3*i  ];
303
      sumY += origPos[3*i+1];
304
      sumZ += origPos[3*i+2];
305
      }
306

    
307
    sumX /= len;
308
    sumY /= len;
309
    sumZ /= len;
310

    
311
    return new Static3D(sumX,sumY,sumZ);
312
    }
313

    
314
///////////////////////////////////////////////////////////////////////////////////////////////////
315

    
316
  private void createMeshAndCubits(InputStream stream, int meshState, boolean fromStream)
317
    {
318
    if( fromStream )
319
      {
320
      DataInputStream dos = new DataInputStream(stream);
321
      mMesh = new MeshFile(dos);
322

    
323
      try
324
        {
325
        stream.close();
326
        }
327
      catch(IOException e)
328
        {
329
        android.util.Log.e("meshFile", "Error closing InputStream: "+e.toString());
330
        }
331

    
332
      for(int i=0; i<NUM_CUBITS; i++)
333
        {
334
        CUBITS[i] = new Cubit(this,mOrigPos[i], NUM_AXIS);
335
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
336
        }
337
      }
338
    else
339
      {
340
      MeshBase[] cubitMesh = new MeshBase[NUM_CUBITS];
341

    
342
      for(int i=0; i<NUM_CUBITS; i++)
343
        {
344
        CUBITS[i] = new Cubit(this,mOrigPos[i], NUM_AXIS);
345
        cubitMesh[i] = createCubitMesh(i,mNumLayers,meshState);
346
        Static3D pos = getPos(mOrigPos[i]);
347
        cubitMesh[i].apply(new MatrixEffectMove(pos),1,0);
348
        cubitMesh[i].setEffectAssociation(0, CUBITS[i].computeAssociation(), 0);
349
        }
350

    
351
      mMesh = new MeshJoined(cubitMesh);
352

    
353
      FactoryCubit factory = FactoryCubit.getInstance();
354
      factory.printStickerCoords();
355
      }
356
    }
357

    
358
///////////////////////////////////////////////////////////////////////////////////////////////////
359

    
360
  private MeshBase createCubitMesh(int cubit, int[] numLayers, int meshState)
361
    {
362
    int variant = getCubitVariant(cubit,numLayers);
363

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

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

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

    
383
    return mesh;
384
    }
385

    
386
///////////////////////////////////////////////////////////////////////////////////////////////////
387

    
388
  private void createDataStructuresForSolved(int[] numLayers)
389
    {
390
    mTmpQuats = new int[NUM_QUATS];
391
    mSolvedQuats = new int[NUM_CUBITS][];
392

    
393
    for(int c=0; c<NUM_CUBITS; c++)
394
      {
395
      mSolvedQuats[c] = getSolvedQuats(c,numLayers);
396
      }
397
    }
398

    
399
///////////////////////////////////////////////////////////////////////////////////////////////////
400

    
401
  private int getMultQuat(int index1, int index2)
402
    {
403
    if( mQuatMult==null )
404
      {
405
      mQuatMult = new int[NUM_QUATS][NUM_QUATS];
406

    
407
      for(int i=0; i<NUM_QUATS; i++)
408
        for(int j=0; j<NUM_QUATS; j++) mQuatMult[i][j] = -1;
409
      }
410

    
411
    if( mQuatMult[index1][index2]==-1 )
412
      {
413
      mQuatMult[index1][index2] = mulQuat(index1,index2);
414
      }
415

    
416
    return mQuatMult[index1][index2];
417
    }
418

    
419
///////////////////////////////////////////////////////////////////////////////////////////////////
420
// This is used to build internal data structures for the generic 'isSolved()'
421
//
422
// if this is an internal cubit (all faces black): return -1
423
// if this is a face cubit (one non-black face): return the color index of the only non-black face.
424
// Color index, i.e. the index into the 'FACE_COLORS' table.
425
// else (edge or corner cubit, more than one non-black face): return -2.
426

    
427
  protected int retCubitSolvedStatus(int cubit, int[] numLayers)
428
    {
429
    int numNonBlack=0, nonBlackIndex=-1, varColor, cubColor;
430
    int variant = getCubitVariant(cubit,numLayers);
431

    
432
    for(int face=0; face<mNumCubitFaces; face++)
433
      {
434
      varColor = getVariantFaceColor(variant,face,numLayers);
435
      cubColor = getCubitFaceColor(cubit,face,numLayers);
436

    
437
      if( varColor>=0 && cubColor>=0 )
438
        {
439
        numNonBlack++;
440
        nonBlackIndex = cubColor;
441
        }
442
      }
443

    
444
    if( numNonBlack==0 ) return -1;
445
    if( numNonBlack>=2 ) return -2;
446

    
447
    return nonBlackIndex;
448
    }
449

    
450
///////////////////////////////////////////////////////////////////////////////////////////////////
451

    
452
  public boolean shouldResetTextureMaps()
453
    {
454
    return false;
455
    }
456

    
457
///////////////////////////////////////////////////////////////////////////////////////////////////
458

    
459
  protected int[] buildSolvedQuats(Static3D faceAx, Static4D[] quats)
460
    {
461
    final float MAXD = 0.0001f;
462
    float x = faceAx.get0();
463
    float y = faceAx.get1();
464
    float z = faceAx.get2();
465
    float a,dx,dy,dz,qx,qy,qz;
466
    Static4D quat;
467

    
468
    int len = quats.length;
469
    int place = 0;
470

    
471
    for(int q=1; q<len; q++)
472
      {
473
      quat = quats[q];
474
      qx = quat.get0();
475
      qy = quat.get1();
476
      qz = quat.get2();
477

    
478
           if( x!=0.0f ) { a = qx/x; }
479
      else if( y!=0.0f ) { a = qy/y; }
480
      else               { a = qz/z; }
481

    
482
      dx = a*x-qx;
483
      dy = a*y-qy;
484
      dz = a*z-qz;
485

    
486
      if( dx>-MAXD && dx<MAXD && dy>-MAXD && dy<MAXD && dz>-MAXD && dz<MAXD )
487
        {
488
        mTmpQuats[place++] = q;
489
        }
490
      }
491

    
492
    if( place!=0 )
493
      {
494
      int[] ret = new int[place];
495
      System.arraycopy(mTmpQuats,0,ret,0,place);
496
      return ret;
497
      }
498

    
499
    return null;
500
    }
501

    
502
///////////////////////////////////////////////////////////////////////////////////////////////////
503

    
504
  private boolean isSolved0()
505
    {
506
    int len, q1,q = CUBITS[0].mQuatIndex;
507
    int[] solved;
508
    boolean skip;
509

    
510
    for(int c=1; c<NUM_CUBITS; c++)
511
      {
512
      q1 = CUBITS[c].mQuatIndex;
513

    
514
      if( q1==q ) continue;
515

    
516
      skip = false;
517
      solved = mSolvedQuats[c];
518
      len = solved==null ? 0:solved.length;
519

    
520
      for(int i=0; i<len; i++)
521
        {
522
        if( q1==getMultQuat(q,solved[i]) )
523
          {
524
          skip = true;
525
          break;
526
          }
527
        }
528

    
529
      if( !skip ) return false;
530
      }
531

    
532
    return true;
533
    }
534

    
535
///////////////////////////////////////////////////////////////////////////////////////////////////
536

    
537
  private int computeScramble(int quatNum, int centerNum)
538
    {
539
    float MAXDIFF = 0.01f;
540
    float[] center= mOrigPos[centerNum];
541
    Static4D sc = new Static4D(center[0], center[1], center[2], 1.0f);
542
    Static4D result = QuatHelper.rotateVectorByQuat(sc,OBJECT_QUATS[quatNum]);
543

    
544
    float x = result.get0();
545
    float y = result.get1();
546
    float z = result.get2();
547

    
548
    for(int c=0; c<NUM_CUBITS; c++)
549
      {
550
      float[] cent = mOrigPos[c];
551

    
552
      float qx = cent[0] - x;
553
      float qy = cent[1] - y;
554
      float qz = cent[2] - z;
555

    
556
      if( qx>-MAXDIFF && qx<MAXDIFF &&
557
          qy>-MAXDIFF && qy<MAXDIFF &&
558
          qz>-MAXDIFF && qz<MAXDIFF  ) return c;
559
      }
560

    
561
    return -1;
562
    }
563

    
564
///////////////////////////////////////////////////////////////////////////////////////////////////
565
// Dino4 uses this. It is solved if and only if groups of cubits
566
// (0,3,7), (1,2,5), (4,8,9), (6,10,11)
567
// or
568
// (0,1,4), (2,3,6), (5,9,10), (7,8,11)
569
// are all the same color.
570

    
571
  private boolean isSolved1()
572
    {
573
    if( mScramble==null )
574
      {
575
      mScramble = new int[NUM_QUATS][NUM_CUBITS];
576
      mColors   = new int[NUM_CUBITS];
577

    
578
      for(int q=0; q<NUM_QUATS; q++)
579
        for(int c=0; c<NUM_CUBITS; c++) mScramble[q][c] = computeScramble(q,c);
580
      }
581

    
582
    if( mFaceMap==null )
583
      {
584
      mFaceMap = new int[] { 4, 2, 2, 4, 0, 2, 1, 4, 0, 0, 1, 1 };
585
      }
586

    
587
    for(int c=0; c<NUM_CUBITS; c++)
588
      {
589
      int index = mScramble[CUBITS[c].mQuatIndex][c];
590
      mColors[index] = mFaceMap[c];
591
      }
592

    
593
    if( mColors[0]==mColors[3] && mColors[0]==mColors[7] &&
594
        mColors[1]==mColors[2] && mColors[1]==mColors[5] &&
595
        mColors[4]==mColors[8] && mColors[4]==mColors[9]  ) return true;
596

    
597
    if( mColors[0]==mColors[1] && mColors[0]==mColors[4] &&
598
        mColors[2]==mColors[3] && mColors[2]==mColors[6] &&
599
        mColors[5]==mColors[9] && mColors[5]==mColors[10] ) return true;
600

    
601
    return false;
602
    }
603

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

    
622
  private boolean isSolved2()
623
    {
624
    int qX = CUBITS[0].mQuatIndex;
625
    int qY = CUBITS[1].mQuatIndex;
626
    int qZ = CUBITS[4].mQuatIndex;
627

    
628
    if( CUBITS[2].mQuatIndex != qX || CUBITS[8].mQuatIndex != qX || CUBITS[10].mQuatIndex != qX ||
629
        CUBITS[3].mQuatIndex != qY || CUBITS[9].mQuatIndex != qY || CUBITS[11].mQuatIndex != qY ||
630
        CUBITS[5].mQuatIndex != qZ || CUBITS[6].mQuatIndex != qZ || CUBITS[ 7].mQuatIndex != qZ  )
631
      {
632
      return false;
633
      }
634

    
635
    return ( qX==qY && qX==qZ ) || ( qY==mulQuat(qX,2) && qZ==mulQuat(qX,8) );
636
    }
637

    
638
///////////////////////////////////////////////////////////////////////////////////////////////////
639
// Square-2 is solved iff
640
// a) all of its cubits are rotated with the same quat
641
// b) its two 'middle' cubits are rotated with the same quat, the 6 'front' and 6 'back'
642
// edges and corners with this quat multiplied by QUATS[18] (i.e. those are upside down)
643
// and all the 12 left and right edges and corners also with the same quat multiplied by
644
// QUATS[12] - i.e. also upside down.
645

    
646
  private boolean isSolved3()
647
    {
648
    int index = CUBITS[0].mQuatIndex;
649

    
650
    if( CUBITS[1].mQuatIndex!=index ) return false;
651

    
652
    boolean solved = true;
653

    
654
    for(int i=2; i<NUM_CUBITS; i++)
655
      {
656
      if( CUBITS[i].mQuatIndex!=index )
657
        {
658
        solved = false;
659
        break;
660
        }
661
      }
662

    
663
    if( solved ) return true;
664

    
665
    int indexX = mulQuat(index,12);  // QUATS[12] = 180deg (1,0,0)
666
    int indexZ = mulQuat(index,18);  // QUATS[18] = 180deg (0,0,1)
667

    
668
    for(int i= 2; i<        18; i+=2) if( CUBITS[i].mQuatIndex != indexZ ) return false;
669
    for(int i= 3; i<        18; i+=2) if( CUBITS[i].mQuatIndex != indexX ) return false;
670
    for(int i=18; i<NUM_CUBITS; i+=2) if( CUBITS[i].mQuatIndex != indexX ) return false;
671
    for(int i=19; i<NUM_CUBITS; i+=2) if( CUBITS[i].mQuatIndex != indexZ ) return false;
672

    
673
    return true;
674
    }
675

    
676
///////////////////////////////////////////////////////////////////////////////////////////////////
677

    
678
  int computeRow(float[] pos, int axisIndex)
679
    {
680
    int ret=0;
681
    int len = pos.length / 3;
682
    Static3D axis = mAxis[axisIndex];
683
    float axisX = axis.get0();
684
    float axisY = axis.get1();
685
    float axisZ = axis.get2();
686
    float casted;
687

    
688
    for(int i=0; i<len; i++)
689
      {
690
      casted = pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ;
691
      ret |= computeSingleRow(axisIndex,casted);
692
      }
693

    
694
    return ret;
695
    }
696

    
697
///////////////////////////////////////////////////////////////////////////////////////////////////
698

    
699
  private int computeSingleRow(int axisIndex,float casted)
700
    {
701
    int num = mNumCuts[axisIndex];
702

    
703
    for(int i=0; i<num; i++)
704
      {
705
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
706
      }
707

    
708
    return (1<<num);
709
    }
710

    
711
///////////////////////////////////////////////////////////////////////////////////////////////////
712

    
713
  private boolean wasRotateApplied()
714
    {
715
    return mEffects.exists(mRotateEffect.getID());
716
    }
717

    
718
///////////////////////////////////////////////////////////////////////////////////////////////////
719

    
720
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
721
    {
722
    return (CUBITS[cubit].getRotRow(axis) & rowBitmap) != 0;
723
    }
724

    
725
///////////////////////////////////////////////////////////////////////////////////////////////////
726
// note the minus in front of the sin() - we rotate counterclockwise
727
// when looking towards the direction where the axis increases in values.
728

    
729
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
730
    {
731
    Static3D axis = mAxis[axisIndex];
732

    
733
    while( angleInDegrees<0 ) angleInDegrees += 360;
734
    angleInDegrees %= 360;
735
    
736
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
737
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
738

    
739
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
740
    }
741

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

    
744
  private synchronized void setupPosition(int[][] moves)
745
    {
746
    if( moves!=null )
747
      {
748
      Static4D quat;
749
      int index, axis, rowBitmap, angle;
750
      int[] basic = getBasicAngle();
751

    
752
      for(int[] move: moves)
753
        {
754
        axis     = move[0];
755
        rowBitmap= move[1];
756
        angle    = move[2]*(360/basic[axis]);
757
        quat     = makeQuaternion(axis,angle);
758

    
759
        for(int j=0; j<NUM_CUBITS; j++)
760
          if( belongsToRotation(j,axis,rowBitmap) )
761
            {
762
            index = CUBITS[j].removeRotationNow(quat);
763
            mMesh.setEffectAssociation(j, CUBITS[j].computeAssociation(),index);
764
            }
765
        }
766
      }
767
    }
768

    
769
///////////////////////////////////////////////////////////////////////////////////////////////////
770

    
771
  public int getScrambleType()
772
    {
773
    return 0;
774
    }
775

    
776
///////////////////////////////////////////////////////////////////////////////////////////////////
777

    
778
  int computeBitmapFromRow(int rowBitmap, int axis)
779
    {
780
    if( mIsBandaged )
781
      {
782
      int bitmap, initBitmap=0;
783

    
784
      while( initBitmap!=rowBitmap )
785
        {
786
        initBitmap = rowBitmap;
787

    
788
        for(int cubit=0; cubit<NUM_CUBITS; cubit++)
789
          {
790
          bitmap = CUBITS[cubit].getRotRow(axis);
791
          if( (rowBitmap & bitmap) != 0 ) rowBitmap |= bitmap;
792
          }
793
        }
794
      }
795

    
796
    return rowBitmap;
797
    }
798

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

    
803
  void clampPos(float[] pos, int offset)
804
    {
805
    float currError, minError = Float.MAX_VALUE;
806
    int minErrorIndex1 = -1;
807
    int minErrorIndex2 = -1;
808

    
809
    float x = pos[offset  ];
810
    float y = pos[offset+1];
811
    float z = pos[offset+2];
812

    
813
    float xo,yo,zo;
814

    
815
    for(int i=0; i<NUM_CUBITS; i++)
816
      {
817
      int len = mOrigPos[i].length / 3;
818

    
819
      for(int j=0; j<len; j++)
820
        {
821
        xo = mOrigPos[i][3*j  ];
822
        yo = mOrigPos[i][3*j+1];
823
        zo = mOrigPos[i][3*j+2];
824

    
825
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
826

    
827
        if( currError<minError )
828
          {
829
          minError = currError;
830
          minErrorIndex1 = i;
831
          minErrorIndex2 = j;
832
          }
833
        }
834
      }
835

    
836
    if( minError< 0.1f ) // TODO: 0.1 ?
837
      {
838
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
839
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
840
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
841
      }
842
    }
843

    
844
///////////////////////////////////////////////////////////////////////////////////////////////////
845
// remember about the double cover or unit quaternions!
846

    
847
  int mulQuat(int q1, int q2)
848
    {
849
    Static4D result = QuatHelper.quatMultiply(OBJECT_QUATS[q1],OBJECT_QUATS[q2]);
850

    
851
    float rX = result.get0();
852
    float rY = result.get1();
853
    float rZ = result.get2();
854
    float rW = result.get3();
855

    
856
    final float MAX_ERROR = 0.1f;
857
    float dX,dY,dZ,dW;
858

    
859
    for(int i=0; i<NUM_QUATS; i++)
860
      {
861
      dX = OBJECT_QUATS[i].get0() - rX;
862
      dY = OBJECT_QUATS[i].get1() - rY;
863
      dZ = OBJECT_QUATS[i].get2() - rZ;
864
      dW = OBJECT_QUATS[i].get3() - rW;
865

    
866
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
867
          dY<MAX_ERROR && dY>-MAX_ERROR &&
868
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
869
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return 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

    
882
    return -1;
883
    }
884

    
885
///////////////////////////////////////////////////////////////////////////////////////////////////
886

    
887
  private float getAngle()
888
    {
889
    int pointNum = mRotationAngle.getNumPoints();
890

    
891
    if( pointNum>=1 )
892
      {
893
      return mRotationAngle.getPoint(pointNum-1).get0();
894
      }
895
    else
896
      {
897
      mInterface.reportProblem("points in RotationAngle: "+pointNum, false);
898
      return 0;
899
      }
900
    }
901

    
902
///////////////////////////////////////////////////////////////////////////////////////////////////
903

    
904
  void setLibInterface(ObjectLibInterface inter)
905
    {
906
    mInterface = inter;
907
    }
908

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

    
911
  void initializeObject(int[][] moves)
912
    {
913
    solve();
914
    setupPosition(moves);
915
    }
916

    
917
///////////////////////////////////////////////////////////////////////////////////////////////////
918

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

    
930
    mRotationAngle.removeAll();
931
    mRotationAngleStatic.set0(0);
932

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

    
941
///////////////////////////////////////////////////////////////////////////////////////////////////
942

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

    
952
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
953
      mRotationAngle.resetToBeginning();
954
      mRotationAngle.removeAll();
955
      mRotationAngle.add(mRotationAngleStatic);
956
      mRotationAngle.add(mRotationAngleMiddle);
957
      mRotationAngle.add(mRotationAngleFinal);
958
      mRotateEffect.notifyWhenFinished(listener);
959

    
960
      return mRotateEffect.getID();
961
      }
962

    
963
    return 0;
964
    }
965

    
966
///////////////////////////////////////////////////////////////////////////////////////////////////
967

    
968
  synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
969
    {
970
    if( wasRotateApplied() )
971
      {
972
      mCurrentRotAxis = axis;
973
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
974

    
975
      mRotationAngleStatic.set0(0.0f);
976
      mRotationAxis.set( mAxis[axis] );
977
      mRotationAngle.setDuration(durationMillis);
978
      mRotationAngle.resetToBeginning();
979
      mRotationAngle.add(new Static1D(0));
980
      mRotationAngle.add(new Static1D(angle));
981
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*SHIFT) , -1);
982
      mRotateEffect.notifyWhenFinished(listener);
983

    
984
      return mRotateEffect.getID();
985
      }
986

    
987
    return 0;
988
    }
989

    
990
///////////////////////////////////////////////////////////////////////////////////////////////////
991

    
992
  void continueRotation(float angleInDegrees)
993
    {
994
    mRotationAngleStatic.set0(angleInDegrees);
995
    }
996

    
997
///////////////////////////////////////////////////////////////////////////////////////////////////
998

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

    
1012
    mCurrentRotAxis = axis;
1013
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
1014
    mRotationAngleStatic.set0(0.0f);
1015
    mRotationAxis.set( mAxis[axis] );
1016
    mRotationAngle.add(mRotationAngleStatic);
1017
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*SHIFT) , -1);
1018
    }
1019

    
1020
///////////////////////////////////////////////////////////////////////////////////////////////////
1021

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

    
1030
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1031
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1032
    }
1033

    
1034
///////////////////////////////////////////////////////////////////////////////////////////////////
1035

    
1036
  void resetAllTextureMaps()
1037
    {
1038
    final float ratioW = 1.0f/mNumTexCols;
1039
    final float ratioH = 1.0f/mNumTexRows;
1040
    int cubColor, varColor, color, variant, row, col;
1041

    
1042
    for(int cubit=0; cubit<NUM_CUBITS; cubit++)
1043
      {
1044
      final Static4D[] maps = new Static4D[mNumCubitFaces];
1045
      variant = getCubitVariant(cubit,mNumLayers);
1046

    
1047
      for(int face=0; face<mNumCubitFaces; face++)
1048
        {
1049
        cubColor = getCubitFaceColor(cubit,face,mNumLayers);
1050
     //   varColor = getVariantFaceColor(variant,face,mNumLayers);
1051

    
1052
        int len = mStickerVariants[variant].length;
1053

    
1054
        varColor = face>=len? -1 : mStickerVariants[variant][face];
1055

    
1056
/*
1057
        try
1058
          {
1059
          int len = mStickerVariants[variant].length;
1060
          int varColor2 = face>=len? -1 : mStickerVariants[variant][face];
1061

    
1062
          if( varColor!=varColor2 )
1063
            {
1064
            android.util.Log.e("D", "old="+varColor+" new="+varColor2+" variant="+variant+" face="+face);
1065
            }
1066
          }
1067
        catch(Exception ex)
1068
          {
1069
          android.util.Log.e("D", "variant="+variant+" face="+face+" Exception: "+ex.getMessage());
1070
          }
1071
*/
1072
        color    = cubColor<0 || varColor<0 ? NUM_TEXTURES : varColor*NUM_FACE_COLORS + cubColor;
1073
        row      = (mNumTexRows-1) - color/mNumTexCols;
1074
        col      = color%mNumTexCols;
1075

    
1076
        maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1077
        }
1078

    
1079
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1080
      }
1081
    }
1082

    
1083
///////////////////////////////////////////////////////////////////////////////////////////////////
1084

    
1085
  void releaseResources()
1086
    {
1087
    mTexture.markForDeletion();
1088
    mMesh.markForDeletion();
1089
    mEffects.markForDeletion();
1090

    
1091
    for(int j=0; j<NUM_CUBITS; j++)
1092
      {
1093
      CUBITS[j].releaseResources();
1094
      }
1095
    }
1096

    
1097
///////////////////////////////////////////////////////////////////////////////////////////////////
1098

    
1099
  synchronized void restorePreferences(SharedPreferences preferences)
1100
    {
1101
    boolean error = false;
1102

    
1103
    for(int i=0; i<NUM_CUBITS; i++)
1104
      {
1105
      mQuatDebug[i] = CUBITS[i].restorePreferences(preferences);
1106

    
1107
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<NUM_QUATS)
1108
        {
1109
        CUBITS[i].modifyCurrentPosition(OBJECT_QUATS[mQuatDebug[i]]);
1110
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),mQuatDebug[i]);
1111
        }
1112
      else
1113
        {
1114
        error = true;
1115
        }
1116
      }
1117

    
1118
    if( error )
1119
      {
1120
      for(int i=0; i<NUM_CUBITS; i++)
1121
        {
1122
        CUBITS[i].solve();
1123
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),0);
1124
        }
1125
      }
1126
    }
1127

    
1128
///////////////////////////////////////////////////////////////////////////////////////////////////
1129

    
1130
  void savePreferences(SharedPreferences.Editor editor)
1131
    {
1132
    for(int i=0; i<NUM_CUBITS; i++) CUBITS[i].savePreferences(editor);
1133
    }
1134

    
1135
///////////////////////////////////////////////////////////////////////////////////////////////////
1136
// some objects (currently only Kilominx) might want to change the stickers.
1137

    
1138
  public void adjustStickerCoords()
1139
    {
1140

    
1141
    }
1142

    
1143
///////////////////////////////////////////////////////////////////////////////////////////////////
1144
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
1145

    
1146
  private void createTexture()
1147
    {
1148
    Paint paint = new Paint();
1149
    mBitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_8888);
1150
    Canvas canvas = new Canvas(mBitmap);
1151

    
1152
    paint.setAntiAlias(true);
1153
    paint.setTextAlign(Paint.Align.CENTER);
1154
    paint.setStyle(Paint.Style.FILL);
1155

    
1156
    paint.setColor(COLOR_INTERNAL);
1157
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
1158

    
1159
    int texture = 0;
1160
    FactorySticker factory = FactorySticker.getInstance();
1161

    
1162
    for(int row=0; row<mNumTexRows; row++)
1163
      for(int col=0; col<mNumTexCols; col++)
1164
        {
1165
        if( texture>=NUM_TEXTURES ) break;
1166
        ObjectSticker sticker = retSticker(texture/NUM_FACE_COLORS);
1167
        int color = getColor(texture%NUM_FACE_COLORS);
1168
        factory.drawRoundedPolygon(canvas, paint, col*TEXTURE_HEIGHT, row*TEXTURE_HEIGHT, color, sticker);
1169
        texture++;
1170
        }
1171
    }
1172

    
1173
///////////////////////////////////////////////////////////////////////////////////////////////////
1174

    
1175
  void setTexture()
1176
    {
1177
    if( mBitmap==null ) createTexture();
1178

    
1179
    if( !mTexture.setTexture(mBitmap) )
1180
      {
1181
      int max = DistortedLibrary.getMaxTextureSize();
1182
      mInterface.reportProblem("failed to set texture of size "+mBitmap.getWidth()+"x"+mBitmap.getHeight()+" max is "+max, true);
1183
      }
1184
    }
1185

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

    
1188
  void setObjectRatioNow(float sc, int nodeSize)
1189
    {
1190
    mObjectScreenRatio = sc;
1191
    float scale = mObjectScreenRatio*mInitScreenRatio*nodeSize/mSize;
1192
    mObjectScale.set(scale,scale,scale);
1193

    
1194
    if( mTouchControl ==null ) mTouchControl = getTouchControl();
1195
    mTouchControl.setObjectRatio(mObjectScreenRatio*mInitScreenRatio);
1196
    }
1197

    
1198
///////////////////////////////////////////////////////////////////////////////////////////////////
1199

    
1200
  void setObjectRatio(float sizeChange, int nodeSize)
1201
    {
1202
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
1203

    
1204
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
1205
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
1206

    
1207
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1208
    }
1209

    
1210
///////////////////////////////////////////////////////////////////////////////////////////////////
1211

    
1212
  void setNodeSize(int nodeSize)
1213
    {
1214
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1215
    }
1216

    
1217
///////////////////////////////////////////////////////////////////////////////////////////////////
1218

    
1219
  public float getRatio()
1220
    {
1221
    return mObjectScreenRatio;
1222
    }
1223

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

    
1226
  public float getObjectRatio()
1227
    {
1228
    return mObjectScreenRatio*mInitScreenRatio;
1229
    }
1230

    
1231
///////////////////////////////////////////////////////////////////////////////////////////////////
1232

    
1233
  boolean isSolved()
1234
    {
1235
    if( mSolvedFunctionIndex==0 ) return isSolved0();
1236
    if( mSolvedFunctionIndex==1 ) return isSolved1();
1237
    if( mSolvedFunctionIndex==2 ) return isSolved2();
1238
    if( mSolvedFunctionIndex==3 ) return isSolved3();
1239

    
1240
    return false;
1241
    }
1242

    
1243
///////////////////////////////////////////////////////////////////////////////////////////////////
1244
// only called with figuring out which cubit was touched in MODE_REPLACE, which is only used in
1245
// during setting up the initial position in the solver.
1246

    
1247
  int getCubit(float[] point3D)
1248
    {
1249
    float dist, minDist = Float.MAX_VALUE;
1250
    int currentBest=-1;
1251
    float multiplier = mNumLayers[0];
1252

    
1253
    point3D[0] *= multiplier;
1254
    point3D[1] *= multiplier;
1255
    point3D[2] *= multiplier;
1256

    
1257
    for(int i=0; i<NUM_CUBITS; i++)
1258
      {
1259
      dist = CUBITS[i].getDistSquared(point3D);
1260
      if( dist<minDist )
1261
        {
1262
        minDist = dist;
1263
        currentBest = i;
1264
        }
1265
      }
1266

    
1267
    return currentBest;
1268
    }
1269

    
1270
///////////////////////////////////////////////////////////////////////////////////////////////////
1271

    
1272
  int computeNearestAngle(int axis, float angle, float speed)
1273
    {
1274
    int[] basicArray = getBasicAngle();
1275
    int basicAngle   = basicArray[axis>=basicArray.length ? 0 : axis];
1276
    int nearestAngle = 360/basicAngle;
1277

    
1278
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
1279
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
1280

    
1281
    if( tmp!=0 ) return nearestAngle*tmp;
1282

    
1283
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
1284
    }
1285

    
1286
///////////////////////////////////////////////////////////////////////////////////////////////////
1287
// INTERNAL API - those are called from 'effects' package
1288
///////////////////////////////////////////////////////////////////////////////////////////////////
1289

    
1290
  public void randomizeNewScramble(int[][] scramble, Random rnd, int curr, int total)
1291
    {
1292
    mScrambler.randomizeNewScramble(scramble,rnd,curr,total);
1293
    }
1294

    
1295
///////////////////////////////////////////////////////////////////////////////////////////////////
1296

    
1297
  public Static4D getRotationQuat()
1298
    {
1299
    return mQuat;
1300
    }
1301

    
1302
///////////////////////////////////////////////////////////////////////////////////////////////////
1303

    
1304
  public float getSize()
1305
    {
1306
    return mSize;
1307
    }
1308

    
1309
///////////////////////////////////////////////////////////////////////////////////////////////////
1310

    
1311
  public void apply(Effect effect, int position)
1312
    {
1313
    mEffects.apply(effect, position);
1314
    }
1315

    
1316
///////////////////////////////////////////////////////////////////////////////////////////////////
1317

    
1318
  public void remove(long effectID)
1319
    {
1320
    mEffects.abortById(effectID);
1321
    }
1322

    
1323
///////////////////////////////////////////////////////////////////////////////////////////////////
1324

    
1325
  public MeshBase getObjectMesh()
1326
    {
1327
    return mMesh;
1328
    }
1329

    
1330
///////////////////////////////////////////////////////////////////////////////////////////////////
1331

    
1332
  public DistortedEffects getObjectEffects()
1333
    {
1334
    return mEffects;
1335
    }
1336

    
1337
///////////////////////////////////////////////////////////////////////////////////////////////////
1338
// PUBLIC API
1339
///////////////////////////////////////////////////////////////////////////////////////////////////
1340

    
1341
  public int getCubitFaceColorIndex(int cubit, int face)
1342
    {
1343
    Static4D texMap = mMesh.getTextureMap(NUM_FACE_COLORS*cubit + face);
1344

    
1345
    int x = (int)(texMap.get0()/texMap.get2());
1346
    int y = (int)(texMap.get1()/texMap.get3());
1347

    
1348
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
1349
    }
1350

    
1351
///////////////////////////////////////////////////////////////////////////////////////////////////
1352

    
1353
  public int[] getNumLayers()
1354
    {
1355
    return mNumLayers;
1356
    }
1357

    
1358
///////////////////////////////////////////////////////////////////////////////////////////////////
1359

    
1360
  public synchronized void solve()
1361
    {
1362
    for(int i=0; i<NUM_CUBITS; i++)
1363
      {
1364
      CUBITS[i].solve();
1365
      mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
1366
      }
1367
    }
1368

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

    
1371
  public int getCubitQuatIndex(int cubit)
1372
    {
1373
    return CUBITS[cubit].mQuatIndex;
1374
    }
1375

    
1376
///////////////////////////////////////////////////////////////////////////////////////////////////
1377

    
1378
  public int getCubitRotRow(int cubit, int axis)
1379
    {
1380
    return CUBITS[cubit].getRotRow(axis);
1381
    }
1382

    
1383
///////////////////////////////////////////////////////////////////////////////////////////////////
1384

    
1385
  public Bitmap getStickerBitmap()
1386
    {
1387
    return mBitmap;
1388
    }
1389

    
1390
///////////////////////////////////////////////////////////////////////////////////////////////////
1391

    
1392
  public DistortedNode getNode()
1393
    {
1394
    return mNode;
1395
    }
1396

    
1397
///////////////////////////////////////////////////////////////////////////////////////////////////
1398

    
1399
  public ObjectType getObjectType()
1400
    {
1401
    return intGetObjectType(mNumLayers);
1402
    }
1403

    
1404
///////////////////////////////////////////////////////////////////////////////////////////////////
1405

    
1406
  public int getNumStickerTypes()
1407
    {
1408
    return mNumStickerTypes;
1409
    }
1410

    
1411
///////////////////////////////////////////////////////////////////////////////////////////////////
1412

    
1413
  public TouchControl getTouchControl()
1414
    {
1415
    if( mTouchControl==null )
1416
      {
1417
      switch(getTouchControlType())
1418
        {
1419
        case TC_TETRAHEDRON    : mTouchControl = new TouchControlTetrahedron(this);
1420
                                 break;
1421
        case TC_HEXAHEDRON     : mTouchControl = new TouchControlHexahedron(this);
1422
                                 break;
1423
        case TC_OCTAHEDRON     : mTouchControl = new TouchControlOctahedron(this);
1424
                                 break;
1425
        case TC_DODECAHEDRON   : mTouchControl = new TouchControlDodecahedron(this);
1426
                                 break;
1427
        case TC_CUBOID         : int[] numLayers = getNumLayers();
1428
                                 mTouchControl = new TouchControlCuboids(this,getDist3D(numLayers));
1429
                                 break;
1430
        case TC_CHANGING_MIRROR: mTouchControl = new TouchControlMirror(this);
1431
                                 break;
1432
        case TC_CHANGING_SQUARE: mTouchControl = new TouchControlSquare(this);
1433
                                 break;
1434
        }
1435
      }
1436
    return mTouchControl;
1437
    }
1438

    
1439
///////////////////////////////////////////////////////////////////////////////////////////////////
1440

    
1441
  public String getShortName()
1442
    {
1443
    return getObjectType().name();
1444
    }
1445

    
1446
///////////////////////////////////////////////////////////////////////////////////////////////////
1447

    
1448
  protected void setReader(JsonReader reader)
1449
    {
1450
    // empty
1451
    }
1452

    
1453
///////////////////////////////////////////////////////////////////////////////////////////////////
1454

    
1455
  protected abstract ObjectType intGetObjectType(int[] numLayers);
1456

    
1457
  // for JSON only
1458
  public abstract int getSolvedFunctionIndex();
1459
  public abstract int getTouchControlType();
1460
  public abstract int getTouchControlSplit();
1461
  public abstract boolean[][] getLayerRotatable(int[] numLayers);
1462
  public abstract int[][][] getEnabled();
1463
  public abstract float[] getDist3D(int[] numLayers);
1464
  public abstract ScrambleState[] getScrambleStates();
1465
  public abstract float[][] getCuts(int[] numLayers);
1466
  public abstract Static4D[] getQuats();
1467
  public abstract ObjectSticker retSticker(int sticker);
1468
  public abstract int getCubitVariant(int cubit, int[] numLayers);
1469
  public abstract ObjectShape getObjectShape(int variant);
1470
  public abstract int getNumCubitVariants(int[] numLayers);
1471
  public abstract float[][] getCubitPositions(int[] numLayers);
1472
  public abstract Static4D getQuat(int cubit, int[] numLayers);
1473
  public abstract int[] getSolvedQuats(int cubit, int[] numLayers);
1474
  public abstract int getCubitFaceColor(int cubit, int face, int[] numLayers);
1475
  public abstract int getVariantFaceColor(int variant, int face, int[] numLayers);
1476
  public abstract int getNumFaceColors();
1477
  public abstract int getNumCubitFaces();
1478
  public abstract float getScreenRatio();
1479
  public abstract int getColor(int face);
1480

    
1481
  // not only for JSON
1482
  public abstract Static3D[] getRotationAxis();
1483
  public abstract int[] getBasicAngle();
1484
  public abstract int getNumFaces();
1485
  public abstract String getObjectName();
1486
  public abstract String getInventor();
1487
  public abstract int getYearOfInvention();
1488
  public abstract int getComplexity();
1489
  public abstract int getFOV();
1490
  }
(11-11/13)