Project

General

Profile

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

distorted-objectlib / src / main / java / org / distorted / objectlib / main / TwistyObject.java @ 9b1fe915

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[] mOrigQuat;
115
  private Static4D mQuat;
116
  private final int[] mNumLayers;
117
  private final float mSize;
118
  private DistortedEffects mEffects;
119
  private VertexEffectRotate mRotateEffect;
120
  private Dynamic1D mRotationAngle;
121
  private Static3D mRotationAxis;
122
  private Static3D mObjectScale;
123
  private int[] mQuatDebug;
124
  private Static1D mRotationAngleStatic, mRotationAngleMiddle, mRotationAngleFinal;
125
  private DistortedTexture mTexture;
126
  private float mInitScreenRatio;
127
  private int mSolvedFunctionIndex;
128
  private boolean mIsBandaged;
129
  private float mObjectScreenRatio;
130
  private int[][] mSolvedQuats;
131
  private int[][] mQuatMult;
132
  private int[] mTmpQuats;
133
  private int mNumTexRows, mNumTexCols;
134
  private int mRotRowBitmap;
135
  private int mCurrentRotAxis;
136
  private MeshBase mMesh;
137
  private TwistyObjectScrambler mScrambler;
138
  private TouchControl mTouchControl;
139
  private DistortedNode mNode;
140
  private ObjectLibInterface mInterface;
141
  private Bitmap mBitmap;
142
  private ObjectSticker[] mStickers;
143
  private ObjectShape[] mShapes;
144
  private int mNumCubitVariants;
145
  private int[][] mCubitFaceColors;
146

    
147
  //////////////////// SOLVED1 ////////////////////////
148

    
149
  private int[] mFaceMap;
150
  private int[][] mScramble;
151
  private int[] mColors;
152

    
153
///////////////////////////////////////////////////////////////////////////////////////////////////
154

    
155
  TwistyObject(InputStream jsonStream, int meshState, Static4D quat, Static3D move, float scale, InputStream meshStream)
156
    {
157
    JsonReader reader = new JsonReader();
158
    reader.parseJsonFile(jsonStream);
159
    setReader(reader);
160

    
161
    mNumLayers = reader.getNumLayers();
162
    mSize      = reader.getSize();
163
    initialize(meshState,quat,move,scale,meshStream,true);
164
    }
165

    
166
///////////////////////////////////////////////////////////////////////////////////////////////////
167

    
168
  TwistyObject(int[] numLayers, int meshState, float size, Static4D quat, Static3D move, float scale, InputStream meshStream)
169
    {
170
    mNumLayers = numLayers;
171
    mSize      = size;
172
    initialize(meshState,quat,move,scale,meshStream,false);
173
    }
174

    
175
///////////////////////////////////////////////////////////////////////////////////////////////////
176

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

    
185
    int numAxis = mAxis.length;
186
    SHIFT = -1;
187

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

    
196
    OBJECT_QUATS = getQuats();
197
    NUM_CUBITS  = mOrigPos.length;
198
    NUM_FACE_COLORS = getNumFaceColors();
199
    NUM_AXIS = mAxis.length;
200
    NUM_QUATS = OBJECT_QUATS.length;
201

    
202
    int scramblingType = getScrambleType();
203
    ScrambleState[] states = getScrambleStates();
204
    mScrambler = new TwistyObjectScrambler(scramblingType,NUM_AXIS,mNumLayers,states);
205

    
206
    boolean bandaged=false;
207

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

    
217
    mIsBandaged = bandaged;
218
    mQuatDebug = new int[NUM_CUBITS];
219

    
220
    mRotationAngle= new Dynamic1D();
221
    mRotationAxis = new Static3D(1,0,0);
222
    mRotateEffect = new VertexEffectRotate(mRotationAngle, mRotationAxis, CENTER);
223

    
224
    mRotationAngleStatic = new Static1D(0);
225
    mRotationAngleMiddle = new Static1D(0);
226
    mRotationAngleFinal  = new Static1D(0);
227

    
228
    mObjectScale = new Static3D(scale,scale,scale);
229
    setObjectRatioNow(scale,720);
230

    
231
    MatrixEffectScale scaleEffect = new MatrixEffectScale(mObjectScale);
232
    MatrixEffectQuaternion quatEffect = new MatrixEffectQuaternion(mQuat, CENTER);
233
    MatrixEffectMove moveEffect = new MatrixEffectMove(move);
234

    
235
    boolean fromDMESH = (stream!=null && meshState==MESH_NICE);
236
    getQuatsAndShapes(fromDMESH,fromJSON);
237
    createMeshAndCubits(stream,meshState,fromDMESH,fromJSON);
238
    setUpTextures(fromDMESH,fromJSON);
239
    createDataStructuresForSolved(mNumLayers);
240

    
241
    mEffects = new DistortedEffects();
242

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

    
250
    mEffects.apply(mRotateEffect);
251
    mEffects.apply(quatEffect);
252
    mEffects.apply(scaleEffect);
253
    mEffects.apply(moveEffect);
254

    
255
    mNode = new DistortedNode(mTexture,mEffects,mMesh);
256
    }
257

    
258
///////////////////////////////////////////////////////////////////////////////////////////////////
259

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

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

    
274
    sumX /= len;
275
    sumY /= len;
276
    sumZ /= len;
277

    
278
    return new Static3D(sumX,sumY,sumZ);
279
    }
280

    
281
///////////////////////////////////////////////////////////////////////////////////////////////////
282

    
283
  private void getQuatsAndShapes(boolean fromDMESH, boolean fromJSON)
284
    {
285
    mNumCubitVariants = getNumCubitVariants(mNumLayers);
286

    
287
    if( !fromDMESH || !fromJSON )
288
      {
289
      FactoryCubit factory = FactoryCubit.getInstance();
290
      factory.clear();
291

    
292
      mOrigQuat = new Static4D[NUM_CUBITS];
293
      for(int i=0; i<NUM_CUBITS; i++) mOrigQuat[i] = getQuat(i,mNumLayers);
294

    
295
      mShapes = new ObjectShape[mNumCubitVariants];
296
      for(int i=0; i<mNumCubitVariants; i++) mShapes[i] = getObjectShape(i);
297
      mNumCubitFaces = ObjectShape.computeNumComponents(mShapes);
298

    
299
      if( fromDMESH )
300
        {
301
        for(int i=0; i<mNumCubitVariants; i++) factory.createNewFaceTransform(mShapes[i]);
302
        }
303

    
304
      if( !fromJSON )
305
        {
306
        mCubitFaceColors = ObjectShape.computeColors(mShapes,mOrigPos,mOrigQuat,this);
307
        }
308
      }
309
    }
