Project

General

Profile

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

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

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 float[][] mStickerCoords;
96
  int mNumAxis, mMaxNumLayers;
97
  Static4D[] mObjectQuats;
98

    
99
  private int[][] mStickerVariants;
100
  private float[] mStickerScales;
101
  private Cubit[] mCubits;
102
  private MeshBase[] mMeshes;
103
  private int mNumCubits, mNumQuats, mNumFaceColors, mNumTextures;
104
  private int mNumCubitFaces, mNumStickerTypes;
105
  private Static3D[] mAxis;
106
  private float[][] mCuts;
107
  private int[] mNumCuts;
108
  private float[][] mOrigPos;
109
  private Static4D[] mOrigQuat;
110
  private Static4D mQuat;
111
  private final int[] mNumLayers;
112
  private final float mSize;
113
  private DistortedEffects mEffects;
114
  private VertexEffectRotate mRotateEffect;
115
  private Dynamic1D mRotationAngle;
116
  private Static3D mRotationAxis;
117
  private Static3D mObjectScale;
118
  private int[] mQuatDebug;
119
  private Static1D mRotationAngleStatic, mRotationAngleMiddle, mRotationAngleFinal;
120
  private DistortedTexture mTexture;
121
  private float mInitScreenRatio;
122
  private int mSolvedFunctionIndex;
123
  private boolean mIsBandaged;
124
  private float mObjectScreenRatio;
125
  private int[][] mSolvedQuats;
126
  private int[][] mQuatMult;
127
  private int[] mTmpQuats;
128
  private int mNumTexRows, mNumTexCols;
129
  private int mRotRowBitmap;
130
  private int mCurrentRotAxis;
131
  private MeshBase mMesh;
132
  private TwistyObjectScrambler mScrambler;
133
  private TouchControl mTouchControl;
134
  private DistortedNode mNode;
135
  private ObjectLibInterface mInterface;
136
  private Bitmap mBitmap;
137
  private ObjectSticker[] mStickers;
138
  private ObjectShape[] mShapes;
139
  private int mNumCubitVariants;
140
  private int[][] mCubitFaceColors;
141
  private int[][] mVariantFaceIsOuter;
142

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

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

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

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

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

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

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

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

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

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

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

    
192
    mNumCubits = mOrigPos.length;
193
    mNumFaceColors = getNumFaceColors();
194
    mNumAxis = mAxis.length;
195

    
196
    mObjectQuats = getQuats();
197
    mNumQuats = mObjectQuats.length;
198

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

    
203
    boolean bandaged=false;
204

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

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

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

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

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

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

    
232
    boolean fromDMESH = (stream!=null && meshState==MESH_NICE);
233
    getQuatsAndShapes(fromDMESH,fromJSON);
234
    createMeshAndCubits(stream,meshState,fromDMESH);
235
    setUpTextures(fromDMESH,fromJSON);
236
    createDataStructuresForSolved(mNumLayers);
237

    
238
    mEffects = new DistortedEffects();
239

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

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

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

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

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

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

    
271
    sumX /= len;
272
    sumY /= len;
273
    sumZ /= len;
274

    
275
    return new Static3D(sumX,sumY,sumZ);
276
    }
277

    
278
///////////////////////////////////////////////////////////////////////////////////////////////////
279

    
280
  private void createOuterFaces()
281
    {
282
    for(int v=0; v<mNumCubitVariants; v++)
283
      {
284
      int[][] indices = mShapes[v].getVertIndices();
285
      int faces = indices.length;
286
      mVariantFaceIsOuter[v] = new int[faces];
287
      }
288

    
289
    for( int cubit=0; cubit<mNumCubits; cubit++)
290
      {
291
      int variant = getCubitVariant(cubit,mNumLayers);
292
      int[][] indices = mShapes[variant].getVertIndices();
293
      int numFaces = indices.length;
294

    
295
      for(int face=0; face<numFaces; face++)
296
        if( getCubitFaceColor(cubit,face)>=0 )
297
          {
298
          mVariantFaceIsOuter[variant][face] = 1;
299
          }
300
      }
301
    }
302

    
303
///////////////////////////////////////////////////////////////////////////////////////////////////
304

    
305
  private void getQuatsAndShapes(boolean fromDMESH, boolean fromJSON)
306
    {
307
    mNumCubitVariants = getNumCubitVariants(mNumLayers);
308

    
309
    if( !fromDMESH || !fromJSON )
310
      {
311
      FactoryCubit factory = FactoryCubit.getInstance();
312
      factory.clear();
313

    
314
      mOrigQuat = new Static4D[mNumCubits];
315
      for(int i=0; i<mNumCubits; i++) mOrigQuat[i] = getCubitQuats(i,mNumLayers);
316

    
317
      mShapes = new ObjectShape[mNumCubitVariants];
318
      for(int i=0; i<mNumCubitVariants; i++) mShapes[i] = getObjectShape(i);
319
      mNumCubitFaces = ObjectShape.computeNumComponents(mShapes);
320
      mVariantFaceIsOuter = new int[mNumCubitVariants][];
321

    
322
      if( !fromJSON )
323
        {
324
        mCubitFaceColors = ObjectShape.computeColors(mShapes,mOrigPos,mOrigQuat,this);
325
        createOuterFaces();
326
        }
327

    
328
      if( fromDMESH )
329
        {
330
        for(int i=0; i<mNumCubitVariants; i++) factory.createNewFaceTransform(mShapes[i], mVariantFaceIsOuter[i]);
331
        }
332
      }
333
    }
334

    
335
///////////////////////////////////////////////////////////////////////////////////////////////////
336

    
337
  private void createMeshAndCubits(InputStream stream, int meshState, boolean fromDMESH)
338
    {
339
    mCubits = new Cubit[mNumCubits];
340

    
341
    if( fromDMESH )
342
      {
343
      DataInputStream dos = new DataInputStream(stream);
344
      mMesh = new MeshFile(dos);
345

    
346
      try
347
        {
348
        stream.close();
349
        }
350
      catch(IOException e)
351
        {
352
        android.util.Log.e("meshFile", "Error closing InputStream: "+e.toString());
353
        }
354

    
355
      for(int i=0; i<mNumCubits; i++)
356
        {
357
        mCubits[i] = new Cubit(this,mOrigPos[i], mNumAxis);
358
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(), 0);
359
        }
360
      }
