Project

General

Profile

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

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

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.QuatGroupGenerator;
59
import org.distorted.objectlib.scrambling.ScrambleState;
60
import org.distorted.objectlib.scrambling.ObjectScrambler;
61
import org.distorted.objectlib.json.JsonReader;
62
import org.distorted.objectlib.touchcontrol.*;
63

    
64
import static org.distorted.objectlib.touchcontrol.TouchControl.*;
65

    
66
///////////////////////////////////////////////////////////////////////////////////////////////////
67

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

    
73
  public static final int MODE_ICON = 0;
74
  public static final int MODE_NORM = 1;
75

    
76
  public static final int COLOR_YELLOW   = 0xffffff00;
77
  public static final int COLOR_WHITE    = 0xffffffff;
78
  public static final int COLOR_BLUE     = 0xff0000ff;
79
  public static final int COLOR_GREEN    = 0xff00bb00;
80
  public static final int COLOR_RED      = 0xff990000;
81
  public static final int COLOR_ORANGE   = 0xffff6200;
82
  public static final int COLOR_GREY     = 0xff727c7b;
83
  public static final int COLOR_VIOLET   = 0xff7700bb;
84
  public static final int COLOR_STROKE   = 0xff000000;
85
  private static final int COLOR_INTERNAL= 0xff000000;
86

    
87
  public static final int TEXTURE_HEIGHT = 256;
88
  static final int NUM_STICKERS_IN_ROW = 4;
89

    
90
  public static final float SQ2 = (float)Math.sqrt(2);
91
  public static final float SQ3 = (float)Math.sqrt(3);
92
  public static final float SQ5 = (float)Math.sqrt(5);
93
  public static final float SQ6 = (float)Math.sqrt(6);
94

    
95
  private static final float MAX_SIZE_CHANGE = 1.35f;
96
  private static final float MIN_SIZE_CHANGE = 0.75f;
97

    
98
  private static final Static3D CENTER = new Static3D(0,0,0);
99
  private static final int POST_ROTATION_MILLISEC = 500;
100

    
101
  protected float[][] mStickerCoords;
102
  protected Static4D[] mObjectQuats;
103
  int mNumAxis, mMaxNumLayers;
104

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

    
151
  //////////////////// SOLVED1 ////////////////////////
152

    
153
  private int[] mFaceMap;
154
  private int[][] mScramble;
155
  private int[] mColors;
156

    
157
///////////////////////////////////////////////////////////////////////////////////////////////////
158

    
159
  TwistyObject(InputStream jsonStream, int meshState, int iconMode, Static4D quat, Static3D move, float scale, InputStream meshStream)
160
    {
161
    JsonReader reader = JsonReader.getInstance();
162
    reader.parseJsonFile(jsonStream);
163
    setReader(reader);
164

    
165
    mNumLayers = reader.getNumLayers();
166
    mSize      = reader.getSize();
167
    initialize(meshState,iconMode,quat,move,scale,meshStream,true);
168
    }
169

    
170
///////////////////////////////////////////////////////////////////////////////////////////////////
171

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

    
179
///////////////////////////////////////////////////////////////////////////////////////////////////
180

    
181
  private void initialize(int meshState, int iconMode, Static4D quat, Static3D move, float scale, InputStream stream, boolean fromJSON)
182
    {
183
    mIconMode = iconMode;
184
    mQuat = quat;
185
    mAxis = getRotationAxis();
186
    mInitScreenRatio = getScreenRatio();
187
    mSolvedFunctionIndex = getSolvedFunctionIndex();
188
    mBasicAngles = getBasicAngles();
189
    mObjectQuats = getQuats();
190
    mNumQuats = mObjectQuats.length;
191
    mOrigPos = getCubitPositions(mNumLayers);
192

    
193
    int numAxis = mAxis.length;
194
    mMaxNumLayers = -1;
195
    mCuts = getCuts(mNumLayers);
196
    mNumCuts = new int[numAxis];
197
    for(int i=0; i<numAxis; i++)
198
      {
199
      if( mMaxNumLayers<mNumLayers[i] ) mMaxNumLayers = mNumLayers[i];
200
      mNumCuts[i] = (mCuts==null || mCuts[i]==null ? 0 : mCuts[i].length);
201
      }
202

    
203
    mNumCubits = mOrigPos.length;
204
    mNumFaceColors = getNumFaceColors();
205
    mNumAxis = mAxis.length;
206

    
207
    int scramblingType = getScrambleType();
208
    ScrambleState[] states = getScrambleStates();
209
    mScrambler = new ObjectScrambler(scramblingType, mNumAxis,mNumLayers,states);
210

    
211
    boolean bandaged=false;
212

    
213
    for( int c=0; c<mNumCubits; c++)
214
      {
215
      if( mOrigPos[c].length>3 )
216
        {
217
        bandaged=true;
218
        break;
219
        }
220
      }
221
    mIsBandaged = bandaged;
222
    mQuatDebug = new int[mNumCubits];
223

    
224
    mRotationAngle= new Dynamic1D();
225
    mRotationAxis = new Static3D(1,0,0);
226
    mRotateEffect = new VertexEffectRotate(mRotationAngle, mRotationAxis, CENTER);
227

    
228
    mRotationAngleStatic = new Static1D(0);
229
    mRotationAngleMiddle = new Static1D(0);
230
    mRotationAngleFinal  = new Static1D(0);
231

    
232
    mObjectScale = new Static3D(scale,scale,scale);
233
    setObjectRatioNow(scale,720);
234

    
235
    MatrixEffectScale scaleEffect = new MatrixEffectScale(mObjectScale);
236
    MatrixEffectQuaternion quatEffect = new MatrixEffectQuaternion(mQuat, CENTER);
237
    MatrixEffectMove moveEffect = new MatrixEffectMove(move);
238

    
239
    boolean fromDMESH = (stream!=null && meshState==MESH_NICE);
240
    getQuatsAndShapes(fromDMESH,fromJSON);
241
    createMeshAndCubits(stream,meshState,fromDMESH);
242
    setUpTextures(fromDMESH,fromJSON);
243
    createDataStructuresForSolved();
244

    
245
    mEffects = new DistortedEffects();
246

    
247
    for( int q=0; q<mNumQuats; q++)
248
      {
249
      VertexEffectQuaternion vq = new VertexEffectQuaternion(mObjectQuats[q],CENTER);
250
      vq.setMeshAssociation(0,q);
251
      mEffects.apply(vq);
252
      }
253

    
254
    mEffects.apply(mRotateEffect);
255
    mEffects.apply(quatEffect);
256
    mEffects.apply(scaleEffect);
257
    mEffects.apply(moveEffect);
258

    
259
    mNode = new DistortedNode(mTexture,mEffects,mMesh);
260
    }
261

    
262
///////////////////////////////////////////////////////////////////////////////////////////////////
263

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

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

    
278
    sumX /= len;
279
    sumY /= len;
280
    sumZ /= len;
281

    
282
    return new Static3D(sumX,sumY,sumZ);
283
    }
284

    
285
///////////////////////////////////////////////////////////////////////////////////////////////////
286

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

    
296
    for( int cubit=0; cubit<mNumCubits; cubit++)
