Project

General

Profile

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

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

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
  private int[][] mVariantFaceIsOuter;
147

    
148
  //////////////////// SOLVED1 ////////////////////////
149

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

    
154
///////////////////////////////////////////////////////////////////////////////////////////////////
155

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

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

    
167
///////////////////////////////////////////////////////////////////////////////////////////////////
168

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

    
176
///////////////////////////////////////////////////////////////////////////////////////////////////
177

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

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

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

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

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

    
207
    boolean bandaged=false;
208

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

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

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

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

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

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

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

    
242
    mEffects = new DistortedEffects();
243

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

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

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

    
259
///////////////////////////////////////////////////////////////////////////////////////////////////
260

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

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

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

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

    
282
///////////////////////////////////////////////////////////////////////////////////////////////////
283

    
284
  private void createOuterFaces()
285
    {
286
    for(int v=0; v<mNumCubitVariants; v++)
287
      {
288
      int[][] indices = mShapes[v].getVertIndices();
289
      int faces = indices.length;
290
      mVariantFaceIsOuter[v] = new int[faces];
291
      }
292

    
293
    for(int cubit=0; cubit<NUM_CUBITS; cubit++)
294
      {
295
      int variant = getCubitVariant(cubit,mNumLayers);
296
      int[][] indices = mShapes[variant].getVertIndices();
297
      int numFaces = indices.length;
298

    
299
      for(int face=0; face<numFaces; face++)
300
        if( getCubitFaceColor(cubit,face)>=0 )
301
          {
302
          mVariantFaceIsOuter[variant][face] = 1;
303
          }
304
      }
305
    }
306

    
307
///////////////////////////////////////////////////////////////////////////////////////////////////
308

    
309
  private void getQuatsAndShapes(boolean fromDMESH, boolean fromJSON)
310
    {
311
    mNumCubitVariants = getNumCubitVariants(mNumLayers);
312

    
313
    if( !fromDMESH || !fromJSON )
314
      {
315
      FactoryCubit factory = FactoryCubit.getInstance();
316
      factory.clear();
317

    
318
      mOrigQuat = new Static4D[NUM_CUBITS];
319
      for(int i=0; i<NUM_CUBITS; i++) mOrigQuat[i] = getCubitQuats(i,mNumLayers);
320

    
321
      mShapes = new ObjectShape[mNumCubitVariants];
322
      for(int i=0; i<mNumCubitVariants; i++) mShapes[i] = getObjectShape(i);
323
      mNumCubitFaces = ObjectShape.computeNumComponents(mShapes);
324
      mVariantFaceIsOuter = new int[mNumCubitVariants][];
325

    
326
      if( !fromJSON )
327
        {
328
        mCubitFaceColors = ObjectShape.computeColors(mShapes,mOrigPos,mOrigQuat,this);
329
        createOuterFaces();
330
        }
331

    
332
      if( fromDMESH )
333
        {
334
        for(int i=0; i<mNumCubitVariants; i++) factory.createNewFaceTransform(mShapes[i], mVariantFaceIsOuter[i]);
335
        }
336
      }
337
    }
338

    
339
///////////////////////////////////////////////////////////////////////////////////////////////////
340

    
341
  private void createMeshAndCubits(InputStream stream, int meshState, boolean fromDMESH)
342
    {
343
    CUBITS = new Cubit[NUM_CUBITS];
344

    
345
    if( fromDMESH )
346
      {
347
      DataInputStream dos = new DataInputStream(stream);
348
      mMesh = new MeshFile(dos);
349

    
350
      try
351
        {
352
        stream.close();
353
        }
354
      catch(IOException e)
355
        {
356
        android.util.Log.e("meshFile", "Error closing InputStream: "+e.toString());
357
        }
358

    
359
      for(int i=0; i<NUM_CUBITS; i++)
360
        {
361
        CUBITS[i] = new Cubit(this,mOrigPos[i], NUM_AXIS);
362
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
363
        }
364
      }
365
    else
366
      {
367
      MeshBase[] cubitMesh = new MeshBase[NUM_CUBITS];
368

    
369
      for(int i=0; i<NUM_CUBITS; i++)
370
        {
371
        CUBITS[i] = new Cubit(this,mOrigPos[i], NUM_AXIS);
372
        cubitMesh[i] = createCubitMesh(i,mNumLayers,meshState,mNumCubitFaces);
373
        Static3D pos = getPos(mOrigPos[i]);
374
        cubitMesh[i].apply(new MatrixEffectMove(pos),1,0);
375
        cubitMesh[i].setEffectAssociation(0, CUBITS[i].computeAssociation(), 0);
376
        }
377

    
378
      mMesh = new MeshJoined(cubitMesh);
379
      }
380
    }