361
    else
362
      {
363
      MeshBase[] cubitMesh = new MeshBase[mNumCubits];
364

    
365
      for(int i=0; i<mNumCubits; i++)
366
        {
367
        mCubits[i] = new Cubit(this,mOrigPos[i], mNumAxis);
368
        cubitMesh[i] = createCubitMesh(i,mNumLayers,meshState,mNumCubitFaces);
369
        Static3D pos = getPos(mOrigPos[i]);
370
        cubitMesh[i].apply(new MatrixEffectMove(pos),1,0);
371
        cubitMesh[i].setEffectAssociation(0, mCubits[i].computeAssociation(), 0);
372
        }
373

    
374
      mMesh = new MeshJoined(cubitMesh);
375
      }
376
    }
377

    
378
///////////////////////////////////////////////////////////////////////////////////////////////////
379

    
380
  private MeshBase createCubitMesh(int cubit, int[] numLayers, int meshState, int numComponents)
381
    {
382
    int variant = getCubitVariant(cubit,numLayers);
383

    
384
    if( mMeshes==null ) mMeshes = new MeshBase[mNumCubitVariants];
385

    
386
    if( mMeshes[variant]==null )
387
      {
388
      ObjectFaceShape faceShape = getObjectFaceShape(variant);
389
      FactoryCubit factory = FactoryCubit.getInstance();
390
      factory.createNewFaceTransform(mShapes[variant],mVariantFaceIsOuter[variant]);
391
      mMeshes[variant] = factory.createRoundedSolid(mShapes[variant],faceShape,meshState, numComponents);
392
      }
393

    
394
    MeshBase mesh = mMeshes[variant].copy(true);
395
    MatrixEffectQuaternion quat = new MatrixEffectQuaternion( mOrigQuat[cubit], CENTER );
396
    mesh.apply(quat,0xffffffff,0);
397

    
398
    return mesh;
399
    }
400

    
401
///////////////////////////////////////////////////////////////////////////////////////////////////
402

    
403
  private void setUpTextures(boolean fromDMESH, boolean fromJSON)
404
    {
405
    mTexture = new DistortedTexture();
406

    
407
    if( fromJSON )
408
      {
409
      mNumStickerTypes = getNumStickerTypes();
410
      mNumCubitFaces = getNumCubitFaces();
411
      }
412
    else
413
      {
414
      FactoryCubit factory = FactoryCubit.getInstance();
415
      mStickerCoords   = factory.getOuterStickerCoords();
416
      mStickerVariants = factory.getStickerVariants();
417
      mStickerScales   = factory.getOuterStickerScales();
418
      mNumStickerTypes = mStickerCoords.length;
419
      adjustStickerCoords();
420
      }
421

    
422
    mNumTextures= mNumFaceColors *mNumStickerTypes;
423
    mNumTexCols = NUM_STICKERS_IN_ROW;
424
    mNumTexRows = (mNumTextures+1)/NUM_STICKERS_IN_ROW;
425
    if( mNumTexCols*mNumTexRows < mNumTextures+1 ) mNumTexRows++;
426

    
427
    if( !fromDMESH || shouldResetTextureMaps() ) resetAllTextureMaps();
428
    setTexture();
429
    }
430

    
431
///////////////////////////////////////////////////////////////////////////////////////////////////
432

    
433
  private void createDataStructuresForSolved(int[] numLayers)
434
    {
435
    mTmpQuats = new int[mNumQuats];
436
    mSolvedQuats = new int[mNumCubits][];
437

    
438
    for(int c=0; c<mNumCubits; c++)
439
      {
440
      mSolvedQuats[c] = getSolvedQuats(c,numLayers);
441
      }
442
    }
443

    
444
///////////////////////////////////////////////////////////////////////////////////////////////////
445

    
446
  private int getMultQuat(int index1, int index2)
447
    {
448
    if( mQuatMult==null )
449
      {
450
      mQuatMult = new int[mNumQuats][mNumQuats];
451

    
452
      for(int i=0; i<mNumQuats; i++)
453
        for(int j=0; j<mNumQuats; j++) mQuatMult[i][j] = -1;
454
      }
455

    
456
    if( mQuatMult[index1][index2]==-1 )
457
      {
458
      mQuatMult[index1][index2] = mulQuat(index1,index2);
459
      }
460

    
461
    return mQuatMult[index1][index2];
462
    }
463

    
464
///////////////////////////////////////////////////////////////////////////////////////////////////
465

    
466
  public int getVariantFaceColor(int variant, int face)
467
    {
468
    return face>=mStickerVariants[variant].length ? -1 : mStickerVariants[variant][face];
469
    }
470

    
471
///////////////////////////////////////////////////////////////////////////////////////////////////
472
// This is used to build internal data structures for the generic 'isSolved()'
473
//
474
// if this is an internal cubit (all faces black): return -1
475
// if this is a face cubit (one non-black face): return the color index of the only non-black face.
476
// Color index, i.e. the index into the 'FACE_COLORS' table.
477
// else (edge or corner cubit, more than one non-black face): return -2.
478

    
479
  protected int retCubitSolvedStatus(int cubit, int[] numLayers)
480
    {
481
    int numNonBlack=0, nonBlackIndex=-1, varColor, cubColor;
482
    int variant = getCubitVariant(cubit,numLayers);
483

    
484
    for(int face=0; face<mNumCubitFaces; face++)
485
      {
486
      varColor = getVariantFaceColor(variant,face);
487
      cubColor = getCubitFaceColor(cubit,face);
488

    
489
      if( varColor>=0 && cubColor>=0 )
490
        {
491
        numNonBlack++;
492
        nonBlackIndex = cubColor;
493
        }
494
      }
495

    
496
    if( numNonBlack==0 ) return -1;
497
    if( numNonBlack>=2 ) return -2;
498

    
499
    return nonBlackIndex;
500
    }
501

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

    
504
  public boolean shouldResetTextureMaps()