297
      {
298
      int variant = getCubitVariant(cubit,mNumLayers);
299
      int[][] indices = mShapes[variant].getVertIndices();
300
      int numFaces = indices.length;
301

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

    
310
///////////////////////////////////////////////////////////////////////////////////////////////////
311

    
312
  private void getQuatsAndShapes(boolean fromDMESH, boolean fromJSON)
313
    {
314
    mNumCubitVariants = getNumCubitVariants(mNumLayers);
315

    
316
    if( !fromDMESH || !fromJSON )
317
      {
318
      FactoryCubit factory = FactoryCubit.getInstance();
319
      factory.clear();
320

    
321
displayCubitQuats();
322

    
323
      mOrigQuat = new Static4D[mNumCubits];
324
      for(int i=0; i<mNumCubits; i++) mOrigQuat[i] = getCubitQuats(i,mNumLayers);
325

    
326
      mShapes = new ObjectShape[mNumCubitVariants];
327
      for(int i=0; i<mNumCubitVariants; i++) mShapes[i] = getObjectShape(i);
328
      mNumCubitFaces = ObjectShape.computeNumComponents(mShapes);
329
      mVariantFaceIsOuter = new int[mNumCubitVariants][];
330

    
331
      if( !fromJSON )
332
        {
333
        mCubitFaceColors = ObjectShape.computeColors(mShapes,mOrigPos,mOrigQuat,this);
334
        createOuterFaces();
335
        }
336

    
337
      if( fromDMESH )
338
        {
339
        for(int i=0; i<mNumCubitVariants; i++) factory.createNewFaceTransform(mShapes[i], mVariantFaceIsOuter[i]);
340
        }
341
      }
342
    }
343

    
344
///////////////////////////////////////////////////////////////////////////////////////////////////
345

    
346
  private void createMeshAndCubits(InputStream stream, int meshState, boolean fromDMESH)
347
    {
348
    mCubits = new Cubit[mNumCubits];
349

    
350
    if( fromDMESH )
351
      {
352
      DataInputStream dos = new DataInputStream(stream);
353
      mMesh = new MeshFile(dos);
354

    
355
      try
356
        {
357
        stream.close();
358
        }
359
      catch(IOException e)
360
        {
361
        android.util.Log.e("meshFile", "Error closing InputStream: "+e.toString());
362
        }
363

    
364
      for(int i=0; i<mNumCubits; i++)
365
        {
366
        mCubits[i] = new Cubit(this,mOrigPos[i], mNumAxis);
367
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(), 0);
368
        }
369
      }
370
    else
371
      {
372
      MeshBase[] cubitMesh = new MeshBase[mNumCubits];
373

    
374
      for(int i=0; i<mNumCubits; i++)
375
        {
376
        mCubits[i] = new Cubit(this,mOrigPos[i], mNumAxis);
377
        cubitMesh[i] = createCubitMesh(i,mNumLayers,meshState,mNumCubitFaces);
378
        Static3D pos = getPos(mOrigPos[i]);
379
        cubitMesh[i].apply(new MatrixEffectMove(pos),1,0);
380
        cubitMesh[i].setEffectAssociation(0, mCubits[i].computeAssociation(), 0);
381
        }
382

    
383
      mMesh = new MeshJoined(cubitMesh);
384
      }
385
    }
386

    
387
///////////////////////////////////////////////////////////////////////////////////////////////////
388

    
389
  private MeshBase createCubitMesh(int cubit, int[] numLayers, int meshState, int numComponents)
390
    {
391
    int variant = getCubitVariant(cubit,numLayers);
392

    
393
    if( mMeshes==null ) mMeshes = new MeshBase[mNumCubitVariants];
394

    
395
    if( mMeshes[variant]==null )
396
      {
397
      ObjectFaceShape faceShape = getObjectFaceShape(variant);
398
      FactoryCubit factory = FactoryCubit.getInstance();
399
      factory.createNewFaceTransform(mShapes[variant],mVariantFaceIsOuter[variant]);
400
      mMeshes[variant] = factory.createRoundedSolid(mShapes[variant],faceShape,meshState, numComponents);
401
      }
402

    
403
    MeshBase mesh = mMeshes[variant].copy(true);
404
    MatrixEffectQuaternion quat = new MatrixEffectQuaternion( mOrigQuat[cubit], CENTER );
405
    mesh.apply(quat,0xffffffff,0);
406

    
407
    return mesh;
408
    }
409

    
410
///////////////////////////////////////////////////////////////////////////////////////////////////
411

    
412
  private void setUpTextures(boolean fromDMESH, boolean fromJSON)
413
    {
414
    mTexture = new DistortedTexture();
415

    
416
    if( fromJSON )
417
      {
418
      mNumStickerTypes = getNumStickerTypes();
419
      mNumCubitFaces = getNumCubitFaces();
420
      }
421
    else
422
      {
423
      FactoryCubit factory = FactoryCubit.getInstance();
424
      mStickerCoords   = factory.getStickerCoords();
425
      mStickerVariants = factory.getStickerVariants();
426
      mStickerScales   = factory.getStickerScales();
427
      adjustStickerCoords();
428
      mNumStickerTypes = (mStickerCoords==null ? 0 : mStickerCoords.length);
429
      }
430

    
431
    mNumTextures= mNumFaceColors *mNumStickerTypes;
432
    mNumTexCols = NUM_STICKERS_IN_ROW;
433
    mNumTexRows = (mNumTextures+1)/NUM_STICKERS_IN_ROW;
434
    if( mNumTexCols*mNumTexRows < mNumTextures+1 ) mNumTexRows++;
435

    
436
    if( !fromDMESH || shouldResetTextureMaps() ) resetAllTextureMaps();
437
    setTexture();
438
    }
439

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

    
442
  private int getMultQuat(int index1, int index2)
443
    {
444
    if( mQuatMult==null )
445
      {
446
      mQuatMult = new int[mNumQuats][mNumQuats];
447

    
448
      for(int i=0; i<mNumQuats; i++)
449
        for(int j=0; j<mNumQuats; j++) mQuatMult[i][j] = -1;
450
      }
451

    
452
    if( mQuatMult[index1][index2]==-1 )
453
      {
454
      mQuatMult[index1][index2] = mulQuat(index1,index2);
455
      }
456

    
457
    return mQuatMult[index1][index2];
458
    }
459

    
460
///////////////////////////////////////////////////////////////////////////////////////////////////
461

    
462
  public boolean isInIconMode()
463
    {
464
    return mIconMode==MODE_ICON;
465
    }
466

    
467
///////////////////////////////////////////////////////////////////////////////////////////////////
468

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

    
474
///////////////////////////////////////////////////////////////////////////////////////////////////
475

    
476
  public boolean shouldResetTextureMaps()
477
    {
478
    return false;
479
    }
480

    
481
///////////////////////////////////////////////////////////////////////////////////////////////////
482

    
483
  private void createDataStructuresForSolved()
484
    {
485
    mTmpQuats = new int[mNumQuats];
486
    mSolvedQuats = getSolvedQuats();
487
    }
488

    
489
///////////////////////////////////////////////////////////////////////////////////////////////////
490
// This is used to build internal data structures for the generic 'isSolved()'
491
//
492
// if this is an internal cubit (all faces black): return -1
493
// if this is a face cubit (one non-black face): return the color index of the only non-black face.
494
// Color index, i.e. the index into the 'FACE_COLORS' table.
495
// else (edge or corner cubit, more than one non-black face): return -2.
496

    
497
  protected int retCubitSolvedStatus(int cubit)