310

    
311
///////////////////////////////////////////////////////////////////////////////////////////////////
312

    
313
  private void createMeshAndCubits(InputStream stream, int meshState, boolean fromDMESH, boolean fromJSON)
314
    {
315
    CUBITS = new Cubit[NUM_CUBITS];
316

    
317
    if( fromDMESH )
318
      {
319
      DataInputStream dos = new DataInputStream(stream);
320
      mMesh = new MeshFile(dos);
321

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

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

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

    
350
      mMesh = new MeshJoined(cubitMesh);
351
      }
352
    }
353

    
354
///////////////////////////////////////////////////////////////////////////////////////////////////
355

    
356
  private MeshBase createCubitMesh(int cubit, int[] numLayers, int meshState, int numComponents)
357
    {
358
    int variant = getCubitVariant(cubit,numLayers);
359

    
360
    if( mMeshes==null ) mMeshes = new MeshBase[mNumCubitVariants];
361

    
362
    if( mMeshes[variant]==null )
363
      {
364
      ObjectFaceShape faceShape = getObjectFaceShape(variant);
365
      FactoryCubit factory = FactoryCubit.getInstance();
366
      factory.createNewFaceTransform(mShapes[variant]);
367
      mMeshes[variant] = factory.createRoundedSolid(mShapes[variant],faceShape,meshState, numComponents);
368
      }
369

    
370
    MeshBase mesh = mMeshes[variant].copy(true);
371
    MatrixEffectQuaternion quat = new MatrixEffectQuaternion( mOrigQuat[cubit], CENTER );
372
    mesh.apply(quat,0xffffffff,0);
373

    
374
    return mesh;
375
    }
376

    
377
///////////////////////////////////////////////////////////////////////////////////////////////////
378

    
379
  private void setUpTextures(boolean fromDMESH, boolean fromJSON)
380
    {
381
    mTexture = new DistortedTexture();
382

    
383
    if( fromJSON )
384
      {
385
      mNumStickerTypes = getNumStickerTypes();
386
      mNumCubitFaces = getNumCubitFaces();
387
      }
388
    else
389
      {
390
      FactoryCubit factory = FactoryCubit.getInstance();
391
      mStickerCoords   = factory.getOuterStickerCoords();
392
      mStickerVariants = factory.getStickerVariants();
393
      mStickerScales   = factory.getOuterStickerScales();
394
      mNumStickerTypes = mStickerCoords.length;
395
      adjustStickerCoords();
396
      }
397

    
398
    NUM_TEXTURES = NUM_FACE_COLORS*mNumStickerTypes;
399
    mNumTexCols = NUM_STICKERS_IN_ROW;
400
    mNumTexRows = (NUM_TEXTURES+1)/NUM_STICKERS_IN_ROW;
401
    if( mNumTexCols*mNumTexRows < NUM_TEXTURES+1 ) mNumTexRows++;
402

    
403
    if( !fromDMESH || shouldResetTextureMaps() ) resetAllTextureMaps();
404
    setTexture();
405
    }
406

    
407
///////////////////////////////////////////////////////////////////////////////////////////////////
408

    
409
  private void createDataStructuresForSolved(int[] numLayers)
410
    {
411
    mTmpQuats = new int[NUM_QUATS];
412
    mSolvedQuats = new int[NUM_CUBITS][];
413

    
414
    for(int c=0; c<NUM_CUBITS; c++)
415
      {
416
      mSolvedQuats[c] = getSolvedQuats(c,numLayers);
417
      }
418
    }
419

    
420
///////////////////////////////////////////////////////////////////////////////////////////////////
421

    
422
  private int getMultQuat(int index1, int index2)
423
    {
424
    if( mQuatMult==null )
425
      {
426
      mQuatMult = new int[NUM_QUATS][NUM_QUATS];
427

    
428
      for(int i=0; i<NUM_QUATS; i++)
429
        for(int j=0; j<NUM_QUATS; j++) mQuatMult[i][j] = -1;
430
      }
431

    
432
    if( mQuatMult[index1][index2]==-1 )
433
      {
434
      mQuatMult[index1][index2] = mulQuat(index1,index2);
435
      }
436

    
437
    return mQuatMult[index1][index2];
438
    }
439

    
440
///////////////////////////////////////////////////////////////////////////////////////////////////
441

    
442
  public int getVariantFaceColor(int variant, int face)
443
    {
444
    return face>=mStickerVariants[variant].length ? -1 : mStickerVariants[variant][face];
445
    }
446

    
447
///////////////////////////////////////////////////////////////////////////////////////////////////
448
// This is used to build internal data structures for the generic 'isSolved()'
449
//
450
// if this is an internal cubit (all faces black): return -1
451
// if this is a face cubit (one non-black face): return the color index of the only non-black face.
452
// Color index, i.e. the index into the 'FACE_COLORS' table.
453
// else (edge or corner cubit, more than one non-black face): return -2.
454

    
455
  protected int retCubitSolvedStatus(int cubit, int[] numLayers)
456
    {
457
    int numNonBlack=0, nonBlackIndex=-1, varColor, cubColor;
458
    int variant = getCubitVariant(cubit,numLayers);
459

    
460
    for(int face=0; face<mNumCubitFaces; face++)
461
      {
462
      varColor = getVariantFaceColor(variant,face);
463
      cubColor = getCubitFaceColor(cubit,face,numLayers);
464

    
465
      if( varColor>=0 && cubColor>=0 )
466
        {
467
        numNonBlack++;
468
        nonBlackIndex = cubColor;
469
        }
470
      }
471

    
472
    if( numNonBlack==0 ) return -1;
473
    if( numNonBlack>=2 ) return -2;
474

    
475
    return nonBlackIndex;
476
    }