381

    
382
///////////////////////////////////////////////////////////////////////////////////////////////////
383

    
384
  private MeshBase createCubitMesh(int cubit, int[] numLayers, int meshState, int numComponents)
385
    {
386
    int variant = getCubitVariant(cubit,numLayers);
387

    
388
    if( mMeshes==null ) mMeshes = new MeshBase[mNumCubitVariants];
389

    
390
    if( mMeshes[variant]==null )
391
      {
392
      ObjectFaceShape faceShape = getObjectFaceShape(variant);
393
      FactoryCubit factory = FactoryCubit.getInstance();
394
      factory.createNewFaceTransform(mShapes[variant],mVariantFaceIsOuter[variant]);
395
      mMeshes[variant] = factory.createRoundedSolid(mShapes[variant],faceShape,meshState, numComponents);
396
      }
397

    
398
    MeshBase mesh = mMeshes[variant].copy(true);
399
    MatrixEffectQuaternion quat = new MatrixEffectQuaternion( mOrigQuat[cubit], CENTER );
400
    mesh.apply(quat,0xffffffff,0);
401

    
402
    return mesh;
403
    }
404

    
405
///////////////////////////////////////////////////////////////////////////////////////////////////
406

    
407
  private void setUpTextures(boolean fromDMESH, boolean fromJSON)
408
    {
409
    mTexture = new DistortedTexture();
410

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

    
426
    NUM_TEXTURES = NUM_FACE_COLORS*mNumStickerTypes;
427
    mNumTexCols = NUM_STICKERS_IN_ROW;
428
    mNumTexRows = (NUM_TEXTURES+1)/NUM_STICKERS_IN_ROW;
429
    if( mNumTexCols*mNumTexRows < NUM_TEXTURES+1 ) mNumTexRows++;
430

    
431
    if( !fromDMESH || shouldResetTextureMaps() ) resetAllTextureMaps();
432
    setTexture();
433
    }
434

    
435
///////////////////////////////////////////////////////////////////////////////////////////////////
436

    
437
  private void createDataStructuresForSolved(int[] numLayers)
438
    {
439
    mTmpQuats = new int[NUM_QUATS];
440
    mSolvedQuats = new int[NUM_CUBITS][];
441

    
442
    for(int c=0; c<NUM_CUBITS; c++)
443
      {
444
      mSolvedQuats[c] = getSolvedQuats(c,numLayers);
445
      }
446
    }
447

    
448
///////////////////////////////////////////////////////////////////////////////////////////////////
449

    
450
  private int getMultQuat(int index1, int index2)
451
    {
452
    if( mQuatMult==null )
453
      {
454
      mQuatMult = new int[NUM_QUATS][NUM_QUATS];
455

    
456
      for(int i=0; i<NUM_QUATS; i++)
457
        for(int j=0; j<NUM_QUATS; j++) mQuatMult[i][j] = -1;
458
      }
459

    
460
    if( mQuatMult[index1][index2]==-1 )
461
      {
462
      mQuatMult[index1][index2] = mulQuat(index1,index2);
463
      }
464

    
465
    return mQuatMult[index1][index2];
466
    }
467

    
468
///////////////////////////////////////////////////////////////////////////////////////////////////
469

    
470
  public int getVariantFaceColor(int variant, int face)
471
    {
472
    return face>=mStickerVariants[variant].length ? -1 : mStickerVariants[variant][face];
473
    }
474

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

    
483
  protected int retCubitSolvedStatus(int cubit, int[] numLayers)
484
    {
485
    int numNonBlack=0, nonBlackIndex=-1, varColor, cubColor;
486
    int variant = getCubitVariant(cubit,numLayers);
487

    
488
    for(int face=0; face<mNumCubitFaces; face++)
489
      {
490
      varColor = getVariantFaceColor(variant,face);
491
      cubColor = getCubitFaceColor(cubit,face);
492

    
493
      if( varColor>=0 && cubColor>=0 )
494
        {
495
        numNonBlack++;
496
        nonBlackIndex = cubColor;
497
        }
498
      }
499

    
500
    if( numNonBlack==0 ) return -1;
501
    if( numNonBlack>=2 ) return -2;
502

    
503
    return nonBlackIndex;
504
    }
505

    
506
///////////////////////////////////////////////////////////////////////////////////////////////////
507

    
508
  public boolean shouldResetTextureMaps()
509
    {
510
    return false;
511
    }
512

    
513
///////////////////////////////////////////////////////////////////////////////////////////////////
514

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

    
524
    int len = quats.length;
525
    int place = 0;
526

    
527
    for(int q=1; q<len; q++)