498
    {
499
    int numNonBlack=0, nonBlackIndex=-1, varColor, cubColor;
500
    int variant = getCubitVariant(cubit,mNumLayers);
501

    
502
    for(int face=0; face<mNumCubitFaces; face++)
503
      {
504
      varColor = getVariantFaceColor(variant,face);
505
      int numFaces = mCubitFaceColors[cubit].length;
506
      cubColor = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
507

    
508
      if( varColor>=0 && cubColor>=0 )
509
        {
510
        numNonBlack++;
511
        nonBlackIndex = cubColor;
512
        }
513
      }
514

    
515
    if( numNonBlack==0 ) return -1;
516
    if( numNonBlack>=2 ) return -2;
517

    
518
    return nonBlackIndex;
519
    }
520

    
521
///////////////////////////////////////////////////////////////////////////////////////////////////
522

    
523
  private boolean sticksOut(Static3D[] faceAxis, float[] dist, float x, float y, float z )
524
    {
525
    final float MAXERR = 0.05f;
526
    int numAxis = dist.length;
527

    
528
    for(int i=0; i<numAxis; i++)
529
      {
530
      Static3D ax = faceAxis[i];
531
      float len = ax.get0()*x + ax.get1()*y + ax.get2()*z;
532
      if( len>mSize*dist[i]+MAXERR ) return true;
533
      }
534

    
535
    return false;
536
    }
537

    
538
///////////////////////////////////////////////////////////////////////////////////////////////////
539

    
540
  private boolean doesNotStickOut(int variant, float px, float py, float pz, float[] tmp, Static4D quat)
541
    {
542
    ObjectShape shape = getObjectShape(variant);
543
    float[][] vertices = shape.getVertices();
544
    Static3D[] axis = getFaceAxis();
545
    float[] dist3D = getDist3D(mNumLayers);
546

    
547
    for( float[] vertex : vertices)
548
      {
549
      float x = vertex[0];
550
      float y = vertex[1];
551
      float z = vertex[2];
552

    
553
      QuatHelper.rotateVectorByQuat(tmp, x, y, z, 1, quat);
554

    
555
      float mx = tmp[0] + px;
556
      float my = tmp[1] + py;
557
      float mz = tmp[2] + pz;
558

    
559
      if( sticksOut(axis, dist3D, mx,my,mz) ) return false;
560
      }
561

    
562
    return true;
563
    }
564

    
565
///////////////////////////////////////////////////////////////////////////////////////////////////
566

    
567
  private float computeAvg(float[] pos, int offset)
568
    {
569
    int len = pos.length/3;
570
    float ret=0.0f;
571
    for(int i=0; i<len; i++) ret += pos[3*i+offset];
572
    ret /= len;
573

    
574
    return ret;
575
    }
576

    
577
///////////////////////////////////////////////////////////////////////////////////////////////////
578

    
579
  protected void displayCubitQuats()
580
    {
581
    StringBuilder builder = new StringBuilder();
582
    float[] tmp = new float[4];
583
    float ERR = 0.01f;
584

    
585
    for(int cubit=0; cubit<mNumCubits; cubit++)
586
      {
587
      builder.append(cubit);
588
      builder.append(" : ");
589

    
590
      int refCubit,variant = getCubitVariant(cubit,mNumLayers);
591

    
592
      for(refCubit=0; refCubit<mNumCubits; refCubit++)
593
        {
594
        if( getCubitVariant(refCubit,mNumLayers)==variant ) break;
595
        }
596

    
597
      float[] curpos = mOrigPos[cubit];
598
      float[] refpos = mOrigPos[refCubit];
599
      float refX = computeAvg(refpos,0);
600
      float refY = computeAvg(refpos,1);
601
      float refZ = computeAvg(refpos,2);
602
      float curX = computeAvg(curpos,0);
603
      float curY = computeAvg(curpos,1);
604
      float curZ = computeAvg(curpos,2);
605

    
606
      for(int quat=0; quat<mNumQuats; quat++)
607
        {
608
        QuatHelper.rotateVectorByQuat(tmp,refX,refY,refZ,0,mObjectQuats[quat]);
609

    
610
        float dx = tmp[0]-curX;
611
        float dy = tmp[1]-curY;
612
        float dz = tmp[2]-curZ;
613

    
614
        if( dx>-ERR && dx<ERR && dy>-ERR && dy<ERR && dz>-ERR && dz<ERR )
615
          {
616
          if( doesNotStickOut(variant,curX,curY,curZ,tmp,mObjectQuats[quat]) )
617
            {
618
            builder.append(quat);
619
            builder.append(',');
620
            }
621
          else
622
            {
623
            android.util.Log.e("D", "cubit: "+cubit+" quat: "+quat+" : center correct, but shape sticks out");
624
            }
625
          }
626
        }
627

    
628
      builder.append('\n');
629
      }
630

    
631
    android.util.Log.e("D", "cubitQuats: \n"+builder.toString() );
632
    }
633

    
634
///////////////////////////////////////////////////////////////////////////////////////////////////
635

    
636
  protected int[] buildSolvedQuats(Static3D faceAx)
637
    {
638
    final float MAXD = 0.0001f;
639
    float x = faceAx.get0();
640
    float y = faceAx.get1();
641
    float z = faceAx.get2();
642
    float a,dx,dy,dz,qx,qy,qz;
643
    Static4D quat;
644
    int place = 0;
645

    
646
    for(int q=1; q<mNumQuats; q++)
647
      {
648
      quat = mObjectQuats[q];
649
      qx = quat.get0();
650
      qy = quat.get1();
651
      qz = quat.get2();
652

    
653
           if( x!=0.0f ) { a = qx/x; }
654
      else if( y!=0.0f ) { a = qy/y; }
655
      else               { a = qz/z; }
656

    
657
      dx = a*x-qx;
658
      dy = a*y-qy;
659
      dz = a*z-qz;
660

    
661
      if( dx>-MAXD && dx<MAXD && dy>-MAXD && dy<MAXD && dz>-MAXD && dz<MAXD )
662
        {
663
        mTmpQuats[place++] = q;
664
        }
665
      }
666

    
667
    if( place!=0 )
668
      {
669
      int[] ret = new int[place];
670
      System.arraycopy(mTmpQuats,0,ret,0,place);
671
      return ret;
672
      }
673

    
674
    return null;
675
    }
676

    
677
///////////////////////////////////////////////////////////////////////////////////////////////////
678

    
679
  public int[][] getSolvedQuats()