505
    {
506
    return false;
507
    }
508

    
509
///////////////////////////////////////////////////////////////////////////////////////////////////
510

    
511
  protected int[] buildSolvedQuats(Static3D faceAx, Static4D[] quats)
512
    {
513
    final float MAXD = 0.0001f;
514
    float x = faceAx.get0();
515
    float y = faceAx.get1();
516
    float z = faceAx.get2();
517
    float a,dx,dy,dz,qx,qy,qz;
518
    Static4D quat;
519

    
520
    int len = quats.length;
521
    int place = 0;
522

    
523
    for(int q=1; q<len; q++)
524
      {
525
      quat = quats[q];
526
      qx = quat.get0();
527
      qy = quat.get1();
528
      qz = quat.get2();
529

    
530
           if( x!=0.0f ) { a = qx/x; }
531
      else if( y!=0.0f ) { a = qy/y; }
532
      else               { a = qz/z; }
533

    
534
      dx = a*x-qx;
535
      dy = a*y-qy;
536
      dz = a*z-qz;
537

    
538
      if( dx>-MAXD && dx<MAXD && dy>-MAXD && dy<MAXD && dz>-MAXD && dz<MAXD )
539
        {
540
        mTmpQuats[place++] = q;
541
        }
542
      }
543

    
544
    if( place!=0 )
545
      {
546
      int[] ret = new int[place];
547
      System.arraycopy(mTmpQuats,0,ret,0,place);
548
      return ret;
549
      }
550

    
551
    return null;
552
    }
553

    
554
///////////////////////////////////////////////////////////////////////////////////////////////////
555

    
556
  private boolean isSolved0()
557
    {
558
    int len, q1,q = mCubits[0].mQuatIndex;
559
    int[] solved;
560
    boolean skip;
561

    
562
    for(int c=1; c<mNumCubits; c++)
563
      {
564
      q1 = mCubits[c].mQuatIndex;
565

    
566
      if( q1==q ) continue;
567

    
568
      skip = false;
569
      solved = mSolvedQuats[c];
570
      len = solved==null ? 0:solved.length;
571

    
572
      for(int i=0; i<len; i++)
573
        {
574
        if( q1==getMultQuat(q,solved[i]) )
575
          {
576
          skip = true;
577
          break;
578
          }
579
        }
580

    
581
      if( !skip ) return false;
582
      }
583

    
584
    return true;
585
    }
586

    
587
///////////////////////////////////////////////////////////////////////////////////////////////////
588

    
589
  private int computeScramble(int quatNum, int centerNum)
590
    {
591
    float MAXDIFF = 0.01f;
592
    float[] center= mOrigPos[centerNum];
593
    Static4D sc = new Static4D(center[0], center[1], center[2], 1.0f);
594
    Static4D result = QuatHelper.rotateVectorByQuat(sc,mObjectQuats[quatNum]);
595

    
596
    float x = result.get0();
597
    float y = result.get1();
598
    float z = result.get2();
599

    
600
    for(int c=0; c<mNumCubits; c++)
601
      {
602
      float[] cent = mOrigPos[c];
603

    
604
      float qx = cent[0] - x;
605
      float qy = cent[1] - y;
606
      float qz = cent[2] - z;
607

    
608
      if( qx>-MAXDIFF && qx<MAXDIFF &&
609
          qy>-MAXDIFF && qy<MAXDIFF &&
610
          qz>-MAXDIFF && qz<MAXDIFF  ) return c;
611
      }
612

    
613
    return -1;
614
    }
615

    
616
///////////////////////////////////////////////////////////////////////////////////////////////////
617
// Dino4 uses this. It is solved if and only if groups of cubits
618
// (0,3,7), (1,2,5), (4,8,9), (6,10,11)
619
// or
620
// (0,1,4), (2,3,6), (5,9,10), (7,8,11)
621
// are all the same color.
622

    
623
  private boolean isSolved1()
624
    {
625
    if( mScramble==null )
626
      {
627
      mScramble = new int[mNumQuats][mNumCubits];
628
      mColors   = new int[mNumCubits];
629

    
630
      for(int q=0; q<mNumQuats; q++)
631
        for(int c=0; c<mNumCubits; c++) mScramble[q][c] = computeScramble(q,c);
632
      }
633

    
634
    if( mFaceMap==null )
635
      {
636
      mFaceMap = new int[] { 4, 2, 2, 4, 0, 2, 1, 4, 0, 0, 1, 1 };
637
      }
638

    
639
    for(int c=0; c<mNumCubits; c++)
640
      {
641
      int index = mScramble[mCubits[c].mQuatIndex][c];
642
      mColors[index] = mFaceMap[c];
643
      }
644

    
645
    if( mColors[0]==mColors[3] && mColors[0]==mColors[7] &&
646
        mColors[1]==mColors[2] && mColors[1]==mColors[5] &&
647
        mColors[4]==mColors[8] && mColors[4]==mColors[9]  ) return true;
648

    
649
    if( mColors[0]==mColors[1] && mColors[0]==mColors[4] &&
650
        mColors[2]==mColors[3] && mColors[2]==mColors[6] &&
651
        mColors[5]==mColors[9] && mColors[5]==mColors[10] ) return true;
652

    
653
    return false;
654
    }
655

    
656
///////////////////////////////////////////////////////////////////////////////////////////////////
657
// Dino6 uses this. It is solved if and only if:
658
//
659
// All four 'X' cubits (i.e. those whose longest edge goes along the X axis) are rotated
660
// by the same quaternion qX, similarly all four 'Y' cubits by the same qY and all four 'Z'
661
// by the same qZ, and then either:
662
//
663
// a) qX = qY = qZ
664
// b) qY = qX*Q2 and qZ = qX*Q8  (i.e. swap of WHITE and YELLOW faces)
665
// c) qX = qY*Q2 and qZ = qY*Q10 (i.e. swap of BLUE and GREEN faces)
666
// d) qX = qZ*Q8 and qY = qZ*Q10 (i.e. swap of RED and BROWN faces)
667
//
668
// BUT: cases b), c) and d) are really the same - it's all just a mirror image of the original.
669
//
670
// X cubits: 0, 2, 8, 10
671
// Y cubits: 1, 3, 9, 11
672
// Z cubits: 4, 5, 6, 7
673

    
674
  private boolean isSolved2()