477

    
478
///////////////////////////////////////////////////////////////////////////////////////////////////
479

    
480
  public boolean shouldResetTextureMaps()
481
    {
482
    return false;
483
    }
484

    
485
///////////////////////////////////////////////////////////////////////////////////////////////////
486

    
487
  protected int[] buildSolvedQuats(Static3D faceAx, Static4D[] quats)
488
    {
489
    final float MAXD = 0.0001f;
490
    float x = faceAx.get0();
491
    float y = faceAx.get1();
492
    float z = faceAx.get2();
493
    float a,dx,dy,dz,qx,qy,qz;
494
    Static4D quat;
495

    
496
    int len = quats.length;
497
    int place = 0;
498

    
499
    for(int q=1; q<len; q++)
500
      {
501
      quat = quats[q];
502
      qx = quat.get0();
503
      qy = quat.get1();
504
      qz = quat.get2();
505

    
506
           if( x!=0.0f ) { a = qx/x; }
507
      else if( y!=0.0f ) { a = qy/y; }
508
      else               { a = qz/z; }
509

    
510
      dx = a*x-qx;
511
      dy = a*y-qy;
512
      dz = a*z-qz;
513

    
514
      if( dx>-MAXD && dx<MAXD && dy>-MAXD && dy<MAXD && dz>-MAXD && dz<MAXD )
515
        {
516
        mTmpQuats[place++] = q;
517
        }
518
      }
519

    
520
    if( place!=0 )
521
      {
522
      int[] ret = new int[place];
523
      System.arraycopy(mTmpQuats,0,ret,0,place);
524
      return ret;
525
      }
526

    
527
    return null;
528
    }
529

    
530
///////////////////////////////////////////////////////////////////////////////////////////////////
531

    
532
  private boolean isSolved0()
533
    {
534
    int len, q1,q = CUBITS[0].mQuatIndex;
535
    int[] solved;
536
    boolean skip;
537

    
538
    for(int c=1; c<NUM_CUBITS; c++)
539
      {
540
      q1 = CUBITS[c].mQuatIndex;
541

    
542
      if( q1==q ) continue;
543

    
544
      skip = false;
545
      solved = mSolvedQuats[c];
546
      len = solved==null ? 0:solved.length;
547

    
548
      for(int i=0; i<len; i++)
549
        {
550
        if( q1==getMultQuat(q,solved[i]) )
551
          {
552
          skip = true;
553
          break;
554
          }
555
        }
556

    
557
      if( !skip ) return false;
558
      }
559

    
560
    return true;
561
    }
562

    
563
///////////////////////////////////////////////////////////////////////////////////////////////////
564

    
565
  private int computeScramble(int quatNum, int centerNum)
566
    {
567
    float MAXDIFF = 0.01f;
568
    float[] center= mOrigPos[centerNum];
569
    Static4D sc = new Static4D(center[0], center[1], center[2], 1.0f);
570
    Static4D result = QuatHelper.rotateVectorByQuat(sc,OBJECT_QUATS[quatNum]);
571

    
572
    float x = result.get0();
573
    float y = result.get1();
574
    float z = result.get2();
575

    
576
    for(int c=0; c<NUM_CUBITS; c++)
577
      {
578
      float[] cent = mOrigPos[c];
579

    
580
      float qx = cent[0] - x;
581
      float qy = cent[1] - y;
582
      float qz = cent[2] - z;
583

    
584
      if( qx>-MAXDIFF && qx<MAXDIFF &&
585
          qy>-MAXDIFF && qy<MAXDIFF &&
586
          qz>-MAXDIFF && qz<MAXDIFF  ) return c;
587
      }
588

    
589
    return -1;
590
    }
591

    
592
///////////////////////////////////////////////////////////////////////////////////////////////////
593
// Dino4 uses this. It is solved if and only if groups of cubits
594
// (0,3,7), (1,2,5), (4,8,9), (6,10,11)
595
// or
596
// (0,1,4), (2,3,6), (5,9,10), (7,8,11)
597
// are all the same color.
598

    
599
  private boolean isSolved1()
600
    {
601
    if( mScramble==null )
602
      {
603
      mScramble = new int[NUM_QUATS][NUM_CUBITS];
604
      mColors   = new int[NUM_CUBITS];
605

    
606
      for(int q=0; q<NUM_QUATS; q++)
607
        for(int c=0; c<NUM_CUBITS; c++) mScramble[q][c] = computeScramble(q,c);
608
      }
609

    
610
    if( mFaceMap==null )
611
      {
612
      mFaceMap = new int[] { 4, 2, 2, 4, 0, 2, 1, 4, 0, 0, 1, 1 };
613
      }
614

    
615
    for(int c=0; c<NUM_CUBITS; c++)
616
      {
617
      int index = mScramble[CUBITS[c].mQuatIndex][c];
618
      mColors[index] = mFaceMap[c];
619
      }
620

    
621
    if( mColors[0]==mColors[3] && mColors[0]==mColors[7] &&
622
        mColors[1]==mColors[2] && mColors[1]==mColors[5] &&
623
        mColors[4]==mColors[8] && mColors[4]==mColors[9]  ) return true;
624

    
625
    if( mColors[0]==mColors[1] && mColors[0]==mColors[4] &&
626
        mColors[2]==mColors[3] && mColors[2]==mColors[6] &&
627
        mColors[5]==mColors[9] && mColors[5]==mColors[10] ) return true;
628

    
629
    return false;
630
    }
631

    
632
///////////////////////////////////////////////////////////////////////////////////////////////////
633
// Dino6 uses this. It is solved if and only if:
634
//
635
// All four 'X' cubits (i.e. those whose longest edge goes along the X axis) are rotated
636
// by the same quaternion qX, similarly all four 'Y' cubits by the same qY and all four 'Z'
637
// by the same qZ, and then either:
638
//
639
// a) qX = qY = qZ
640
// b) qY = qX*Q2 and qZ = qX*Q8  (i.e. swap of WHITE and YELLOW faces)
641
// c) qX = qY*Q2 and qZ = qY*Q10 (i.e. swap of BLUE and GREEN faces)
642
// d) qX = qZ*Q8 and qY = qZ*Q10 (i.e. swap of RED and BROWN faces)
643
//
644
// BUT: cases b), c) and d) are really the same - it's all just a mirror image of the original.
645
//
646
// X cubits: 0, 2, 8, 10
647
// Y cubits: 1, 3, 9, 11
648
// Z cubits: 4, 5, 6, 7
649

    
650
  private boolean isSolved2()