680
    {
681
    int[] groups = new int[mNumCubits];
682
    int numGroups = 1;
683
    int numFirst  = 0;
684

    
685
    for(int cubit=0; cubit<mNumCubits; cubit++)
686
      {
687
      groups[cubit] = retCubitSolvedStatus(cubit);
688
      if( groups[cubit]>=0 ) numGroups++;
689
      else                   numFirst++;
690
      }
691

    
692
    int firstIndex = 1;
693
    int groupIndex = 1;
694
    int[][] solvedQuats = new int[numGroups][];
695
    solvedQuats[0] = new int[1+numFirst];
696
    solvedQuats[0][0] = numFirst;
697
    Static3D[] axis = getFaceAxis();
698

    
699
    for(int cubit=0; cubit<mNumCubits; cubit++)
700
      {
701
      int group = groups[cubit];
702

    
703
      if( group<0 )
704
        {
705
        solvedQuats[0][firstIndex] = cubit;
706
        firstIndex++;
707
        }
708
      else
709
        {
710
        int[] quats = buildSolvedQuats(axis[group]);
711
        int len = quats==null ? 0 : quats.length;
712
        solvedQuats[groupIndex] = new int[2+len];
713
        solvedQuats[groupIndex][0] = 1;
714
        solvedQuats[groupIndex][1] = cubit;
715
        for(int i=0; i<len; i++) solvedQuats[groupIndex][i+2] = quats[i];
716
        groupIndex++;
717
        }
718
      }
719
/*
720
    String dbg = "SOLVED GROUPS:\n";
721

    
722
    for(int g=0; g<numGroups; g++)
723
      {
724
      int len = solvedQuats[g].length;
725
      for(int i=0; i<len; i++) dbg += (" "+solvedQuats[g][i]);
726
      dbg+="\n";
727
      }
728

    
729
    android.util.Log.e("D", dbg);
730
*/
731
    return solvedQuats;
732
    }
733

    
734
///////////////////////////////////////////////////////////////////////////////////////////////////
735

    
736
  public int getSolvedFunctionIndex()
737
    {
738
    return 0;
739
    }
740

    
741
///////////////////////////////////////////////////////////////////////////////////////////////////
742
// special SolvedQuats for the case where there are no corner of edge cubits.
743
// first row {0} - means there are no corners or edges.
744
// each next defines all cubits of a singe face (numCubits, firstCubit, cubit1,..,cubitN-1, quat0,..., quatM
745

    
746
  private boolean isSolvedCentersOnly()
747
    {
748
    int numGroups = mSolvedQuats.length;
749

    
750
    for(int group=1; group<numGroups; group++)
751
      {
752
      int numEntries= mSolvedQuats[group].length;
753
      int numCubits = mSolvedQuats[group][0];
754
      int firstCubit= mSolvedQuats[group][1];
755
      int firstQuat = mCubits[firstCubit].mQuatIndex;
756

    
757
      for(int cubit=2; cubit<=numCubits; cubit++)
758
        {
759
        int currCubit= mSolvedQuats[group][cubit];
760
        int currQuat = mCubits[currCubit].mQuatIndex;
761
        boolean isGood= (firstQuat==currQuat);
762

    
763
        for(int q=numCubits+1; !isGood && q<numEntries; q++)
764
          {
765
          int quat = mSolvedQuats[group][q];
766
          if( firstQuat == getMultQuat(currQuat,quat) ) isGood = true;
767
          }
768

    
769
        if( !isGood ) return false;
770
        }
771
      }
772

    
773
    return true;
774
    }
775

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

    
778
  private boolean isSolved0()
779
    {
780
    if( mSolvedQuats[0][0]==0 ) return isSolvedCentersOnly();
781

    
782
    for( int[] solvedQuat : mSolvedQuats )
783
      {
784
      int numCubits = solvedQuat[0];
785
      int firstCubit= solvedQuat[1];
786
      int quat = mCubits[firstCubit].mQuatIndex;
787

    
788
      for( int cubit=2; cubit<=numCubits; cubit++ )
789
        {
790
        int c = solvedQuat[cubit];
791
        if( quat != mCubits[c].mQuatIndex ) return false;
792
        }
793
      }
794

    
795
    int cubit= mSolvedQuats[0][1];
796
    int quat0= mCubits[cubit].mQuatIndex;
797
    int numGroups = mSolvedQuats.length;
798

    
799
    for(int group=1; group<numGroups; group++)
800
      {
801
      int firstCubit= mSolvedQuats[group][1];
802
      int currQuat  = mCubits[firstCubit].mQuatIndex;
803

    
804
      if( quat0==currQuat ) continue;
805

    
806
      boolean isGood= false;
807
      int numEntries= mSolvedQuats[group].length;
808
      int numCubits = mSolvedQuats[group][0];
809

    
810
      for(int q=numCubits+1; q<numEntries; q++)
811
        {
812
        int quat = mSolvedQuats[group][q];
813

    
814
        if( quat0 == getMultQuat(currQuat,quat) )
815
          {
816
          isGood = true;
817
          break;
818
          }
819
        }
820

    
821
      if( !isGood ) return false;
822
      }
823

    
824
    return true;
825
    }
826

    
827
///////////////////////////////////////////////////////////////////////////////////////////////////
828

    
829
  private int computeScramble(int quatNum, int centerNum)
830
    {
831
    float MAXDIFF = 0.01f;
832
    float[] center= mOrigPos[centerNum];
833
    Static4D sc = new Static4D(center[0], center[1], center[2], 1.0f);
834
    Static4D result = QuatHelper.rotateVectorByQuat(sc,mObjectQuats[quatNum]);
835

    
836
    float x = result.get0();
837
    float y = result.get1();
838
    float z = result.get2();
839

    
840
    for(int c=0; c<mNumCubits; c++)
841
      {
842
      float[] cent = mOrigPos[c];
843

    
844
      float qx = cent[0] - x;
845
      float qy = cent[1] - y;
846
      float qz = cent[2] - z;
847

    
848
      if( qx>-MAXDIFF && qx<MAXDIFF &&
849
          qy>-MAXDIFF && qy<MAXDIFF &&
850
          qz>-MAXDIFF && qz<MAXDIFF  ) return c;
851
      }
852

    
853
    return -1;
854
    }
855

    
856
///////////////////////////////////////////////////////////////////////////////////////////////////
857
// Dino4 uses this. It is solved if and only if groups of cubits
858
// (0,3,7), (1,2,5), (4,8,9), (6,10,11)
859
// or
860
// (0,1,4), (2,3,6), (5,9,10), (7,8,11)
861
// are all the same color.
862

    
863
  private boolean isSolved1()
864
    {
865
    if( mScramble==null )
866
      {
867
      mScramble = new int[mNumQuats][mNumCubits];
868
      mColors   = new int[mNumCubits];
869

    
870
      for(int q=0; q<mNumQuats; q++)
871
        for(int c=0; c<mNumCubits; c++) mScramble[q][c] = computeScramble(q,c);
872
      }
873

    
874
    if( mFaceMap==null )
875
      {
876
      mFaceMap = new int[] { 4, 2, 2, 4, 0, 2, 1, 4, 0, 0, 1, 1 };
877
      }
878

    
879
    for(int c=0; c<mNumCubits; c++)
880
      {
881
      int index = mScramble[mCubits[c].mQuatIndex][c];
882
      mColors[index] = mFaceMap[c];
883
      }
884

    
885
    if( mColors[0]==mColors[3] && mColors[0]==mColors[7] &&
886
        mColors[1]==mColors[2] && mColors[1]==mColors[5] &&
887
        mColors[4]==mColors[8] && mColors[4]==mColors[9]  ) return true;
888

    
889
    if( mColors[0]==mColors[1] && mColors[0]==mColors[4] &&
890
        mColors[2]==mColors[3] && mColors[2]==mColors[6] &&
891
        mColors[5]==mColors[9] && mColors[5]==mColors[10] ) return true;
892

    
893
    return false;
894
    }