675
    {
676
    int qX = mCubits[0].mQuatIndex;
677
    int qY = mCubits[1].mQuatIndex;
678
    int qZ = mCubits[4].mQuatIndex;
679

    
680
    if( mCubits[2].mQuatIndex != qX || mCubits[8].mQuatIndex != qX || mCubits[10].mQuatIndex != qX ||
681
        mCubits[3].mQuatIndex != qY || mCubits[9].mQuatIndex != qY || mCubits[11].mQuatIndex != qY ||
682
        mCubits[5].mQuatIndex != qZ || mCubits[6].mQuatIndex != qZ || mCubits[ 7].mQuatIndex != qZ  )
683
      {
684
      return false;
685
      }
686

    
687
    return ( qX==qY && qX==qZ ) || ( qY==mulQuat(qX,2) && qZ==mulQuat(qX,8) );
688
    }
689

    
690
///////////////////////////////////////////////////////////////////////////////////////////////////
691
// Square-2 is solved iff
692
// a) all of its cubits are rotated with the same quat
693
// b) its two 'middle' cubits are rotated with the same quat, the 6 'front' and 6 'back'
694
// edges and corners with this quat multiplied by QUATS[18] (i.e. those are upside down)
695
// and all the 12 left and right edges and corners also with the same quat multiplied by
696
// QUATS[12] - i.e. also upside down.
697

    
698
  private boolean isSolved3()
699
    {
700
    int index = mCubits[0].mQuatIndex;
701

    
702
    if( mCubits[1].mQuatIndex!=index ) return false;
703

    
704
    boolean solved = true;
705

    
706
    for(int i=2; i<mNumCubits; i++)
707
      {
708
      if( mCubits[i].mQuatIndex!=index )
709
        {
710
        solved = false;
711
        break;
712
        }
713
      }
714

    
715
    if( solved ) return true;
716

    
717
    int indexX = mulQuat(index,12);  // QUATS[12] = 180deg (1,0,0)
718
    int indexZ = mulQuat(index,18);  // QUATS[18] = 180deg (0,0,1)
719

    
720
    for(int i= 2; i<         18; i+=2) if( mCubits[i].mQuatIndex != indexZ ) return false;
721
    for(int i= 3; i<         18; i+=2) if( mCubits[i].mQuatIndex != indexX ) return false;
722
    for(int i=18; i< mNumCubits; i+=2) if( mCubits[i].mQuatIndex != indexX ) return false;
723
    for(int i=19; i< mNumCubits; i+=2) if( mCubits[i].mQuatIndex != indexZ ) return false;
724

    
725
    return true;
726
    }
727

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

    
730
  int computeRow(float[] pos, int axisIndex)
731
    {
732
    int ret=0;
733
    int len = pos.length / 3;
734
    Static3D axis = mAxis[axisIndex];
735
    float axisX = axis.get0();
736
    float axisY = axis.get1();
737
    float axisZ = axis.get2();
738
    float casted;
739

    
740
    for(int i=0; i<len; i++)
741
      {
742
      casted = pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ;
743
      ret |= computeSingleRow(axisIndex,casted);
744
      }
745

    
746
    return ret;
747
    }
748

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

    
751
  private int computeSingleRow(int axisIndex,float casted)
752
    {
753
    int num = mNumCuts[axisIndex];
754

    
755
    for(int i=0; i<num; i++)
756
      {
757
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
758
      }
759

    
760
    return (1<<num);
761
    }
762

    
763
///////////////////////////////////////////////////////////////////////////////////////////////////
764

    
765
  private boolean wasRotateApplied()
766
    {
767
    return mEffects.exists(mRotateEffect.getID());
768
    }
769

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

    
772
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
773
    {
774
    return (mCubits[cubit].getRotRow(axis) & rowBitmap) != 0;
775
    }
776

    
777
///////////////////////////////////////////////////////////////////////////////////////////////////
778
// note the minus in front of the sin() - we rotate counterclockwise
779
// when looking towards the direction where the axis increases in values.
780

    
781
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
782
    {
783
    Static3D axis = mAxis[axisIndex];
784

    
785
    while( angleInDegrees<0 ) angleInDegrees += 360;
786
    angleInDegrees %= 360;
787
    
788
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
789
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
790

    
791
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
792
    }
793

    
794
///////////////////////////////////////////////////////////////////////////////////////////////////
795

    
796
  private synchronized void setupPosition(int[][] moves)
797
    {
798
    if( moves!=null )
799
      {
800
      Static4D quat;
801
      int index, axis, rowBitmap, angle;
802
      int[] basic = getBasicAngle();
803

    
804
      for(int[] move: moves)
805
        {
806
        axis     = move[0];
807
        rowBitmap= move[1];
808
        angle    = move[2]*(360/basic[axis]);
809
        quat     = makeQuaternion(axis,angle);
810

    
811
        for(int j=0; j<mNumCubits; j++)
812
          if( belongsToRotation(j,axis,rowBitmap) )
813
            {
814
            index = mCubits[j].removeRotationNow(quat);
815
            mMesh.setEffectAssociation(j, mCubits[j].computeAssociation(),index);
816
            }
817
        }
818
      }
819
    }
820

    
821
///////////////////////////////////////////////////////////////////////////////////////////////////
822

    
823
  public int getScrambleType()
824
    {
825
    return 0;
826
    }
827

    
828
///////////////////////////////////////////////////////////////////////////////////////////////////
829

    
830
  int computeBitmapFromRow(int rowBitmap, int axis)
831
    {
832
    if( mIsBandaged )
833
      {
834
      int bitmap, initBitmap=0;
835

    
836
      while( initBitmap!=rowBitmap )
837
        {
838
        initBitmap = rowBitmap;
839

    
840
        for(int cubit=0; cubit<mNumCubits; cubit++)
841
          {
842
          bitmap = mCubits[cubit].getRotRow(axis);
843
          if( (rowBitmap & bitmap) != 0 ) rowBitmap |= bitmap;
844
          }
845
        }
846
      }
847

    
848
    return rowBitmap;
849
    }