528
      {
529
      quat = quats[q];
530
      qx = quat.get0();
531
      qy = quat.get1();
532
      qz = quat.get2();
533

    
534
           if( x!=0.0f ) { a = qx/x; }
535
      else if( y!=0.0f ) { a = qy/y; }
536
      else               { a = qz/z; }
537

    
538
      dx = a*x-qx;
539
      dy = a*y-qy;
540
      dz = a*z-qz;
541

    
542
      if( dx>-MAXD && dx<MAXD && dy>-MAXD && dy<MAXD && dz>-MAXD && dz<MAXD )
543
        {
544
        mTmpQuats[place++] = q;
545
        }
546
      }
547

    
548
    if( place!=0 )
549
      {
550
      int[] ret = new int[place];
551
      System.arraycopy(mTmpQuats,0,ret,0,place);
552
      return ret;
553
      }
554

    
555
    return null;
556
    }
557

    
558
///////////////////////////////////////////////////////////////////////////////////////////////////
559

    
560
  private boolean isSolved0()
561
    {
562
    int len, q1,q = CUBITS[0].mQuatIndex;
563
    int[] solved;
564
    boolean skip;
565

    
566
    for(int c=1; c<NUM_CUBITS; c++)
567
      {
568
      q1 = CUBITS[c].mQuatIndex;
569

    
570
      if( q1==q ) continue;
571

    
572
      skip = false;
573
      solved = mSolvedQuats[c];
574
      len = solved==null ? 0:solved.length;
575

    
576
      for(int i=0; i<len; i++)
577
        {
578
        if( q1==getMultQuat(q,solved[i]) )
579
          {
580
          skip = true;
581
          break;
582
          }
583
        }
584

    
585
      if( !skip ) return false;
586
      }
587

    
588
    return true;
589
    }
590

    
591
///////////////////////////////////////////////////////////////////////////////////////////////////
592

    
593
  private int computeScramble(int quatNum, int centerNum)
594
    {
595
    float MAXDIFF = 0.01f;
596
    float[] center= mOrigPos[centerNum];
597
    Static4D sc = new Static4D(center[0], center[1], center[2], 1.0f);
598
    Static4D result = QuatHelper.rotateVectorByQuat(sc,OBJECT_QUATS[quatNum]);
599

    
600
    float x = result.get0();
601
    float y = result.get1();
602
    float z = result.get2();
603

    
604
    for(int c=0; c<NUM_CUBITS; c++)
605
      {
606
      float[] cent = mOrigPos[c];
607

    
608
      float qx = cent[0] - x;
609
      float qy = cent[1] - y;
610
      float qz = cent[2] - z;
611

    
612
      if( qx>-MAXDIFF && qx<MAXDIFF &&
613
          qy>-MAXDIFF && qy<MAXDIFF &&
614
          qz>-MAXDIFF && qz<MAXDIFF  ) return c;
615
      }
616

    
617
    return -1;
618
    }
619

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

    
627
  private boolean isSolved1()
628
    {
629
    if( mScramble==null )
630
      {
631
      mScramble = new int[NUM_QUATS][NUM_CUBITS];
632
      mColors   = new int[NUM_CUBITS];
633

    
634
      for(int q=0; q<NUM_QUATS; q++)
635
        for(int c=0; c<NUM_CUBITS; c++) mScramble[q][c] = computeScramble(q,c);
636
      }
637

    
638
    if( mFaceMap==null )
639
      {
640
      mFaceMap = new int[] { 4, 2, 2, 4, 0, 2, 1, 4, 0, 0, 1, 1 };
641
      }
642

    
643
    for(int c=0; c<NUM_CUBITS; c++)
644
      {
645
      int index = mScramble[CUBITS[c].mQuatIndex][c];
646
      mColors[index] = mFaceMap[c];
647
      }
648

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

    
653
    if( mColors[0]==mColors[1] && mColors[0]==mColors[4] &&
654
        mColors[2]==mColors[3] && mColors[2]==mColors[6] &&
655
        mColors[5]==mColors[9] && mColors[5]==mColors[10] ) return true;
656

    
657
    return false;
658
    }
659

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

    
678
  private boolean isSolved2()
679
    {
680
    int qX = CUBITS[0].mQuatIndex;
681
    int qY = CUBITS[1].mQuatIndex;
682
    int qZ = CUBITS[4].mQuatIndex;
683

    
684
    if( CUBITS[2].mQuatIndex != qX || CUBITS[8].mQuatIndex != qX || CUBITS[10].mQuatIndex != qX ||
685
        CUBITS[3].mQuatIndex != qY || CUBITS[9].mQuatIndex != qY || CUBITS[11].mQuatIndex != qY ||
686
        CUBITS[5].mQuatIndex != qZ || CUBITS[6].mQuatIndex != qZ || CUBITS[ 7].mQuatIndex != qZ  )
687
      {
688
      return false;
689
      }
690

    
691
    return ( qX==qY && qX==qZ ) || ( qY==mulQuat(qX,2) && qZ==mulQuat(qX,8) );
692
    }