895

    
896
///////////////////////////////////////////////////////////////////////////////////////////////////
897

    
898
  int computeRow(float[] pos, int axisIndex)
899
    {
900
    int ret=0;
901
    int len = pos.length / 3;
902
    Static3D axis = mAxis[axisIndex];
903
    float axisX = axis.get0();
904
    float axisY = axis.get1();
905
    float axisZ = axis.get2();
906
    float casted;
907

    
908
    for(int i=0; i<len; i++)
909
      {
910
      casted = pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ;
911
      ret |= computeSingleRow(axisIndex,casted);
912
      }
913

    
914
    return ret;
915
    }
916

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

    
919
  private int computeSingleRow(int axisIndex,float casted)
920
    {
921
    int num = mNumCuts[axisIndex];
922

    
923
    for(int i=0; i<num; i++)
924
      {
925
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
926
      }
927

    
928
    return (1<<num);
929
    }
930

    
931
///////////////////////////////////////////////////////////////////////////////////////////////////
932

    
933
  private boolean wasRotateApplied()
934
    {
935
    return mEffects.exists(mRotateEffect.getID());
936
    }
937

    
938
///////////////////////////////////////////////////////////////////////////////////////////////////
939

    
940
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
941
    {
942
    return (mCubits[cubit].getRotRow(axis) & rowBitmap) != 0;
943
    }
944

    
945
///////////////////////////////////////////////////////////////////////////////////////////////////
946
// note the minus in front of the sin() - we rotate counterclockwise
947
// when looking towards the direction where the axis increases in values.
948

    
949
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
950
    {
951
    Static3D axis = mAxis[axisIndex];
952

    
953
    while( angleInDegrees<0 ) angleInDegrees += 360;
954
    angleInDegrees %= 360;
955
    
956
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
957
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
958

    
959
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
960
    }
961

    
962
///////////////////////////////////////////////////////////////////////////////////////////////////
963

    
964
  private synchronized void setupPosition(int[][] moves)
965
    {
966
    if( moves!=null )
967
      {
968
      Static4D quat;
969
      int index, axis, rowBitmap, angle;
970

    
971
      for(int[] move: moves)
972
        {
973
        axis     = move[0];
974
        rowBitmap= computeBitmapFromRow( move[1],axis );
975
        angle    = move[2]*(360/mBasicAngles[axis]);
976
        quat     = makeQuaternion(axis,angle);
977

    
978
        for(int j=0; j<mNumCubits; j++)
979
          if( belongsToRotation(j,axis,rowBitmap) )
980
            {
981
            index = mCubits[j].removeRotationNow(quat);
982
            mMesh.setEffectAssociation(j, mCubits[j].computeAssociation(),index);
983
            }
984
        }
985
      }
986
    }
987

    
988
///////////////////////////////////////////////////////////////////////////////////////////////////
989

    
990
  public int getScrambleType()
991
    {
992
    return 0;
993
    }
994

    
995
///////////////////////////////////////////////////////////////////////////////////////////////////
996

    
997
  int computeBitmapFromRow(int rowBitmap, int axis)
998
    {
999
    if( mIsBandaged )
1000
      {
1001
      int bitmap, initBitmap=0;
1002

    
1003
      while( initBitmap!=rowBitmap )
1004
        {
1005
        initBitmap = rowBitmap;
1006

    
1007
        for(int cubit=0; cubit<mNumCubits; cubit++)
1008
          {
1009
          bitmap = mCubits[cubit].getRotRow(axis);
1010
          if( (rowBitmap & bitmap) != 0 ) rowBitmap |= bitmap;
1011
          }
1012
        }
1013
      }
1014

    
1015
    return rowBitmap;
1016
    }
1017

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

    
1022
  void clampPos(float[] pos, int offset)
1023
    {
1024
    float currError, minError = Float.MAX_VALUE;
1025
    int minErrorIndex1 = -1;
1026
    int minErrorIndex2 = -1;
1027

    
1028
    float x = pos[offset  ];
1029
    float y = pos[offset+1];
1030
    float z = pos[offset+2];
1031

    
1032
    float xo,yo,zo;
1033

    
1034
    for(int i=0; i<mNumCubits; i++)
1035
      {
1036
      int len = mOrigPos[i].length / 3;
1037

    
1038
      for(int j=0; j<len; j++)
1039
        {
1040
        xo = mOrigPos[i][3*j  ];
1041
        yo = mOrigPos[i][3*j+1];
1042
        zo = mOrigPos[i][3*j+2];
1043

    
1044
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
1045

    
1046
        if( currError<minError )
1047
          {
1048
          minError = currError;
1049
          minErrorIndex1 = i;
1050
          minErrorIndex2 = j;
1051
          }
1052
        }
1053
      }
1054

    
1055
    if( minError< 0.1f ) // TODO: 0.1 ?
1056
      {
1057
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
1058
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
1059
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
1060
      }
1061
    }
1062

    
1063
///////////////////////////////////////////////////////////////////////////////////////////////////
1064
// remember about the double cover or unit quaternions!
1065

    
1066
  int mulQuat(int q1, int q2)
1067
    {
1068
    Static4D result = QuatHelper.quatMultiply(mObjectQuats[q1],mObjectQuats[q2]);
1069

    
1070
    float rX = result.get0();
1071
    float rY = result.get1();
1072
    float rZ = result.get2();
1073
    float rW = result.get3();
1074

    
1075
    final float MAX_ERROR = 0.1f;
1076
    float dX,dY,dZ,dW;
1077

    
1078
    for(int i=0; i<mNumQuats; i++)
1079
      {
1080
      dX = mObjectQuats[i].get0() - rX;
1081
      dY = mObjectQuats[i].get1() - rY;
1082
      dZ = mObjectQuats[i].get2() - rZ;
1083
      dW = mObjectQuats[i].get3() - rW;
1084

    
1085
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
1086
          dY<MAX_ERROR && dY>-MAX_ERROR &&
1087
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
1088
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
1089

    
1090
      dX = mObjectQuats[i].get0() + rX;
1091
      dY = mObjectQuats[i].get1() + rY;
1092
      dZ = mObjectQuats[i].get2() + rZ;
1093
      dW = mObjectQuats[i].get3() + rW;
1094

    
1095
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
1096
          dY<MAX_ERROR && dY>-MAX_ERROR &&
1097
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
1098
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
1099
      }
1100

    
1101
    return -1;
1102
    }
1103

    
1104
///////////////////////////////////////////////////////////////////////////////////////////////////
1105

    
1106
  private float getAngle()
1107
    {
1108
    int pointNum = mRotationAngle.getNumPoints();
1109

    
1110
    if( pointNum>=1 )
1111
      {
1112
      return mRotationAngle.getPoint(pointNum-1).get0();
1113
      }
1114
    else
1115
      {
1116
      mInterface.reportProblem("points in RotationAngle: "+pointNum, false);
1117
      return 0;
1118
      }
1119
    }
1120

    
1121
///////////////////////////////////////////////////////////////////////////////////////////////////
1122

    
1123
  void setLibInterface(ObjectLibInterface inter)
1124
    {
1125
    mInterface = inter;
1126
    }
1127

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

    
1130
  void initializeObject(int[][] moves)
1131
    {
1132
    solve();
1133
    setupPosition(moves);
1134
    }
1135

    
1136
///////////////////////////////////////////////////////////////////////////////////////////////////
1137

    
1138
  synchronized void removeRotationNow()