651
    {
652
    int qX = CUBITS[0].mQuatIndex;
653
    int qY = CUBITS[1].mQuatIndex;
654
    int qZ = CUBITS[4].mQuatIndex;
655

    
656
    if( CUBITS[2].mQuatIndex != qX || CUBITS[8].mQuatIndex != qX || CUBITS[10].mQuatIndex != qX ||
657
        CUBITS[3].mQuatIndex != qY || CUBITS[9].mQuatIndex != qY || CUBITS[11].mQuatIndex != qY ||
658
        CUBITS[5].mQuatIndex != qZ || CUBITS[6].mQuatIndex != qZ || CUBITS[ 7].mQuatIndex != qZ  )
659
      {
660
      return false;
661
      }
662

    
663
    return ( qX==qY && qX==qZ ) || ( qY==mulQuat(qX,2) && qZ==mulQuat(qX,8) );
664
    }
665

    
666
///////////////////////////////////////////////////////////////////////////////////////////////////
667
// Square-2 is solved iff
668
// a) all of its cubits are rotated with the same quat
669
// b) its two 'middle' cubits are rotated with the same quat, the 6 'front' and 6 'back'
670
// edges and corners with this quat multiplied by QUATS[18] (i.e. those are upside down)
671
// and all the 12 left and right edges and corners also with the same quat multiplied by
672
// QUATS[12] - i.e. also upside down.
673

    
674
  private boolean isSolved3()
675
    {
676
    int index = CUBITS[0].mQuatIndex;
677

    
678
    if( CUBITS[1].mQuatIndex!=index ) return false;
679

    
680
    boolean solved = true;
681

    
682
    for(int i=2; i<NUM_CUBITS; i++)
683
      {
684
      if( CUBITS[i].mQuatIndex!=index )
685
        {
686
        solved = false;
687
        break;
688
        }
689
      }
690

    
691
    if( solved ) return true;
692

    
693
    int indexX = mulQuat(index,12);  // QUATS[12] = 180deg (1,0,0)
694
    int indexZ = mulQuat(index,18);  // QUATS[18] = 180deg (0,0,1)
695

    
696
    for(int i= 2; i<        18; i+=2) if( CUBITS[i].mQuatIndex != indexZ ) return false;
697
    for(int i= 3; i<        18; i+=2) if( CUBITS[i].mQuatIndex != indexX ) return false;
698
    for(int i=18; i<NUM_CUBITS; i+=2) if( CUBITS[i].mQuatIndex != indexX ) return false;
699
    for(int i=19; i<NUM_CUBITS; i+=2) if( CUBITS[i].mQuatIndex != indexZ ) return false;
700

    
701
    return true;
702
    }
703

    
704
///////////////////////////////////////////////////////////////////////////////////////////////////
705

    
706
  int computeRow(float[] pos, int axisIndex)
707
    {
708
    int ret=0;
709
    int len = pos.length / 3;
710
    Static3D axis = mAxis[axisIndex];
711
    float axisX = axis.get0();
712
    float axisY = axis.get1();
713
    float axisZ = axis.get2();
714
    float casted;
715

    
716
    for(int i=0; i<len; i++)
717
      {
718
      casted = pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ;
719
      ret |= computeSingleRow(axisIndex,casted);
720
      }
721

    
722
    return ret;
723
    }
724

    
725
///////////////////////////////////////////////////////////////////////////////////////////////////
726

    
727
  private int computeSingleRow(int axisIndex,float casted)
728
    {
729
    int num = mNumCuts[axisIndex];
730

    
731
    for(int i=0; i<num; i++)
732
      {
733
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
734
      }
735

    
736
    return (1<<num);
737
    }
738

    
739
///////////////////////////////////////////////////////////////////////////////////////////////////
740

    
741
  private boolean wasRotateApplied()
742
    {
743
    return mEffects.exists(mRotateEffect.getID());
744
    }
745

    
746
///////////////////////////////////////////////////////////////////////////////////////////////////
747

    
748
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
749
    {
750
    return (CUBITS[cubit].getRotRow(axis) & rowBitmap) != 0;
751
    }
752

    
753
///////////////////////////////////////////////////////////////////////////////////////////////////
754
// note the minus in front of the sin() - we rotate counterclockwise
755
// when looking towards the direction where the axis increases in values.
756

    
757
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
758
    {
759
    Static3D axis = mAxis[axisIndex];
760

    
761
    while( angleInDegrees<0 ) angleInDegrees += 360;
762
    angleInDegrees %= 360;
763
    
764
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
765
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
766

    
767
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
768
    }
769

    
770
///////////////////////////////////////////////////////////////////////////////////////////////////
771

    
772
  private synchronized void setupPosition(int[][] moves)
773
    {
774
    if( moves!=null )
775
      {
776
      Static4D quat;
777
      int index, axis, rowBitmap, angle;
778
      int[] basic = getBasicAngle();
779

    
780
      for(int[] move: moves)
781
        {
782
        axis     = move[0];
783
        rowBitmap= move[1];
784
        angle    = move[2]*(360/basic[axis]);
785
        quat     = makeQuaternion(axis,angle);
786

    
787
        for(int j=0; j<NUM_CUBITS; j++)
788
          if( belongsToRotation(j,axis,rowBitmap) )
789
            {
790
            index = CUBITS[j].removeRotationNow(quat);
791
            mMesh.setEffectAssociation(j, CUBITS[j].computeAssociation(),index);
792
            }
793
        }
794
      }
795
    }
796

    
797
///////////////////////////////////////////////////////////////////////////////////////////////////
798

    
799
  public int getScrambleType()
800
    {
801
    return 0;
802
    }