693

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

    
702
  private boolean isSolved3()
703
    {
704
    int index = CUBITS[0].mQuatIndex;
705

    
706
    if( CUBITS[1].mQuatIndex!=index ) return false;
707

    
708
    boolean solved = true;
709

    
710
    for(int i=2; i<NUM_CUBITS; i++)
711
      {
712
      if( CUBITS[i].mQuatIndex!=index )
713
        {
714
        solved = false;
715
        break;
716
        }
717
      }
718

    
719
    if( solved ) return true;
720

    
721
    int indexX = mulQuat(index,12);  // QUATS[12] = 180deg (1,0,0)
722
    int indexZ = mulQuat(index,18);  // QUATS[18] = 180deg (0,0,1)
723

    
724
    for(int i= 2; i<        18; i+=2) if( CUBITS[i].mQuatIndex != indexZ ) return false;
725
    for(int i= 3; i<        18; i+=2) if( CUBITS[i].mQuatIndex != indexX ) return false;
726
    for(int i=18; i<NUM_CUBITS; i+=2) if( CUBITS[i].mQuatIndex != indexX ) return false;
727
    for(int i=19; i<NUM_CUBITS; i+=2) if( CUBITS[i].mQuatIndex != indexZ ) return false;
728

    
729
    return true;
730
    }
731

    
732
///////////////////////////////////////////////////////////////////////////////////////////////////
733

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

    
744
    for(int i=0; i<len; i++)
745
      {
746
      casted = pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ;
747
      ret |= computeSingleRow(axisIndex,casted);
748
      }
749

    
750
    return ret;
751
    }
752

    
753
///////////////////////////////////////////////////////////////////////////////////////////////////
754

    
755
  private int computeSingleRow(int axisIndex,float casted)
756
    {
757
    int num = mNumCuts[axisIndex];
758

    
759
    for(int i=0; i<num; i++)
760
      {
761
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
762
      }
763

    
764
    return (1<<num);
765
    }
766

    
767
///////////////////////////////////////////////////////////////////////////////////////////////////
768

    
769
  private boolean wasRotateApplied()
770
    {
771
    return mEffects.exists(mRotateEffect.getID());
772
    }
773

    
774
///////////////////////////////////////////////////////////////////////////////////////////////////
775

    
776
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
777
    {
778
    return (CUBITS[cubit].getRotRow(axis) & rowBitmap) != 0;
779
    }
780

    
781
///////////////////////////////////////////////////////////////////////////////////////////////////
782
// note the minus in front of the sin() - we rotate counterclockwise
783
// when looking towards the direction where the axis increases in values.
784

    
785
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
786
    {
787
    Static3D axis = mAxis[axisIndex];
788

    
789
    while( angleInDegrees<0 ) angleInDegrees += 360;
790
    angleInDegrees %= 360;
791
    
792
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
793
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
794

    
795
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
796
    }
797

    
798
///////////////////////////////////////////////////////////////////////////////////////////////////
799

    
800
  private synchronized void setupPosition(int[][] moves)
801
    {
802
    if( moves!=null )
803
      {
804
      Static4D quat;
805
      int index, axis, rowBitmap, angle;
806
      int[] basic = getBasicAngle();
807

    
808
      for(int[] move: moves)
809
        {
810
        axis     = move[0];
811
        rowBitmap= move[1];
812
        angle    = move[2]*(360/basic[axis]);
813
        quat     = makeQuaternion(axis,angle);
814

    
815
        for(int j=0; j<NUM_CUBITS; j++)
816
          if( belongsToRotation(j,axis,rowBitmap) )
817
            {
818
            index = CUBITS[j].removeRotationNow(quat);
819
            mMesh.setEffectAssociation(j, CUBITS[j].computeAssociation(),index);
820
            }
821
        }
822
      }
823
    }
824

    
825
///////////////////////////////////////////////////////////////////////////////////////////////////
826

    
827
  public int getScrambleType()
828
    {
829
    return 0;
830
    }
831

    
832
///////////////////////////////////////////////////////////////////////////////////////////////////
833

    
834
  int computeBitmapFromRow(int rowBitmap, int axis)