1139
    {
1140
    float angle = getAngle();
1141
    double nearestAngleInRadians = angle*Math.PI/180;
1142
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
1143
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
1144
    float axisX = mAxis[mCurrentRotAxis].get0();
1145
    float axisY = mAxis[mCurrentRotAxis].get1();
1146
    float axisZ = mAxis[mCurrentRotAxis].get2();
1147
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
1148

    
1149
    mRotationAngle.removeAll();
1150
    mRotationAngleStatic.set0(0);
1151

    
1152
    for(int i=0; i<mNumCubits; i++)
1153
      if( belongsToRotation(i, mCurrentRotAxis,mRotRowBitmap) )
1154
        {
1155
        int index = mCubits[i].removeRotationNow(quat);
1156
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),index);
1157
        }
1158
    }
1159

    
1160
///////////////////////////////////////////////////////////////////////////////////////////////////
1161

    
1162
  long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
1163
    {
1164
    if( wasRotateApplied() )
1165
      {
1166
      float angle = getAngle();
1167
      mRotationAngleStatic.set0(angle);
1168
      mRotationAngleFinal.set0(nearestAngleInDegrees);
1169
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
1170

    
1171
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
1172
      mRotationAngle.resetToBeginning();
1173
      mRotationAngle.removeAll();
1174
      mRotationAngle.add(mRotationAngleStatic);
1175
      mRotationAngle.add(mRotationAngleMiddle);
1176
      mRotationAngle.add(mRotationAngleFinal);
1177
      mRotateEffect.notifyWhenFinished(listener);
1178

    
1179
      return mRotateEffect.getID();
1180
      }
1181

    
1182
    return 0;
1183
    }
1184

    
1185
///////////////////////////////////////////////////////////////////////////////////////////////////
1186

    
1187
  synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
1188
    {
1189
    if( wasRotateApplied() )
1190
      {
1191
      mCurrentRotAxis = axis;
1192
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
1193

    
1194
      mRotationAngleStatic.set0(0.0f);
1195
      mRotationAxis.set( mAxis[axis] );
1196
      mRotationAngle.setDuration(durationMillis);
1197
      mRotationAngle.resetToBeginning();
1198
      mRotationAngle.add(new Static1D(0));
1199
      mRotationAngle.add(new Static1D(angle));
1200
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1201
      mRotateEffect.notifyWhenFinished(listener);
1202

    
1203
      return mRotateEffect.getID();
1204
      }
1205

    
1206
    return 0;
1207
    }
1208

    
1209
///////////////////////////////////////////////////////////////////////////////////////////////////
1210

    
1211
  void continueRotation(float angleInDegrees)
1212
    {
1213
    mRotationAngleStatic.set0(angleInDegrees);
1214
    }
1215

    
1216
///////////////////////////////////////////////////////////////////////////////////////////////////
1217

    
1218
  synchronized void beginNewRotation(int axis, int row )
1219
    {
1220
    if( axis<0 || axis>=mNumAxis )
1221
      {
1222
      android.util.Log.e("object", "invalid rotation axis: "+axis);
1223
      return;
1224
      }
1225
    if( row<0 || row>=mNumLayers[axis] )
1226
      {
1227
      android.util.Log.e("object", "invalid rotation row: "+row);
1228
      return;
1229
      }
1230

    
1231
    mCurrentRotAxis = axis;
1232
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
1233
    mRotationAngleStatic.set0(0.0f);
1234
    mRotationAxis.set( mAxis[axis] );
1235
    mRotationAngle.add(mRotationAngleStatic);
1236
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1237
    }
1238

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

    
1241
  void setTextureMap(int cubit, int face, int newColor)
1242
    {
1243
    final float ratioW = 1.0f/mNumTexCols;
1244
    final float ratioH = 1.0f/mNumTexRows;
1245
    final Static4D[] maps = new Static4D[mNumCubitFaces];
1246
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
1247
    int col = newColor%mNumTexCols;
1248

    
1249
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1250
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1251
    }
1252

    
1253
///////////////////////////////////////////////////////////////////////////////////////////////////
1254

    
1255
  private int getCubitFaceColor(int cubit, int face)
1256
    {
1257
    int puzzleFace = getCubitFaceMap(cubit,face);
1258
    if( puzzleFace>=0 ) puzzleFace %= mNumFaceColors;
1259
    return puzzleFace;
1260
    }
1261

    
1262
///////////////////////////////////////////////////////////////////////////////////////////////////
1263

    
1264
  public int getCubitFaceMap(int cubit, int face)
1265
    {
1266
    int numFaces = mCubitFaceColors[cubit].length;
1267
    int puzzleFace = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
1268
    return puzzleFace<0 ? -1 : puzzleFace;
1269
    }
1270

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

    
1273
  void resetAllTextureMaps()
1274
    {
1275
    final float ratioW = 1.0f/mNumTexCols;
1276
    final float ratioH = 1.0f/mNumTexRows;
1277
    int cubColor, varColor, color, variant, row, col;
1278

    
1279
    for(int cubit=0; cubit<mNumCubits; cubit++)
1280
      {
1281
      final Static4D[] maps = new Static4D[mNumCubitFaces];
1282
      variant = getCubitVariant(cubit,mNumLayers);
1283

    
1284
      for(int face=0; face<mNumCubitFaces; face++)
1285
        {
1286
        cubColor = getCubitFaceColor(cubit,face);
1287
        varColor = getVariantFaceColor(variant,face);
1288
        color    = cubColor<0 || varColor<0 ? mNumTextures : varColor*mNumFaceColors + cubColor;
1289
        row      = (mNumTexRows-1) - color/mNumTexCols;
1290
        col      = color%mNumTexCols;
1291

    
1292
        maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1293
        }
1294

    
1295
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1296
      }
1297
    }
1298

    
1299
///////////////////////////////////////////////////////////////////////////////////////////////////
1300

    
1301
  void releaseResources()
1302
    {
1303
    mTexture.markForDeletion();
1304
    mMesh.markForDeletion();
1305
    mEffects.markForDeletion();
1306

    
1307
    for(int j=0; j<mNumCubits; j++)
1308
      {
1309
      mCubits[j].releaseResources();
1310
      }
1311
    }
1312

    
1313
///////////////////////////////////////////////////////////////////////////////////////////////////
1314

    
1315
  synchronized void restorePreferences(SharedPreferences preferences)
1316
    {
1317
    boolean error = false;
1318
    String key = getShortName();
1319

    
1320
    for(int i=0; i<mNumCubits; i++)
1321
      {
1322
      mQuatDebug[i] = mCubits[i].restorePreferences(key,i,preferences);
1323

    
1324
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<mNumQuats )
1325
        {
1326
        mCubits[i].modifyCurrentPosition(mObjectQuats[mQuatDebug[i]]);
1327
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),mQuatDebug[i]);
1328
        }
1329
      else
1330
        {
1331
        error = true;
1332
        }
1333
      }
1334

    
1335
    if( error )
1336
      {
1337
      for(int i=0; i<mNumCubits; i++)
1338
        {
1339
        mCubits[i].solve();
1340
        mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(),0);
1341
        }
1342
      }
1343
    }
1344

    
1345
///////////////////////////////////////////////////////////////////////////////////////////////////
1346

    
1347
  void savePreferences(SharedPreferences.Editor editor)