803

    
804
///////////////////////////////////////////////////////////////////////////////////////////////////
805

    
806
  int computeBitmapFromRow(int rowBitmap, int axis)
807
    {
808
    if( mIsBandaged )
809
      {
810
      int bitmap, initBitmap=0;
811

    
812
      while( initBitmap!=rowBitmap )
813
        {
814
        initBitmap = rowBitmap;
815

    
816
        for(int cubit=0; cubit<NUM_CUBITS; cubit++)
817
          {
818
          bitmap = CUBITS[cubit].getRotRow(axis);
819
          if( (rowBitmap & bitmap) != 0 ) rowBitmap |= bitmap;
820
          }
821
        }
822
      }
823

    
824
    return rowBitmap;
825
    }
826

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

    
831
  void clampPos(float[] pos, int offset)
832
    {
833
    float currError, minError = Float.MAX_VALUE;
834
    int minErrorIndex1 = -1;
835
    int minErrorIndex2 = -1;
836

    
837
    float x = pos[offset  ];
838
    float y = pos[offset+1];
839
    float z = pos[offset+2];
840

    
841
    float xo,yo,zo;
842

    
843
    for(int i=0; i<NUM_CUBITS; i++)
844
      {
845
      int len = mOrigPos[i].length / 3;
846

    
847
      for(int j=0; j<len; j++)
848
        {
849
        xo = mOrigPos[i][3*j  ];
850
        yo = mOrigPos[i][3*j+1];
851
        zo = mOrigPos[i][3*j+2];
852

    
853
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
854

    
855
        if( currError<minError )
856
          {
857
          minError = currError;
858
          minErrorIndex1 = i;
859
          minErrorIndex2 = j;
860
          }
861
        }
862
      }
863

    
864
    if( minError< 0.1f ) // TODO: 0.1 ?
865
      {
866
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
867
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
868
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
869
      }
870
    }
871

    
872
///////////////////////////////////////////////////////////////////////////////////////////////////
873
// remember about the double cover or unit quaternions!
874

    
875
  int mulQuat(int q1, int q2)
876
    {
877
    Static4D result = QuatHelper.quatMultiply(OBJECT_QUATS[q1],OBJECT_QUATS[q2]);
878

    
879
    float rX = result.get0();
880
    float rY = result.get1();
881
    float rZ = result.get2();
882
    float rW = result.get3();
883

    
884
    final float MAX_ERROR = 0.1f;
885
    float dX,dY,dZ,dW;
886

    
887
    for(int i=0; i<NUM_QUATS; i++)
888
      {
889
      dX = OBJECT_QUATS[i].get0() - rX;
890
      dY = OBJECT_QUATS[i].get1() - rY;
891
      dZ = OBJECT_QUATS[i].get2() - rZ;
892
      dW = OBJECT_QUATS[i].get3() - rW;
893

    
894
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
895
          dY<MAX_ERROR && dY>-MAX_ERROR &&
896
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
897
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
898

    
899
      dX = OBJECT_QUATS[i].get0() + rX;
900
      dY = OBJECT_QUATS[i].get1() + rY;
901
      dZ = OBJECT_QUATS[i].get2() + rZ;
902
      dW = OBJECT_QUATS[i].get3() + rW;
903

    
904
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
905
          dY<MAX_ERROR && dY>-MAX_ERROR &&
906
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
907
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
908
      }
909

    
910
    return -1;
911
    }
912

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

    
915
  private float getAngle()
916
    {
917
    int pointNum = mRotationAngle.getNumPoints();
918

    
919
    if( pointNum>=1 )
920
      {
921
      return mRotationAngle.getPoint(pointNum-1).get0();
922
      }
923
    else
924
      {
925
      mInterface.reportProblem("points in RotationAngle: "+pointNum, false);
926
      return 0;
927
      }
928
    }
929

    
930
///////////////////////////////////////////////////////////////////////////////////////////////////
931

    
932
  void setLibInterface(ObjectLibInterface inter)
933
    {
934
    mInterface = inter;
935
    }
936

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

    
939
  void initializeObject(int[][] moves)
940
    {
941
    solve();
942
    setupPosition(moves);
943
    }
944

    
945
///////////////////////////////////////////////////////////////////////////////////////////////////
946

    
947
  synchronized void removeRotationNow()
948
    {
949
    float angle = getAngle();
950
    double nearestAngleInRadians = angle*Math.PI/180;
951
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
952
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
953
    float axisX = mAxis[mCurrentRotAxis].get0();
954
    float axisY = mAxis[mCurrentRotAxis].get1();
955
    float axisZ = mAxis[mCurrentRotAxis].get2();
956
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
957

    
958
    mRotationAngle.removeAll();
959
    mRotationAngleStatic.set0(0);
960

    
961
    for(int i=0; i<NUM_CUBITS; i++)
962
      if( belongsToRotation(i, mCurrentRotAxis,mRotRowBitmap) )
963
        {
964
        int index = CUBITS[i].removeRotationNow(quat);
965
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),index);
966
        }
967
    }
968

    
969
///////////////////////////////////////////////////////////////////////////////////////////////////
970

    
971
  long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
972
    {
973
    if( wasRotateApplied() )
974
      {
975
      float angle = getAngle();
976
      mRotationAngleStatic.set0(angle);
977
      mRotationAngleFinal.set0(nearestAngleInDegrees);
978
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
979

    
980
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
981
      mRotationAngle.resetToBeginning();
982
      mRotationAngle.removeAll();
983
      mRotationAngle.add(mRotationAngleStatic);
984
      mRotationAngle.add(mRotationAngleMiddle);
985
      mRotationAngle.add(mRotationAngleFinal);
986
      mRotateEffect.notifyWhenFinished(listener);
987

    
988
      return mRotateEffect.getID();
989
      }
990

    
991
    return 0;
992
    }
993

    
994
///////////////////////////////////////////////////////////////////////////////////////////////////
995

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

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

    
1012
      return mRotateEffect.getID();
1013
      }
1014

    
1015
    return 0;
1016
    }
1017

    
1018
///////////////////////////////////////////////////////////////////////////////////////////////////
1019

    
1020
  void continueRotation(float angleInDegrees)