850

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

    
855
  void clampPos(float[] pos, int offset)
856
    {
857
    float currError, minError = Float.MAX_VALUE;
858
    int minErrorIndex1 = -1;
859
    int minErrorIndex2 = -1;
860

    
861
    float x = pos[offset  ];
862
    float y = pos[offset+1];
863
    float z = pos[offset+2];
864

    
865
    float xo,yo,zo;
866

    
867
    for(int i=0; i<mNumCubits; i++)
868
      {
869
      int len = mOrigPos[i].length / 3;
870

    
871
      for(int j=0; j<len; j++)
872
        {
873
        xo = mOrigPos[i][3*j  ];
874
        yo = mOrigPos[i][3*j+1];
875
        zo = mOrigPos[i][3*j+2];
876

    
877
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
878

    
879
        if( currError<minError )
880
          {
881
          minError = currError;
882
          minErrorIndex1 = i;
883
          minErrorIndex2 = j;
884
          }
885
        }
886
      }
887

    
888
    if( minError< 0.1f ) // TODO: 0.1 ?
889
      {
890
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
891
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
892
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
893
      }
894
    }
895

    
896
///////////////////////////////////////////////////////////////////////////////////////////////////
897
// remember about the double cover or unit quaternions!
898

    
899
  int mulQuat(int q1, int q2)
900
    {
901
    Static4D result = QuatHelper.quatMultiply(mObjectQuats[q1],mObjectQuats[q2]);
902

    
903
    float rX = result.get0();
904
    float rY = result.get1();
905
    float rZ = result.get2();
906
    float rW = result.get3();
907

    
908
    final float MAX_ERROR = 0.1f;
909
    float dX,dY,dZ,dW;
910

    
911
    for(int i=0; i<mNumQuats; i++)
912
      {
913
      dX = mObjectQuats[i].get0() - rX;
914
      dY = mObjectQuats[i].get1() - rY;
915
      dZ = mObjectQuats[i].get2() - rZ;
916
      dW = mObjectQuats[i].get3() - rW;
917

    
918
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
919
          dY<MAX_ERROR && dY>-MAX_ERROR &&
920
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
921
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
922

    
923
      dX = mObjectQuats[i].get0() + rX;
924
      dY = mObjectQuats[i].get1() + rY;
925
      dZ = mObjectQuats[i].get2() + rZ;
926
      dW = mObjectQuats[i].get3() + rW;
927

    
928
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
929
          dY<MAX_ERROR && dY>-MAX_ERROR &&
930
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
931
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
932
      }
933

    
934
    return -1;
935
    }
936

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

    
939
  private float getAngle()
940
    {
941
    int pointNum = mRotationAngle.getNumPoints();
942

    
943
    if( pointNum>=1 )
944
      {
945
      return mRotationAngle.getPoint(pointNum-1).get0();
946
      }
947
    else
948
      {
949
      mInterface.reportProblem("points in RotationAngle: "+pointNum, false);
950
      return 0;
951
      }
952
    }
953

    
954
///////////////////////////////////////////////////////////////////////////////////////////////////
955

    
956
  void setLibInterface(ObjectLibInterface inter)
957
    {
958
    mInterface = inter;
959
    }
960

    
961
///////////////////////////////////////////////////////////////////////////////////////////////////
962

    
963
  void initializeObject(int[][] moves)
964
    {
965
    solve();
966
    setupPosition(moves);
967
    }
968

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

    
971
  synchronized void removeRotationNow()
972
    {
973
    float angle = getAngle();
974
    double nearestAngleInRadians = angle*Math.PI/180;
975
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
976
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
977
    float axisX = mAxis[mCurrentRotAxis].get0();
978
    float axisY = mAxis[mCurrentRotAxis].get1();
979
    float axisZ = mAxis[mCurrentRotAxis].get2();
980
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
981

    
982
    mRotationAngle.removeAll();
983
    mRotationAngleStatic.set0(0);
984

    
985
    for(int i=0; i<mNumCubits; i++)
986
      if( belongsToRotation(i, mCurrentRotAxis,mRotRowBitmap) )
987
        {
988
        int index = mCubits[i].removeRotationNow(quat);
989
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),index);
990
        }
991
    }
992

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

    
995
  long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
996
    {
997
    if( wasRotateApplied() )
998
      {
999
      float angle = getAngle();
1000
      mRotationAngleStatic.set0(angle);
1001
      mRotationAngleFinal.set0(nearestAngleInDegrees);
1002
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
1003

    
1004
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
1005
      mRotationAngle.resetToBeginning();
1006
      mRotationAngle.removeAll();
1007
      mRotationAngle.add(mRotationAngleStatic);
1008
      mRotationAngle.add(mRotationAngleMiddle);
1009
      mRotationAngle.add(mRotationAngleFinal);
1010
      mRotateEffect.notifyWhenFinished(listener);
1011

    
1012
      return mRotateEffect.getID();
1013
      }
1014

    
1015
    return 0;
1016
    }
1017

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

    
1020
  synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
1021
    {
1022
    if( wasRotateApplied() )
1023
      {
1024
      mCurrentRotAxis = axis;
1025
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
1026

    
1027
      mRotationAngleStatic.set0(0.0f);
1028
      mRotationAxis.set( mAxis[axis] );
1029
      mRotationAngle.setDuration(durationMillis);
1030
      mRotationAngle.resetToBeginning();
1031
      mRotationAngle.add(new Static1D(0));
1032
      mRotationAngle.add(new Static1D(angle));
1033
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1034
      mRotateEffect.notifyWhenFinished(listener);
1035

    
1036
      return mRotateEffect.getID();
1037
      }
1038

    
1039
    return 0;
1040
    }
1041

    
1042
///////////////////////////////////////////////////////////////////////////////////////////////////
1043

    
1044
  void continueRotation(float angleInDegrees)
1045
    {
1046
    mRotationAngleStatic.set0(angleInDegrees);
1047
    }