835
    {
836
    if( mIsBandaged )
837
      {
838
      int bitmap, initBitmap=0;
839

    
840
      while( initBitmap!=rowBitmap )
841
        {
842
        initBitmap = rowBitmap;
843

    
844
        for(int cubit=0; cubit<NUM_CUBITS; cubit++)
845
          {
846
          bitmap = CUBITS[cubit].getRotRow(axis);
847
          if( (rowBitmap & bitmap) != 0 ) rowBitmap |= bitmap;
848
          }
849
        }
850
      }
851

    
852
    return rowBitmap;
853
    }
854

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

    
859
  void clampPos(float[] pos, int offset)
860
    {
861
    float currError, minError = Float.MAX_VALUE;
862
    int minErrorIndex1 = -1;
863
    int minErrorIndex2 = -1;
864

    
865
    float x = pos[offset  ];
866
    float y = pos[offset+1];
867
    float z = pos[offset+2];
868

    
869
    float xo,yo,zo;
870

    
871
    for(int i=0; i<NUM_CUBITS; i++)
872
      {
873
      int len = mOrigPos[i].length / 3;
874

    
875
      for(int j=0; j<len; j++)
876
        {
877
        xo = mOrigPos[i][3*j  ];
878
        yo = mOrigPos[i][3*j+1];
879
        zo = mOrigPos[i][3*j+2];
880

    
881
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
882

    
883
        if( currError<minError )
884
          {
885
          minError = currError;
886
          minErrorIndex1 = i;
887
          minErrorIndex2 = j;
888
          }
889
        }
890
      }
891

    
892
    if( minError< 0.1f ) // TODO: 0.1 ?
893
      {
894
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
895
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
896
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
897
      }
898
    }
899

    
900
///////////////////////////////////////////////////////////////////////////////////////////////////
901
// remember about the double cover or unit quaternions!
902

    
903
  int mulQuat(int q1, int q2)
904
    {
905
    Static4D result = QuatHelper.quatMultiply(OBJECT_QUATS[q1],OBJECT_QUATS[q2]);
906

    
907
    float rX = result.get0();
908
    float rY = result.get1();
909
    float rZ = result.get2();
910
    float rW = result.get3();
911

    
912
    final float MAX_ERROR = 0.1f;
913
    float dX,dY,dZ,dW;
914

    
915
    for(int i=0; i<NUM_QUATS; i++)
916
      {
917
      dX = OBJECT_QUATS[i].get0() - rX;
918
      dY = OBJECT_QUATS[i].get1() - rY;
919
      dZ = OBJECT_QUATS[i].get2() - rZ;
920
      dW = OBJECT_QUATS[i].get3() - rW;
921

    
922
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
923
          dY<MAX_ERROR && dY>-MAX_ERROR &&
924
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
925
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
926

    
927
      dX = OBJECT_QUATS[i].get0() + rX;
928
      dY = OBJECT_QUATS[i].get1() + rY;
929
      dZ = OBJECT_QUATS[i].get2() + rZ;
930
      dW = OBJECT_QUATS[i].get3() + rW;
931

    
932
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
933
          dY<MAX_ERROR && dY>-MAX_ERROR &&
934
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
935
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
936
      }
937

    
938
    return -1;
939
    }
940

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

    
943
  private float getAngle()
944
    {
945
    int pointNum = mRotationAngle.getNumPoints();
946

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

    
958
///////////////////////////////////////////////////////////////////////////////////////////////////
959

    
960
  void setLibInterface(ObjectLibInterface inter)
961
    {
962
    mInterface = inter;
963
    }
964

    
965
///////////////////////////////////////////////////////////////////////////////////////////////////
966

    
967
  void initializeObject(int[][] moves)
968
    {
969
    solve();
970
    setupPosition(moves);
971
    }
972

    
973
///////////////////////////////////////////////////////////////////////////////////////////////////
974

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

    
986
    mRotationAngle.removeAll();
987
    mRotationAngleStatic.set0(0);
988

    
989
    for(int i=0; i<NUM_CUBITS; i++)
990
      if( belongsToRotation(i, mCurrentRotAxis,mRotRowBitmap) )
991
        {
992
        int index = CUBITS[i].removeRotationNow(quat);
993
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),index);
994
        }
995
    }
996

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

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

    
1008
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
1009
      mRotationAngle.resetToBeginning();
1010
      mRotationAngle.removeAll();
1011
      mRotationAngle.add(mRotationAngleStatic);
1012
      mRotationAngle.add(mRotationAngleMiddle);
1013
      mRotationAngle.add(mRotationAngleFinal);
1014
      mRotateEffect.notifyWhenFinished(listener);
1015

    
1016
      return mRotateEffect.getID();
1017
      }
1018

    
1019
    return 0;
1020
    }
1021

    
1022
///////////////////////////////////////////////////////////////////////////////////////////////////
1023

    
1024
  synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