1021
    {
1022
    mRotationAngleStatic.set0(angleInDegrees);
1023
    }
1024

    
1025
///////////////////////////////////////////////////////////////////////////////////////////////////
1026

    
1027
  synchronized void beginNewRotation(int axis, int row )
1028
    {
1029
    if( axis<0 || axis>=NUM_AXIS )
1030
      {
1031
      android.util.Log.e("object", "invalid rotation axis: "+axis);
1032
      return;
1033
      }
1034
    if( row<0 || row>=mNumLayers[axis] )
1035
      {
1036
      android.util.Log.e("object", "invalid rotation row: "+row);
1037
      return;
1038
      }
1039

    
1040
    mCurrentRotAxis = axis;
1041
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
1042
    mRotationAngleStatic.set0(0.0f);
1043
    mRotationAxis.set( mAxis[axis] );
1044
    mRotationAngle.add(mRotationAngleStatic);
1045
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*SHIFT) , -1);
1046
    }
1047

    
1048
///////////////////////////////////////////////////////////////////////////////////////////////////
1049

    
1050
  void setTextureMap(int cubit, int face, int newColor)
1051
    {
1052
    final float ratioW = 1.0f/mNumTexCols;
1053
    final float ratioH = 1.0f/mNumTexRows;
1054
    final Static4D[] maps = new Static4D[mNumCubitFaces];
1055
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
1056
    int col = newColor%mNumTexCols;
1057

    
1058
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1059
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1060
    }
1061

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

    
1064
  public int getCubitFaceColor(int cubit, int face, int[] numLayers)
1065
    {
1066
    int numFaces = mCubitFaceColors[cubit].length;
1067
    int newColor = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
1068

    
1069
    return newColor<0 ? -1 : newColor%NUM_FACE_COLORS;
1070
    }
1071

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

    
1074
  void resetAllTextureMaps()
1075
    {
1076
    final float ratioW = 1.0f/mNumTexCols;
1077
    final float ratioH = 1.0f/mNumTexRows;
1078
    int cubColor, varColor, color, variant, row, col;
1079

    
1080
    for(int cubit=0; cubit<NUM_CUBITS; cubit++)
1081
      {
1082
      final Static4D[] maps = new Static4D[mNumCubitFaces];
1083
      variant = getCubitVariant(cubit,mNumLayers);
1084

    
1085
      for(int face=0; face<mNumCubitFaces; face++)
1086
        {
1087
        cubColor = getCubitFaceColor(cubit,face,mNumLayers);
1088
        varColor = getVariantFaceColor(variant,face);
1089
        color    = cubColor<0 || varColor<0 ? NUM_TEXTURES : varColor*NUM_FACE_COLORS + cubColor;
1090
        row      = (mNumTexRows-1) - color/mNumTexCols;
1091
        col      = color%mNumTexCols;
1092

    
1093
        maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1094
        }
1095

    
1096
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1097
      }
1098
    }
1099

    
1100
///////////////////////////////////////////////////////////////////////////////////////////////////
1101

    
1102
  void releaseResources()
1103
    {
1104
    mTexture.markForDeletion();
1105
    mMesh.markForDeletion();
1106
    mEffects.markForDeletion();
1107

    
1108
    for(int j=0; j<NUM_CUBITS; j++)
1109
      {
1110
      CUBITS[j].releaseResources();
1111
      }
1112
    }
1113

    
1114
///////////////////////////////////////////////////////////////////////////////////////////////////
1115

    
1116
  synchronized void restorePreferences(SharedPreferences preferences)
1117
    {
1118
    boolean error = false;
1119

    
1120
    for(int i=0; i<NUM_CUBITS; i++)
1121
      {
1122
      mQuatDebug[i] = CUBITS[i].restorePreferences(preferences);
1123

    
1124
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<NUM_QUATS)
1125
        {
1126
        CUBITS[i].modifyCurrentPosition(OBJECT_QUATS[mQuatDebug[i]]);
1127
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),mQuatDebug[i]);
1128
        }
1129
      else
1130
        {
1131
        error = true;
1132
        }
1133
      }
1134

    
1135
    if( error )
1136
      {
1137
      for(int i=0; i<NUM_CUBITS; i++)
1138
        {
1139
        CUBITS[i].solve();
1140
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),0);
1141
        }
1142
      }
1143
    }
1144

    
1145
///////////////////////////////////////////////////////////////////////////////////////////////////
1146

    
1147
  void savePreferences(SharedPreferences.Editor editor)
1148
    {
1149
    for(int i=0; i<NUM_CUBITS; i++) CUBITS[i].savePreferences(editor);
1150
    }
1151

    
1152
///////////////////////////////////////////////////////////////////////////////////////////////////
1153

    
1154
  private float computeRadiusCorrection(float[] sticker, int curr, int len)
1155
    {
1156
    final float A = 0.8f;  // 0<A<1
1157

    
1158
    int prev = curr>0 ? curr-1 : len-1;
1159
    int next = curr<len-1 ? curr+1 : 0;
1160

    
1161
    float v1x = sticker[2*prev  ]-sticker[2*curr  ];
1162
    float v1y = sticker[2*prev+1]-sticker[2*curr+1];
1163
    float v2x = sticker[2*next  ]-sticker[2*curr  ];
1164
    float v2y = sticker[2*next+1]-sticker[2*curr+1];
1165

    
1166
    float len1= v1x*v1x+v1y*v1y;
1167
    float len2= v2x*v2x+v2y*v2y;
1168

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

    
1171
    return 1-A*cos;
1172
    }
1173

    
1174
///////////////////////////////////////////////////////////////////////////////////////////////////
1175

    
1176
  public ObjectSticker retSticker(int sticker)