1048

    
1049
///////////////////////////////////////////////////////////////////////////////////////////////////
1050

    
1051
  synchronized void beginNewRotation(int axis, int row )
1052
    {
1053
    if( axis<0 || axis>=mNumAxis )
1054
      {
1055
      android.util.Log.e("object", "invalid rotation axis: "+axis);
1056
      return;
1057
      }
1058
    if( row<0 || row>=mNumLayers[axis] )
1059
      {
1060
      android.util.Log.e("object", "invalid rotation row: "+row);
1061
      return;
1062
      }
1063

    
1064
    mCurrentRotAxis = axis;
1065
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
1066
    mRotationAngleStatic.set0(0.0f);
1067
    mRotationAxis.set( mAxis[axis] );
1068
    mRotationAngle.add(mRotationAngleStatic);
1069
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1070
    }
1071

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

    
1074
  void setTextureMap(int cubit, int face, int newColor)
1075
    {
1076
    final float ratioW = 1.0f/mNumTexCols;
1077
    final float ratioH = 1.0f/mNumTexRows;
1078
    final Static4D[] maps = new Static4D[mNumCubitFaces];
1079
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
1080
    int col = newColor%mNumTexCols;
1081

    
1082
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1083
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1084
    }
1085

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

    
1088
  public int getCubitFaceColor(int cubit, int face)
1089
    {
1090
    int numFaces = mCubitFaceColors[cubit].length;
1091
    int color = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
1092

    
1093
    return color<0 ? -1 : color%mNumFaceColors;
1094
    }
1095

    
1096
///////////////////////////////////////////////////////////////////////////////////////////////////
1097

    
1098
  void resetAllTextureMaps()
1099
    {
1100
    final float ratioW = 1.0f/mNumTexCols;
1101
    final float ratioH = 1.0f/mNumTexRows;
1102
    int cubColor, varColor, color, variant, row, col;
1103

    
1104
    for(int cubit=0; cubit<mNumCubits; cubit++)
1105
      {
1106
      final Static4D[] maps = new Static4D[mNumCubitFaces];
1107
      variant = getCubitVariant(cubit,mNumLayers);
1108

    
1109
      for(int face=0; face<mNumCubitFaces; face++)
1110
        {
1111
        cubColor = getCubitFaceColor(cubit,face);
1112
        varColor = getVariantFaceColor(variant,face);
1113
        color    = cubColor<0 || varColor<0 ? mNumTextures : varColor*mNumFaceColors + cubColor;
1114
        row      = (mNumTexRows-1) - color/mNumTexCols;
1115
        col      = color%mNumTexCols;
1116

    
1117
        maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1118
        }
1119

    
1120
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1121
      }
1122
    }
1123

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

    
1126
  void releaseResources()
1127
    {
1128
    mTexture.markForDeletion();
1129
    mMesh.markForDeletion();
1130
    mEffects.markForDeletion();
1131

    
1132
    for(int j=0; j<mNumCubits; j++)
1133
      {
1134
      mCubits[j].releaseResources();
1135
      }
1136
    }
1137

    
1138
///////////////////////////////////////////////////////////////////////////////////////////////////
1139

    
1140
  synchronized void restorePreferences(SharedPreferences preferences)
1141
    {
1142
    boolean error = false;
1143

    
1144
    for(int i=0; i<mNumCubits; i++)
1145
      {
1146
      mQuatDebug[i] = mCubits[i].restorePreferences(preferences);
1147

    
1148
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<mNumQuats )
1149
        {
1150
        mCubits[i].modifyCurrentPosition(mObjectQuats[mQuatDebug[i]]);
1151
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),mQuatDebug[i]);
1152
        }
1153
      else
1154
        {
1155
        error = true;
1156
        }
1157
      }
1158

    
1159
    if( error )
1160
      {
1161
      for(int i=0; i<mNumCubits; i++)
1162
        {
1163
        mCubits[i].solve();
1164
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),0);
1165
        }
1166
      }
1167
    }
1168

    
1169
///////////////////////////////////////////////////////////////////////////////////////////////////
1170

    
1171
  void savePreferences(SharedPreferences.Editor editor)
1172
    {
1173
    for(int i=0; i<mNumCubits; i++) mCubits[i].savePreferences(editor);
1174
    }
1175

    
1176
///////////////////////////////////////////////////////////////////////////////////////////////////
1177

    
1178
  private float computeRadiusCorrection(float[] sticker, int curr, int len)
1179
    {
1180
    final float A = 0.8f;  // 0<A<1
1181

    
1182
    int prev = curr>0 ? curr-1 : len-1;
1183
    int next = curr<len-1 ? curr+1 : 0;
1184

    
1185
    float v1x = sticker[2*prev  ]-sticker[2*curr  ];
1186
    float v1y = sticker[2*prev+1]-sticker[2*curr+1];
1187
    float v2x = sticker[2*next  ]-sticker[2*curr  ];
1188
    float v2y = sticker[2*next+1]-sticker[2*curr+1];
1189

    
1190
    float len1= v1x*v1x+v1y*v1y;
1191
    float len2= v2x*v2x+v2y*v2y;
1192

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

    
1195
    return 1-A*cos;
1196
    }
1197

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

    
1200
  public ObjectSticker retSticker(int sticker)
1201
    {
1202
    if( mStickers==null )
1203
      {
1204
      float rad = getStickerRadius();
1205
      float str = getStickerStroke();
1206
      float[][] angles = getStickerAngles();
1207
      int numStickers = mStickerCoords.length;
1208
      mStickers = new ObjectSticker[numStickers];
1209

    
1210
      for(int s=0; s<numStickers; s++)
1211
        {
1212
        float scale = mStickerScales[s];
1213
        float radius = rad / scale;
1214
        float stroke = str / scale;
1215
        int len = mStickerCoords[s].length/2;
1216
        float[] radii = new float[len];
1217
        for(int r=0; r<len; r++) radii[r] = radius*computeRadiusCorrection(mStickerCoords[s],r,len);
1218
        mStickers[s] = new ObjectSticker(mStickerCoords[s],angles==null ? null : angles[s],radii,stroke);
1219
        }
1220
      }
1221

    
1222
    return mStickers[sticker];
1223
    }