1025
    {
1026
    if( wasRotateApplied() )
1027
      {
1028
      mCurrentRotAxis = axis;
1029
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
1030

    
1031
      mRotationAngleStatic.set0(0.0f);
1032
      mRotationAxis.set( mAxis[axis] );
1033
      mRotationAngle.setDuration(durationMillis);
1034
      mRotationAngle.resetToBeginning();
1035
      mRotationAngle.add(new Static1D(0));
1036
      mRotationAngle.add(new Static1D(angle));
1037
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*SHIFT) , -1);
1038
      mRotateEffect.notifyWhenFinished(listener);
1039

    
1040
      return mRotateEffect.getID();
1041
      }
1042

    
1043
    return 0;
1044
    }
1045

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

    
1048
  void continueRotation(float angleInDegrees)
1049
    {
1050
    mRotationAngleStatic.set0(angleInDegrees);
1051
    }
1052

    
1053
///////////////////////////////////////////////////////////////////////////////////////////////////
1054

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

    
1068
    mCurrentRotAxis = axis;
1069
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
1070
    mRotationAngleStatic.set0(0.0f);
1071
    mRotationAxis.set( mAxis[axis] );
1072
    mRotationAngle.add(mRotationAngleStatic);
1073
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*SHIFT) , -1);
1074
    }
1075

    
1076
///////////////////////////////////////////////////////////////////////////////////////////////////
1077

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

    
1086
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1087
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1088
    }
1089

    
1090
///////////////////////////////////////////////////////////////////////////////////////////////////
1091

    
1092
  public int getCubitFaceColor(int cubit, int face)
1093
    {
1094
    int numFaces = mCubitFaceColors[cubit].length;
1095
    int color = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
1096

    
1097
    return color<0 ? -1 : color%NUM_FACE_COLORS;
1098
    }
1099

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

    
1102
  void resetAllTextureMaps()
1103
    {
1104
    final float ratioW = 1.0f/mNumTexCols;
1105
    final float ratioH = 1.0f/mNumTexRows;
1106
    int cubColor, varColor, color, variant, row, col;
1107

    
1108
    for(int cubit=0; cubit<NUM_CUBITS; cubit++)
1109
      {
1110
      final Static4D[] maps = new Static4D[mNumCubitFaces];
1111
      variant = getCubitVariant(cubit,mNumLayers);
1112

    
1113
      for(int face=0; face<mNumCubitFaces; face++)
1114
        {
1115
        cubColor = getCubitFaceColor(cubit,face);
1116
        varColor = getVariantFaceColor(variant,face);
1117
        color    = cubColor<0 || varColor<0 ? NUM_TEXTURES : varColor*NUM_FACE_COLORS + cubColor;
1118
        row      = (mNumTexRows-1) - color/mNumTexCols;
1119
        col      = color%mNumTexCols;
1120

    
1121
        maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1122
        }
1123

    
1124
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1125
      }
1126
    }
1127

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

    
1130
  void releaseResources()
1131
    {
1132
    mTexture.markForDeletion();
1133
    mMesh.markForDeletion();
1134
    mEffects.markForDeletion();
1135

    
1136
    for(int j=0; j<NUM_CUBITS; j++)
1137
      {
1138
      CUBITS[j].releaseResources();
1139
      }
1140
    }
1141

    
1142
///////////////////////////////////////////////////////////////////////////////////////////////////
1143

    
1144
  synchronized void restorePreferences(SharedPreferences preferences)
1145
    {
1146
    boolean error = false;
1147

    
1148
    for(int i=0; i<NUM_CUBITS; i++)
1149
      {
1150
      mQuatDebug[i] = CUBITS[i].restorePreferences(preferences);
1151

    
1152
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<NUM_QUATS)
1153
        {
1154
        CUBITS[i].modifyCurrentPosition(OBJECT_QUATS[mQuatDebug[i]]);
1155
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),mQuatDebug[i]);
1156
        }
1157
      else
1158
        {
1159
        error = true;
1160
        }
1161
      }
1162

    
1163
    if( error )
1164
      {
1165
      for(int i=0; i<NUM_CUBITS; i++)
1166
        {
1167
        CUBITS[i].solve();
1168
        mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(),0);
1169
        }
1170
      }
1171
    }
1172

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

    
1175
  void savePreferences(SharedPreferences.Editor editor)
1176
    {
1177
    for(int i=0; i<NUM_CUBITS; i++) CUBITS[i].savePreferences(editor);
1178
    }
1179

    
1180
///////////////////////////////////////////////////////////////////////////////////////////////////
1181

    
1182
  private float computeRadiusCorrection(float[] sticker, int curr, int len)