1177
    {
1178
    if( mStickers==null )
1179
      {
1180
      float rad = getStickerRadius();
1181
      float str = getStickerStroke();
1182
      float[][] angles = getStickerAngles();
1183
      int numStickers = mStickerCoords.length;
1184
      mStickers = new ObjectSticker[numStickers];
1185

    
1186
      for(int s=0; s<numStickers; s++)
1187
        {
1188
        float scale = mStickerScales[s];
1189
        float radius = rad / scale;
1190
        float stroke = str / scale;
1191
        int len = mStickerCoords[s].length/2;
1192
        float[] radii = new float[len];
1193
        for(int r=0; r<len; r++) radii[r] = radius*computeRadiusCorrection(mStickerCoords[s],r,len);
1194
        mStickers[s] = new ObjectSticker(mStickerCoords[s],angles==null ? null : angles[s],radii,stroke);
1195
        }
1196
      }
1197

    
1198
    return mStickers[sticker];
1199
    }
1200

    
1201
///////////////////////////////////////////////////////////////////////////////////////////////////
1202
// some objects (currently Kilominx,Ivy,Rex) might want to change the stickers.
1203

    
1204
  public void adjustStickerCoords()
1205
    {
1206

    
1207
    }
1208

    
1209
///////////////////////////////////////////////////////////////////////////////////////////////////
1210
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
1211

    
1212
  private void createTexture()
1213
    {
1214
    Paint paint = new Paint();
1215
    mBitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_8888);
1216
    Canvas canvas = new Canvas(mBitmap);
1217

    
1218
    paint.setAntiAlias(true);
1219
    paint.setTextAlign(Paint.Align.CENTER);
1220
    paint.setStyle(Paint.Style.FILL);
1221

    
1222
    paint.setColor(COLOR_INTERNAL);
1223
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
1224

    
1225
    int texture = 0;
1226
    FactorySticker factory = FactorySticker.getInstance();
1227

    
1228
    for(int row=0; row<mNumTexRows; row++)
1229
      for(int col=0; col<mNumTexCols; col++)
1230
        {
1231
        if( texture>=NUM_TEXTURES ) break;
1232
        ObjectSticker sticker = retSticker(texture/NUM_FACE_COLORS);
1233
        int color = getColor(texture%NUM_FACE_COLORS);
1234
        factory.drawRoundedPolygon(canvas, paint, col*TEXTURE_HEIGHT, row*TEXTURE_HEIGHT, color, sticker);
1235
        texture++;
1236
        }
1237
    }
1238

    
1239
///////////////////////////////////////////////////////////////////////////////////////////////////
1240

    
1241
  void setTexture()
1242
    {
1243
    if( mBitmap==null ) createTexture();
1244

    
1245
    if( !mTexture.setTexture(mBitmap) )
1246
      {
1247
      int max = DistortedLibrary.getMaxTextureSize();
1248
      mInterface.reportProblem("failed to set texture of size "+mBitmap.getWidth()+"x"+mBitmap.getHeight()+" max is "+max, true);
1249
      }
1250
    }
1251

    
1252
///////////////////////////////////////////////////////////////////////////////////////////////////
1253

    
1254
  void setObjectRatioNow(float sc, int nodeSize)
1255
    {
1256
    mObjectScreenRatio = sc;
1257
    float scale = mObjectScreenRatio*mInitScreenRatio*nodeSize/mSize;
1258
    mObjectScale.set(scale,scale,scale);
1259

    
1260
    if( mTouchControl ==null ) mTouchControl = getTouchControl();
1261
    mTouchControl.setObjectRatio(mObjectScreenRatio*mInitScreenRatio);
1262
    }
1263

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

    
1266
  void setObjectRatio(float sizeChange, int nodeSize)
1267
    {
1268
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
1269

    
1270
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
1271
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
1272

    
1273
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1274
    }
1275

    
1276
///////////////////////////////////////////////////////////////////////////////////////////////////
1277

    
1278
  void setNodeSize(int nodeSize)
1279
    {
1280
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1281
    }
1282

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

    
1285
  public float getRatio()
1286
    {
1287
    return mObjectScreenRatio;
1288
    }
1289

    
1290
///////////////////////////////////////////////////////////////////////////////////////////////////
1291

    
1292
  public float getObjectRatio()
1293
    {
1294
    return mObjectScreenRatio*mInitScreenRatio;
1295
    }
1296

    
1297
///////////////////////////////////////////////////////////////////////////////////////////////////
1298

    
1299
  boolean isSolved()
1300
    {
1301
    if( mSolvedFunctionIndex==0 ) return isSolved0();
1302
    if( mSolvedFunctionIndex==1 ) return isSolved1();
1303
    if( mSolvedFunctionIndex==2 ) return isSolved2();
1304
    if( mSolvedFunctionIndex==3 ) return isSolved3();
1305

    
1306
    return false;
1307
    }
1308

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

    
1311
  int computeNearestAngle(int axis, float angle, float speed)
1312
    {
1313
    int[] basicArray = getBasicAngle();
1314
    int basicAngle   = basicArray[axis>=basicArray.length ? 0 : axis];
1315
    int nearestAngle = 360/basicAngle;
1316

    
1317
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
1318
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
1319

    
1320
    if( tmp!=0 ) return nearestAngle*tmp;
1321

    
1322
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
1323
    }
1324

    
1325
///////////////////////////////////////////////////////////////////////////////////////////////////
1326
// INTERNAL API - those are called from 'effects' package
1327
///////////////////////////////////////////////////////////////////////////////////////////////////
1328

    
1329
  public void randomizeNewScramble(int[][] scramble, Random rnd, int curr, int total)
1330
    {
1331
    mScrambler.randomizeNewScramble(scramble,rnd,curr,total);
1332
    }
1333

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

    
1336
  public Static4D getRotationQuat()
1337
    {
1338
    return mQuat;
1339
    }
1340

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

    
1343
  public float getSize()
1344
    {
1345
    return mSize;
1346
    }
1347

    
1348
///////////////////////////////////////////////////////////////////////////////////////////////////
1349

    
1350
  public void apply(Effect effect, int position)
1351
    {
1352
    mEffects.apply(effect, position);
1353
    }
1354

    
1355
///////////////////////////////////////////////////////////////////////////////////////////////////
1356

    
1357
  public void remove(long effectID)
1358
    {
1359
    mEffects.abortById(effectID);
1360
    }
1361

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

    
1364
  public MeshBase getObjectMesh()
1365
    {
1366
    return mMesh;
1367
    }