1348
    {
1349
    String key = getShortName();
1350
    for(int i=0; i<mNumCubits; i++) mCubits[i].savePreferences(key,i,editor);
1351
    }
1352

    
1353
///////////////////////////////////////////////////////////////////////////////////////////////////
1354

    
1355
  private float computeRadiusCorrection(float[] sticker, int curr, int len)
1356
    {
1357
    final float A = 0.8f;  // 0<A<1
1358

    
1359
    int prev = curr>0 ? curr-1 : len-1;
1360
    int next = curr<len-1 ? curr+1 : 0;
1361

    
1362
    float v1x = sticker[2*prev  ]-sticker[2*curr  ];
1363
    float v1y = sticker[2*prev+1]-sticker[2*curr+1];
1364
    float v2x = sticker[2*next  ]-sticker[2*curr  ];
1365
    float v2y = sticker[2*next+1]-sticker[2*curr+1];
1366

    
1367
    float len1= v1x*v1x+v1y*v1y;
1368
    float len2= v2x*v2x+v2y*v2y;
1369

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

    
1372
    return 1-A*cos;
1373
    }
1374

    
1375
///////////////////////////////////////////////////////////////////////////////////////////////////
1376

    
1377
  public ObjectSticker retSticker(int sticker)
1378
    {
1379
    if( mStickers==null )
1380
      {
1381
      float rad = getStickerRadius();
1382
      float str = getStickerStroke();
1383
      float[][] angles = getStickerAngles();
1384
      int numStickers = mStickerCoords.length;
1385
      mStickers = new ObjectSticker[numStickers];
1386

    
1387
      for(int s=0; s<numStickers; s++)
1388
        {
1389
        float scale = mStickerScales[s];
1390
        float radius = rad / scale;
1391
        float stroke = str / scale;
1392
        int len = mStickerCoords[s].length/2;
1393
        float[] radii = new float[len];
1394
        for(int r=0; r<len; r++) radii[r] = radius*computeRadiusCorrection(mStickerCoords[s],r,len);
1395
        mStickers[s] = new ObjectSticker(mStickerCoords[s],angles==null ? null : angles[s],radii,stroke);
1396
        }
1397
      }
1398

    
1399
    return mStickers[sticker];
1400
    }
1401

    
1402
///////////////////////////////////////////////////////////////////////////////////////////////////
1403
// some objects (currently Kilominx,Ivy,Rex) might want to change the stickers.
1404

    
1405
  public void adjustStickerCoords()
1406
    {
1407

    
1408
    }
1409

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

    
1412
  public Static4D[] getQuats()
1413
    {
1414
    if( mObjectQuats==null )
1415
      {
1416
      mObjectQuats = QuatGroupGenerator.computeGroup(mAxis,mBasicAngles);
1417
      }
1418

    
1419
    return mObjectQuats;
1420
    }
1421

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

    
1424
  public int getInternalColor()
1425
    {
1426
    return COLOR_INTERNAL;
1427
    }
1428

    
1429
///////////////////////////////////////////////////////////////////////////////////////////////////
1430
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
1431

    
1432
  private void createTexture()
1433
    {
1434
    Paint paint = new Paint();
1435
    mBitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_4444);
1436
    Canvas canvas = new Canvas(mBitmap);
1437

    
1438
    paint.setAntiAlias(true);
1439
    paint.setTextAlign(Paint.Align.CENTER);
1440
    paint.setStyle(Paint.Style.FILL);
1441

    
1442
    paint.setColor(getInternalColor());
1443
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
1444

    
1445
    int texture = 0;
1446
    FactorySticker factory = FactorySticker.getInstance();
1447

    
1448
    for(int row=0; row<mNumTexRows; row++)
1449
      for(int col=0; col<mNumTexCols; col++)
1450
        {
1451
        if( texture>=mNumTextures ) break;
1452
        ObjectSticker sticker = retSticker(texture/mNumFaceColors);
1453
        int color = getColor(texture% mNumFaceColors);
1454
        factory.drawRoundedPolygon(canvas, paint, col*TEXTURE_HEIGHT, (mNumTexRows-row)*TEXTURE_HEIGHT, color, sticker);
1455
        texture++;
1456
        }
1457
    }
1458

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

    
1461
  void setTexture()
1462
    {
1463
    if( mBitmap==null ) createTexture();
1464

    
1465
    if( !mTexture.setTextureAlreadyInverted(mBitmap) )
1466
      {
1467
      int max = DistortedLibrary.getMaxTextureSize();
1468
      mInterface.reportProblem("failed to set texture of size "+mBitmap.getWidth()+"x"+mBitmap.getHeight()+" max is "+max, true);
1469
      }
1470
    }
1471

    
1472
///////////////////////////////////////////////////////////////////////////////////////////////////
1473

    
1474
  void setObjectRatioNow(float sc, int nodeSize)
1475
    {
1476
    mObjectScreenRatio = sc;
1477
    float scale = mObjectScreenRatio*mInitScreenRatio*nodeSize/mSize;
1478
    mObjectScale.set(scale,scale,scale);
1479

    
1480
    if( mTouchControl ==null ) mTouchControl = getTouchControl();
1481
    mTouchControl.setObjectRatio(mObjectScreenRatio*mInitScreenRatio);
1482
    }
1483

    
1484
///////////////////////////////////////////////////////////////////////////////////////////////////
1485

    
1486
  void setObjectRatio(float sizeChange, int nodeSize)
1487
    {
1488
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
1489

    
1490
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
1491
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
1492

    
1493
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1494
    }
1495

    
1496
///////////////////////////////////////////////////////////////////////////////////////////////////
1497

    
1498
  void setNodeSize(int nodeSize)
1499
    {
1500
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1501
    }
1502

    
1503
///////////////////////////////////////////////////////////////////////////////////////////////////
1504

    
1505
  public float getRatio()
1506
    {
1507
    return mObjectScreenRatio;
1508
    }
1509

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

    
1512
  public float getObjectRatio()
1513
    {
1514
    return mObjectScreenRatio*mInitScreenRatio;
1515
    }
1516

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

    
1519
  boolean isSolved()
1520
    {
1521
    if( mSolvedFunctionIndex==0 ) return isSolved0();
1522
    if( mSolvedFunctionIndex==1 ) return isSolved1();
1523

    
1524
    return false;
1525
    }
1526

    
1527
///////////////////////////////////////////////////////////////////////////////////////////////////
1528

    
1529
  int computeNearestAngle(int axis, float angle, float speed)
1530
    {
1531
    int basicAngle   = mBasicAngles[axis>=mBasicAngles.length ? 0 : axis];
1532
    int nearestAngle = 360/basicAngle;
1533

    
1534
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
1535
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
1536

    
1537
    if( tmp!=0 ) return nearestAngle*tmp;
1538

    
1539
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
1540
    }
1541

    
1542
///////////////////////////////////////////////////////////////////////////////////////////////////
1543
// INTERNAL API - those are called from 'effects' package
1544
///////////////////////////////////////////////////////////////////////////////////////////////////
1545

    
1546
  public void randomizeNewScramble(int[][] scramble, Random rnd, int curr, int total)
1547
    {
1548
    mScrambler.randomizeNewScramble(scramble,rnd,curr,total);
1549
    }