1224

    
1225
///////////////////////////////////////////////////////////////////////////////////////////////////
1226
// some objects (currently Kilominx,Ivy,Rex) might want to change the stickers.
1227

    
1228
  public void adjustStickerCoords()
1229
    {
1230

    
1231
    }
1232

    
1233
///////////////////////////////////////////////////////////////////////////////////////////////////
1234
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
1235

    
1236
  private void createTexture()
1237
    {
1238
    Paint paint = new Paint();
1239
    mBitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_4444);
1240
    Canvas canvas = new Canvas(mBitmap);
1241

    
1242
    paint.setAntiAlias(true);
1243
    paint.setTextAlign(Paint.Align.CENTER);
1244
    paint.setStyle(Paint.Style.FILL);
1245

    
1246
    paint.setColor(COLOR_INTERNAL);
1247
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
1248

    
1249
    int texture = 0;
1250
    FactorySticker factory = FactorySticker.getInstance();
1251

    
1252
    for(int row=0; row<mNumTexRows; row++)
1253
      for(int col=0; col<mNumTexCols; col++)
1254
        {
1255
        if( texture>=mNumTextures ) break;
1256
        ObjectSticker sticker = retSticker(texture/mNumFaceColors);
1257
        int color = getColor(texture% mNumFaceColors);
1258
        factory.drawRoundedPolygon(canvas, paint, col*TEXTURE_HEIGHT, row*TEXTURE_HEIGHT, color, sticker);
1259
        texture++;
1260
        }
1261
    }
1262

    
1263
///////////////////////////////////////////////////////////////////////////////////////////////////
1264

    
1265
  void setTexture()
1266
    {
1267
    if( mBitmap==null ) createTexture();
1268

    
1269
    if( !mTexture.setTexture(mBitmap) )
1270
      {
1271
      int max = DistortedLibrary.getMaxTextureSize();
1272
      mInterface.reportProblem("failed to set texture of size "+mBitmap.getWidth()+"x"+mBitmap.getHeight()+" max is "+max, true);
1273
      }
1274
    }
1275

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

    
1278
  void setObjectRatioNow(float sc, int nodeSize)
1279
    {
1280
    mObjectScreenRatio = sc;
1281
    float scale = mObjectScreenRatio*mInitScreenRatio*nodeSize/mSize;
1282
    mObjectScale.set(scale,scale,scale);
1283

    
1284
    if( mTouchControl ==null ) mTouchControl = getTouchControl();
1285
    mTouchControl.setObjectRatio(mObjectScreenRatio*mInitScreenRatio);
1286
    }
1287

    
1288
///////////////////////////////////////////////////////////////////////////////////////////////////
1289

    
1290
  void setObjectRatio(float sizeChange, int nodeSize)
1291
    {
1292
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
1293

    
1294
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
1295
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
1296

    
1297
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1298
    }
1299

    
1300
///////////////////////////////////////////////////////////////////////////////////////////////////
1301

    
1302
  void setNodeSize(int nodeSize)
1303
    {
1304
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1305
    }
1306

    
1307
///////////////////////////////////////////////////////////////////////////////////////////////////
1308

    
1309
  public float getRatio()
1310
    {
1311
    return mObjectScreenRatio;
1312
    }
1313

    
1314
///////////////////////////////////////////////////////////////////////////////////////////////////
1315

    
1316
  public float getObjectRatio()
1317
    {
1318
    return mObjectScreenRatio*mInitScreenRatio;
1319
    }
1320

    
1321
///////////////////////////////////////////////////////////////////////////////////////////////////
1322

    
1323
  boolean isSolved()
1324
    {
1325
    if( mSolvedFunctionIndex==0 ) return isSolved0();
1326
    if( mSolvedFunctionIndex==1 ) return isSolved1();
1327
    if( mSolvedFunctionIndex==2 ) return isSolved2();
1328
    if( mSolvedFunctionIndex==3 ) return isSolved3();
1329

    
1330
    return false;
1331
    }
1332

    
1333
///////////////////////////////////////////////////////////////////////////////////////////////////
1334

    
1335
  int computeNearestAngle(int axis, float angle, float speed)
1336
    {
1337
    int[] basicArray = getBasicAngle();
1338
    int basicAngle   = basicArray[axis>=basicArray.length ? 0 : axis];
1339
    int nearestAngle = 360/basicAngle;
1340

    
1341
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
1342
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
1343

    
1344
    if( tmp!=0 ) return nearestAngle*tmp;
1345

    
1346
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
1347
    }
1348

    
1349
///////////////////////////////////////////////////////////////////////////////////////////////////
1350
// INTERNAL API - those are called from 'effects' package
1351
///////////////////////////////////////////////////////////////////////////////////////////////////
1352

    
1353
  public void randomizeNewScramble(int[][] scramble, Random rnd, int curr, int total)
1354
    {
1355
    mScrambler.randomizeNewScramble(scramble,rnd,curr,total);
1356
    }
1357

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

    
1360
  public Static4D getRotationQuat()
1361
    {
1362
    return mQuat;
1363
    }
1364

    
1365
///////////////////////////////////////////////////////////////////////////////////////////////////
1366

    
1367
  public float getSize()
1368
    {
1369
    return mSize;
1370
    }
1371

    
1372
///////////////////////////////////////////////////////////////////////////////////////////////////
1373

    
1374
  public void apply(Effect effect, int position)
1375
    {
1376
    mEffects.apply(effect, position);
1377
    }
1378

    
1379
///////////////////////////////////////////////////////////////////////////////////////////////////
1380

    
1381
  public void remove(long effectID)
1382
    {
1383
    mEffects.abortById(effectID);
1384
    }
1385

    
1386
///////////////////////////////////////////////////////////////////////////////////////////////////
1387

    
1388
  public MeshBase getObjectMesh()
1389
    {
1390
    return mMesh;
1391
    }
1392

    
1393
///////////////////////////////////////////////////////////////////////////////////////////////////
1394

    
1395
  public DistortedEffects getObjectEffects()
1396
    {
1397
    return mEffects;
1398
    }