1368

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

    
1371
  public DistortedEffects getObjectEffects()
1372
    {
1373
    return mEffects;
1374
    }
1375

    
1376
///////////////////////////////////////////////////////////////////////////////////////////////////
1377
// PUBLIC API
1378
///////////////////////////////////////////////////////////////////////////////////////////////////
1379

    
1380
  public int getCubitFaceColorIndex(int cubit, int face)
1381
    {
1382
    Static4D texMap = mMesh.getTextureMap(NUM_FACE_COLORS*cubit + face);
1383

    
1384
    int x = (int)(texMap.get0()/texMap.get2());
1385
    int y = (int)(texMap.get1()/texMap.get3());
1386

    
1387
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
1388
    }
1389

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

    
1392
  public int[] getNumLayers()
1393
    {
1394
    return mNumLayers;
1395
    }
1396

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

    
1399
  public synchronized void solve()
1400
    {
1401
    for(int i=0; i<NUM_CUBITS; i++)
1402
      {
1403
      CUBITS[i].solve();
1404
      mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
1405
      }
1406
    }
1407

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

    
1410
  public int getCubitQuatIndex(int cubit)
1411
    {
1412
    return CUBITS[cubit].mQuatIndex;
1413
    }
1414

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

    
1417
  public int getCubitRotRow(int cubit, int axis)
1418
    {
1419
    return CUBITS[cubit].getRotRow(axis);
1420
    }
1421

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

    
1424
  public Bitmap getStickerBitmap()
1425
    {
1426
    return mBitmap;
1427
    }
1428

    
1429
///////////////////////////////////////////////////////////////////////////////////////////////////
1430

    
1431
  public DistortedNode getNode()
1432
    {
1433
    return mNode;
1434
    }
1435

    
1436
///////////////////////////////////////////////////////////////////////////////////////////////////
1437

    
1438
  public ObjectType getObjectType()
1439
    {
1440
    return intGetObjectType(mNumLayers);
1441
    }
1442

    
1443
///////////////////////////////////////////////////////////////////////////////////////////////////
1444

    
1445
  public int getNumStickerTypes()
1446
    {
1447
    return mNumStickerTypes;
1448
    }
1449

    
1450
///////////////////////////////////////////////////////////////////////////////////////////////////
1451
// this is here only so it can be overridden in TwistyJSON soo that we can get this from JSON.
1452

    
1453
  public int getNumCubitFaces()
1454
    {
1455
    return 0;
1456
    }
1457

    
1458
///////////////////////////////////////////////////////////////////////////////////////////////////
1459

    
1460
  public TouchControl getTouchControl()
1461
    {
1462
    if( mTouchControl==null )
1463
      {
1464
      switch(getTouchControlType())
1465
        {
1466
        case TC_TETRAHEDRON    : mTouchControl = new TouchControlTetrahedron(this);
1467
                                 break;
1468
        case TC_HEXAHEDRON     : mTouchControl = new TouchControlHexahedron(this);
1469
                                 break;
1470
        case TC_OCTAHEDRON     : mTouchControl = new TouchControlOctahedron(this);
1471
                                 break;
1472
        case TC_DODECAHEDRON   : mTouchControl = new TouchControlDodecahedron(this);
1473
                                 break;
1474
        case TC_CUBOID         : int[] numLayers = getNumLayers();
1475
                                 mTouchControl = new TouchControlCuboids(this,getDist3D(numLayers));
1476
                                 break;
1477
        case TC_CHANGING_MIRROR: mTouchControl = new TouchControlMirror(this);
1478
                                 break;
1479
        case TC_CHANGING_SQUARE: mTouchControl = new TouchControlSquare(this);
1480
                                 break;
1481
        }
1482
      }
1483
    return mTouchControl;
1484
    }
1485

    
1486
///////////////////////////////////////////////////////////////////////////////////////////////////
1487

    
1488
  public String getShortName()
1489
    {
1490
    return getObjectType().name();
1491
    }
1492

    
1493
///////////////////////////////////////////////////////////////////////////////////////////////////
1494

    
1495
  protected void setReader(JsonReader reader)
1496
    {
1497
    // empty
1498
    }
1499

    
1500
///////////////////////////////////////////////////////////////////////////////////////////////////
1501

    
1502
  protected abstract ObjectType intGetObjectType(int[] numLayers);
1503

    
1504
  // for JSON only
1505
  public abstract int getSolvedFunctionIndex();
1506
  public abstract int getTouchControlType();
1507
  public abstract int getTouchControlSplit();
1508
  public abstract boolean[][] getLayerRotatable(int[] numLayers);
1509
  public abstract int[][][] getEnabled();
1510
  public abstract float[] getDist3D(int[] numLayers);
1511
  public abstract Static3D[] getFaceAxis();
1512
  public abstract ScrambleState[] getScrambleStates();
1513
  public abstract float[][] getCuts(int[] numLayers);
1514
  public abstract Static4D[] getQuats();
1515
  public abstract float getStickerRadius();
1516
  public abstract float getStickerStroke();
1517
  public abstract float[][] getStickerAngles();
1518
  public abstract int getCubitVariant(int cubit, int[] numLayers);
1519
  public abstract ObjectShape getObjectShape(int variant);
1520
  public abstract ObjectFaceShape getObjectFaceShape(int variant);
1521
  public abstract int getNumCubitVariants(int[] numLayers);
1522
  public abstract float[][] getCubitPositions(int[] numLayers);
1523
  public abstract Static4D getQuat(int cubit, int[] numLayers);
1524
  public abstract int[] getSolvedQuats(int cubit, int[] numLayers);
1525
  public abstract int getNumFaceColors();
1526
  public abstract float getScreenRatio();
1527
  public abstract int getColor(int face);
1528

    
1529
  // not only for JSON
1530
  public abstract Static3D[] getRotationAxis();
1531
  public abstract int[] getBasicAngle();
1532
  public abstract int getNumFaces();
1533
  public abstract String getObjectName();
1534
  public abstract String getInventor();
1535
  public abstract int getYearOfInvention();
1536
  public abstract int getComplexity();
1537
  public abstract int getFOV();
1538
  }
(11-11/13)