1183
    {
1184
    final float A = 0.8f;  // 0<A<1
1185

    
1186
    int prev = curr>0 ? curr-1 : len-1;
1187
    int next = curr<len-1 ? curr+1 : 0;
1188

    
1189
    float v1x = sticker[2*prev  ]-sticker[2*curr  ];
1190
    float v1y = sticker[2*prev+1]-sticker[2*curr+1];
1191
    float v2x = sticker[2*next  ]-sticker[2*curr  ];
1192
    float v2y = sticker[2*next+1]-sticker[2*curr+1];
1193

    
1194
    float len1= v1x*v1x+v1y*v1y;
1195
    float len2= v2x*v2x+v2y*v2y;
1196

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

    
1199
    return 1-A*cos;
1200
    }
1201

    
1202
///////////////////////////////////////////////////////////////////////////////////////////////////
1203

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

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

    
1226
    return mStickers[sticker];
1227
    }
1228

    
1229
///////////////////////////////////////////////////////////////////////////////////////////////////
1230
// some objects (currently Kilominx,Ivy,Rex) might want to change the stickers.
1231

    
1232
  public void adjustStickerCoords()
1233
    {
1234

    
1235
    }
1236

    
1237
///////////////////////////////////////////////////////////////////////////////////////////////////
1238
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
1239

    
1240
  private void createTexture()
1241
    {
1242
    Paint paint = new Paint();
1243
    mBitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_4444);
1244
    Canvas canvas = new Canvas(mBitmap);
1245

    
1246
    paint.setAntiAlias(true);
1247
    paint.setTextAlign(Paint.Align.CENTER);
1248
    paint.setStyle(Paint.Style.FILL);
1249

    
1250
    paint.setColor(COLOR_INTERNAL);
1251
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
1252

    
1253
    int texture = 0;
1254
    FactorySticker factory = FactorySticker.getInstance();
1255

    
1256
    for(int row=0; row<mNumTexRows; row++)
1257
      for(int col=0; col<mNumTexCols; col++)
1258
        {
1259
        if( texture>=NUM_TEXTURES ) break;
1260
        ObjectSticker sticker = retSticker(texture/NUM_FACE_COLORS);
1261
        int color = getColor(texture%NUM_FACE_COLORS);
1262
        factory.drawRoundedPolygon(canvas, paint, col*TEXTURE_HEIGHT, row*TEXTURE_HEIGHT, color, sticker);
1263
        texture++;
1264
        }
1265
    }
1266

    
1267
///////////////////////////////////////////////////////////////////////////////////////////////////
1268

    
1269
  void setTexture()