1550

    
1551
///////////////////////////////////////////////////////////////////////////////////////////////////
1552

    
1553
  public Static4D getRotationQuat()
1554
    {
1555
    return mQuat;
1556
    }
1557

    
1558
///////////////////////////////////////////////////////////////////////////////////////////////////
1559

    
1560
  public float getSize()
1561
    {
1562
    return mSize;
1563
    }
1564

    
1565
///////////////////////////////////////////////////////////////////////////////////////////////////
1566

    
1567
  public void apply(Effect effect, int position)
1568
    {
1569
    mEffects.apply(effect, position);
1570
    }
1571

    
1572
///////////////////////////////////////////////////////////////////////////////////////////////////
1573

    
1574
  public void remove(long effectID)
1575
    {
1576
    mEffects.abortById(effectID);
1577
    }
1578

    
1579
///////////////////////////////////////////////////////////////////////////////////////////////////
1580

    
1581
  public MeshBase getObjectMesh()
1582
    {
1583
    return mMesh;
1584
    }
1585

    
1586
///////////////////////////////////////////////////////////////////////////////////////////////////
1587

    
1588
  public DistortedEffects getObjectEffects()
1589
    {
1590
    return mEffects;
1591
    }
1592

    
1593
///////////////////////////////////////////////////////////////////////////////////////////////////
1594
// PUBLIC API
1595
///////////////////////////////////////////////////////////////////////////////////////////////////
1596

    
1597
  public int getCubitFaceColorIndex(int cubit, int face)
1598
    {
1599
    Static4D texMap = mMesh.getTextureMap(mNumFaceColors *cubit + face);
1600

    
1601
    int x = (int)(texMap.get0()/texMap.get2());
1602
    int y = (int)(texMap.get1()/texMap.get3());
1603

    
1604
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
1605
    }
1606

    
1607
///////////////////////////////////////////////////////////////////////////////////////////////////
1608

    
1609
  public int[] getNumLayers()
1610
    {
1611
    return mNumLayers;
1612
    }
1613

    
1614
///////////////////////////////////////////////////////////////////////////////////////////////////
1615

    
1616
  public synchronized void solve()
1617
    {
1618
    for(int i=0; i<mNumCubits; i++)
1619
      {
1620
      mCubits[i].solve();
1621
      mMesh.setEffectAssociation(i, mCubits[i].computeAssociation(), 0);
1622
      }
1623
    }
1624

    
1625
///////////////////////////////////////////////////////////////////////////////////////////////////
1626

    
1627
  public int getCubitQuatIndex(int cubit)
1628
    {
1629
    return (cubit>=0 && cubit<mNumCubits) ? mCubits[cubit].mQuatIndex : 0;
1630
    }
1631

    
1632
///////////////////////////////////////////////////////////////////////////////////////////////////
1633

    
1634
  public int getCubitRotRow(int cubit, int axis)
1635
    {
1636
    return mCubits[cubit].getRotRow(axis);
1637
    }
1638

    
1639
///////////////////////////////////////////////////////////////////////////////////////////////////
1640

    
1641
  public Bitmap getStickerBitmap()
1642
    {
1643
    return mBitmap;
1644
    }
1645

    
1646
///////////////////////////////////////////////////////////////////////////////////////////////////
1647

    
1648
  public DistortedNode getNode()
1649
    {
1650
    return mNode;
1651
    }
1652

    
1653
///////////////////////////////////////////////////////////////////////////////////////////////////
1654

    
1655
  public int getNumStickerTypes()
1656
    {
1657
    return mNumStickerTypes;
1658
    }
1659

    
1660
///////////////////////////////////////////////////////////////////////////////////////////////////
1661
// this is here only so it can be overridden in TwistyJSON soo that we can get this from JSON.
1662

    
1663
  public int getNumCubitFaces()
1664
    {
1665
    return 0;
1666
    }
1667

    
1668
///////////////////////////////////////////////////////////////////////////////////////////////////
1669

    
1670
  public TouchControl getTouchControl()
1671
    {
1672
    if( mTouchControl==null )
1673
      {
1674
      switch(getTouchControlType())
1675
        {
1676
        case TC_TETRAHEDRON      : mTouchControl = new TouchControlTetrahedron(this);
1677
                                   break;
1678
        case TC_HEXAHEDRON       : mTouchControl = new TouchControlHexahedron(this);
1679
                                   break;
1680
        case TC_OCTAHEDRON       : mTouchControl = new TouchControlOctahedron(this);
1681
                                   break;
1682
        case TC_DODECAHEDRON     : mTouchControl = new TouchControlDodecahedron(this);
1683
                                   break;
1684
        case TC_CUBOID           : int[] numLayers = getNumLayers();
1685
                                   mTouchControl = new TouchControlCuboids(this,getDist3D(numLayers));
1686
                                   break;
1687
        case TC_CHANGING_MIRROR  : mTouchControl = new TouchControlMirror(this);
1688
                                   break;
1689
        case TC_CHANGING_SQUARE  : mTouchControl = new TouchControlSquare(this);
1690
                                   break;
1691
        case TC_CHANGING_SHAPEMOD: mTouchControl = new TouchControlShapemod(this);
1692
                                   break;
1693
        }
1694
      }
1695
    return mTouchControl;
1696
    }
1697

    
1698
///////////////////////////////////////////////////////////////////////////////////////////////////
1699

    
1700
  protected void setReader(JsonReader reader)
1701
    {
1702
    // empty
1703
    }
1704

    
1705
///////////////////////////////////////////////////////////////////////////////////////////////////
1706
  // for JSON only
1707
  public abstract int getTouchControlType();
1708
  public abstract int getTouchControlSplit();
1709
  public abstract boolean[][] getLayerRotatable(int[] numLayers);
1710
  public abstract int[][][] getEnabled();
1711
  public abstract float[] getDist3D(int[] numLayers);
1712
  public abstract Static3D[] getFaceAxis();
1713
  public abstract ScrambleState[] getScrambleStates();
1714
  public abstract float[][] getCuts(int[] numLayers);
1715
  public abstract float getStickerRadius();
1716
  public abstract float getStickerStroke();
1717
  public abstract float[][] getStickerAngles();
1718
  public abstract int getCubitVariant(int cubit, int[] numLayers);
1719
  public abstract ObjectShape getObjectShape(int variant);
1720
  public abstract ObjectFaceShape getObjectFaceShape(int variant);
1721
  public abstract int getNumCubitVariants(int[] numLayers);
1722
  public abstract float[][] getCubitPositions(int[] numLayers);
1723
  public abstract Static4D getCubitQuats(int cubit, int[] numLayers);
1724
  public abstract int getNumFaceColors();
1725
  public abstract float getScreenRatio();
1726
  public abstract int getColor(int face);
1727
  public abstract String getShortName();
1728
  public abstract long getSignature();
1729

    
1730
  // not only for JSON
1731
  public abstract Static3D[] getRotationAxis();
1732
  public abstract int[] getBasicAngles();
1733
  public abstract int getNumFaces();
1734
  public abstract String getObjectName();
1735
  public abstract String getInventor();
1736
  public abstract int getYearOfInvention();
1737
  public abstract int getComplexity();
1738
  public abstract int getFOV();
1739
  public abstract String[][] getTutorials();
1740
  }
(11-11/12)