1399

    
1400
///////////////////////////////////////////////////////////////////////////////////////////////////
1401
// PUBLIC API
1402
///////////////////////////////////////////////////////////////////////////////////////////////////
1403

    
1404
  public int getCubitFaceColorIndex(int cubit, int face)
1405
    {
1406
    Static4D texMap = mMesh.getTextureMap(mNumFaceColors *cubit + face);
1407

    
1408
    int x = (int)(texMap.get0()/texMap.get2());
1409
    int y = (int)(texMap.get1()/texMap.get3());
1410

    
1411
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
1412
    }
1413

    
1414
///////////////////////////////////////////////////////////////////////////////////////////////////
1415

    
1416
  public int[] getNumLayers()
1417
    {
1418
    return mNumLayers;
1419
    }
1420

    
1421
///////////////////////////////////////////////////////////////////////////////////////////////////
1422

    
1423
  public synchronized void solve()
1424
    {
1425
    for(int i=0; i<mNumCubits; i++)
1426
      {
1427
      mCubits[i].solve();
1428
      mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(), 0);
1429
      }
1430
    }
1431

    
1432
///////////////////////////////////////////////////////////////////////////////////////////////////
1433

    
1434
  public int getCubitQuatIndex(int cubit)
1435
    {
1436
    return mCubits[cubit].mQuatIndex;
1437
    }
1438

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

    
1441
  public int getCubitRotRow(int cubit, int axis)
1442
    {
1443
    return mCubits[cubit].getRotRow(axis);
1444
    }
1445

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

    
1448
  public Bitmap getStickerBitmap()
1449
    {
1450
    return mBitmap;
1451
    }
1452

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

    
1455
  public DistortedNode getNode()
1456
    {
1457
    return mNode;
1458
    }
1459

    
1460
///////////////////////////////////////////////////////////////////////////////////////////////////
1461

    
1462
  public ObjectType getObjectType()
1463
    {
1464
    return intGetObjectType(mNumLayers);
1465
    }
1466

    
1467
///////////////////////////////////////////////////////////////////////////////////////////////////
1468

    
1469
  public int getNumStickerTypes()
1470
    {
1471
    return mNumStickerTypes;
1472
    }
1473

    
1474
///////////////////////////////////////////////////////////////////////////////////////////////////
1475
// this is here only so it can be overridden in TwistyJSON soo that we can get this from JSON.
1476

    
1477
  public int getNumCubitFaces()
1478
    {
1479
    return 0;
1480
    }
1481

    
1482
///////////////////////////////////////////////////////////////////////////////////////////////////
1483

    
1484
  public TouchControl getTouchControl()
1485
    {
1486
    if( mTouchControl==null )
1487
      {
1488
      switch(getTouchControlType())
1489
        {
1490
        case TC_TETRAHEDRON    : mTouchControl = new TouchControlTetrahedron(this);
1491
                                 break;
1492
        case TC_HEXAHEDRON     : mTouchControl = new TouchControlHexahedron(this);
1493
                                 break;
1494
        case TC_OCTAHEDRON     : mTouchControl = new TouchControlOctahedron(this);
1495
                                 break;
1496
        case TC_DODECAHEDRON   : mTouchControl = new TouchControlDodecahedron(this);
1497
                                 break;
1498
        case TC_CUBOID         : int[] numLayers = getNumLayers();
1499
                                 mTouchControl = new TouchControlCuboids(this,getDist3D(numLayers));
1500
                                 break;
1501
        case TC_CHANGING_MIRROR: mTouchControl = new TouchControlMirror(this);
1502
                                 break;
1503
        case TC_CHANGING_SQUARE: mTouchControl = new TouchControlSquare(this);
1504
                                 break;
1505
        }
1506
      }
1507
    return mTouchControl;
1508
    }
1509

    
1510
///////////////////////////////////////////////////////////////////////////////////////////////////
1511

    
1512
  public String getShortName()
1513
    {
1514
    return getObjectType().name();
1515
    }
1516

    
1517
///////////////////////////////////////////////////////////////////////////////////////////////////
1518

    
1519
  protected void setReader(JsonReader reader)
1520
    {
1521
    // empty
1522
    }
1523

    
1524
///////////////////////////////////////////////////////////////////////////////////////////////////
1525

    
1526
  protected abstract ObjectType intGetObjectType(int[] numLayers);
1527

    
1528
  // for JSON only
1529
  public abstract int getSolvedFunctionIndex();
1530
  public abstract int getTouchControlType();
1531
  public abstract int getTouchControlSplit();
1532
  public abstract boolean[][] getLayerRotatable(int[] numLayers);
1533
  public abstract int[][][] getEnabled();
1534
  public abstract float[] getDist3D(int[] numLayers);
1535
  public abstract Static3D[] getFaceAxis();
1536
  public abstract ScrambleState[] getScrambleStates();
1537
  public abstract float[][] getCuts(int[] numLayers);
1538
  public abstract Static4D[] getQuats();
1539
  public abstract float getStickerRadius();
1540
  public abstract float getStickerStroke();
1541
  public abstract float[][] getStickerAngles();
1542
  public abstract int getCubitVariant(int cubit, int[] numLayers);
1543
  public abstract ObjectShape getObjectShape(int variant);
1544
  public abstract ObjectFaceShape getObjectFaceShape(int variant);
1545
  public abstract int getNumCubitVariants(int[] numLayers);
1546
  public abstract float[][] getCubitPositions(int[] numLayers);
1547
  public abstract Static4D getCubitQuats(int cubit, int[] numLayers);
1548
  public abstract int[] getSolvedQuats(int cubit, int[] numLayers);
1549
  public abstract int getNumFaceColors();
1550
  public abstract float getScreenRatio();
1551
  public abstract int getColor(int face);
1552

    
1553
  // not only for JSON
1554
  public abstract Static3D[] getRotationAxis();
1555
  public abstract int[] getBasicAngle();
1556
  public abstract int getNumFaces();
1557
  public abstract String getObjectName();
1558
  public abstract String getInventor();
1559
  public abstract int getYearOfInvention();
1560
  public abstract int getComplexity();
1561
  public abstract int getFOV();
1562
  }
(11-11/13)