1270
    {
1271
    if( mBitmap==null ) createTexture();
1272

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

    
1280
///////////////////////////////////////////////////////////////////////////////////////////////////
1281

    
1282
  void setObjectRatioNow(float sc, int nodeSize)
1283
    {
1284
    mObjectScreenRatio = sc;
1285
    float scale = mObjectScreenRatio*mInitScreenRatio*nodeSize/mSize;
1286
    mObjectScale.set(scale,scale,scale);
1287

    
1288
    if( mTouchControl ==null ) mTouchControl = getTouchControl();
1289
    mTouchControl.setObjectRatio(mObjectScreenRatio*mInitScreenRatio);
1290
    }
1291

    
1292
///////////////////////////////////////////////////////////////////////////////////////////////////
1293

    
1294
  void setObjectRatio(float sizeChange, int nodeSize)
1295
    {
1296
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
1297

    
1298
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
1299
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
1300

    
1301
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1302
    }
1303

    
1304
///////////////////////////////////////////////////////////////////////////////////////////////////
1305

    
1306
  void setNodeSize(int nodeSize)
1307
    {
1308
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1309
    }
1310

    
1311
///////////////////////////////////////////////////////////////////////////////////////////////////
1312

    
1313
  public float getRatio()
1314
    {
1315
    return mObjectScreenRatio;
1316
    }
1317

    
1318
///////////////////////////////////////////////////////////////////////////////////////////////////
1319

    
1320
  public float getObjectRatio()
1321
    {
1322
    return mObjectScreenRatio*mInitScreenRatio;
1323
    }
1324

    
1325
///////////////////////////////////////////////////////////////////////////////////////////////////
1326

    
1327
  boolean isSolved()
1328
    {
1329
    if( mSolvedFunctionIndex==0 ) return isSolved0();
1330
    if( mSolvedFunctionIndex==1 ) return isSolved1();
1331
    if( mSolvedFunctionIndex==2 ) return isSolved2();
1332
    if( mSolvedFunctionIndex==3 ) return isSolved3();
1333

    
1334
    return false;
1335
    }
1336

    
1337
///////////////////////////////////////////////////////////////////////////////////////////////////
1338

    
1339
  int computeNearestAngle(int axis, float angle, float speed)
1340
    {
1341
    int[] basicArray = getBasicAngle();
1342
    int basicAngle   = basicArray[axis>=basicArray.length ? 0 : axis];
1343
    int nearestAngle = 360/basicAngle;
1344

    
1345
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
1346
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
1347

    
1348
    if( tmp!=0 ) return nearestAngle*tmp;
1349

    
1350
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
1351
    }
1352

    
1353
///////////////////////////////////////////////////////////////////////////////////////////////////
1354
// INTERNAL API - those are called from 'effects' package
1355
///////////////////////////////////////////////////////////////////////////////////////////////////
1356

    
1357
  public void randomizeNewScramble(int[][] scramble, Random rnd, int curr, int total)
1358
    {
1359
    mScrambler.randomizeNewScramble(scramble,rnd,curr,total);
1360
    }
1361

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

    
1364
  public Static4D getRotationQuat()
1365
    {
1366
    return mQuat;
1367
    }
1368

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

    
1371
  public float getSize()
1372
    {
1373
    return mSize;
1374
    }
1375

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

    
1378
  public void apply(Effect effect, int position)
1379
    {
1380
    mEffects.apply(effect, position);
1381
    }
1382

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

    
1385
  public void remove(long effectID)
1386
    {
1387
    mEffects.abortById(effectID);
1388
    }
1389

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

    
1392
  public MeshBase getObjectMesh()
1393
    {
1394
    return mMesh;
1395
    }
1396

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

    
1399
  public DistortedEffects getObjectEffects()
1400
    {
1401
    return mEffects;
1402
    }
1403

    
1404
///////////////////////////////////////////////////////////////////////////////////////////////////
1405
// PUBLIC API
1406
///////////////////////////////////////////////////////////////////////////////////////////////////
1407

    
1408
  public int getCubitFaceColorIndex(int cubit, int face)
1409
    {
1410
    Static4D texMap = mMesh.getTextureMap(NUM_FACE_COLORS*cubit + face);
1411

    
1412
    int x = (int)(texMap.get0()/texMap.get2());
1413
    int y = (int)(texMap.get1()/texMap.get3());
1414

    
1415
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
1416
    }
1417

    
1418
///////////////////////////////////////////////////////////////////////////////////////////////////
1419

    
1420
  public int[] getNumLayers()
1421
    {
1422
    return mNumLayers;
1423
    }
1424

    
1425
///////////////////////////////////////////////////////////////////////////////////////////////////
1426

    
1427
  public synchronized void solve()
1428
    {
1429
    for(int i=0; i<NUM_CUBITS; i++)
1430
      {
1431
      CUBITS[i].solve();
1432
      mMesh.setEffectAssociation(i, CUBITS[i].computeAssociation(), 0);
1433
      }
1434
    }
1435

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

    
1438
  public int getCubitQuatIndex(int cubit)
1439
    {
1440
    return CUBITS[cubit].mQuatIndex;
1441
    }
1442

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

    
1445
  public int getCubitRotRow(int cubit, int axis)
1446
    {
1447
    return CUBITS[cubit].getRotRow(axis);
1448
    }
1449

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

    
1452
  public Bitmap getStickerBitmap()
1453
    {
1454
    return mBitmap;
1455
    }
1456

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

    
1459
  public DistortedNode getNode()
1460
    {
1461
    return mNode;
1462
    }
1463

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

    
1466
  public ObjectType getObjectType()
1467
    {
1468
    return intGetObjectType(mNumLayers);
1469
    }
1470

    
1471
///////////////////////////////////////////////////////////////////////////////////////////////////
1472

    
1473
  public int getNumStickerTypes()
1474
    {
1475
    return mNumStickerTypes;
1476
    }
1477

    
1478
///////////////////////////////////////////////////////////////////////////////////////////////////
1479
// this is here only so it can be overridden in TwistyJSON soo that we can get this from JSON.
1480

    
1481
  public int getNumCubitFaces()
1482
    {
1483
    return 0;
1484
    }
1485

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

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

    
1514
///////////////////////////////////////////////////////////////////////////////////////////////////
1515

    
1516
  public String getShortName()
1517
    {
1518
    return getObjectType().name();
1519
    }
1520

    
1521
///////////////////////////////////////////////////////////////////////////////////////////////////
1522

    
1523
  protected void setReader(JsonReader reader)
1524
    {
1525
    // empty
1526
    }
1527

    
1528
///////////////////////////////////////////////////////////////////////////////////////////////////
1529

    
1530
  protected abstract ObjectType intGetObjectType(int[] numLayers);
1531

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

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