Project

General

Profile

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

distorted-objectlib / src / main / java / org / distorted / objectlib / main / TwistyObject.java @ 00a28d71

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

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

    
67
///////////////////////////////////////////////////////////////////////////////////////////////////
68

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

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

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

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

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

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

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

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

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

    
154
  //////////////////// SOLVED1 ////////////////////////
155

    
156
  private int[] mFaceMap;
157
  private int[][] mScramble;
158
  private int[] mColors;
159

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

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

    
168
    mNumLayers = reader.getNumLayers();
169
    mSize      = reader.getSize();
170
    initialize(meshState,iconMode,quat,move,scale,meshStream,true);
171
    }
172

    
173
///////////////////////////////////////////////////////////////////////////////////////////////////
174

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

    
182
///////////////////////////////////////////////////////////////////////////////////////////////////
183

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

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

    
206
    mNumCubits = mOrigPos.length;
207
    mNumFaceColors = getNumFaceColors();
208
    mNumAxis = mAxis.length;
209

    
210
    int scramblingType = getScrambleType();
211
    ScrambleState[] states = getScrambleStates();
212
    mScrambler = new ObjectScrambler(scramblingType, mNumAxis,mNumLayers,states);
213

    
214
    boolean bandaged=false;
215

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

    
227
    mRotationAngle= new Dynamic1D();
228
    mRotationAxis = new Static3D(1,0,0);
229
    mRotateEffect = new VertexEffectRotate(mRotationAngle, mRotationAxis, CENTER);
230

    
231
    mRotationAngleStatic = new Static1D(0);
232
    mRotationAngleMiddle = new Static1D(0);
233
    mRotationAngleFinal  = new Static1D(0);
234

    
235
    mObjectScale = new Static3D(scale,scale,scale);
236
    setObjectRatioNow(scale,720);
237

    
238
    mEffects = new DistortedEffects();
239
    createQuaternionEffects();
240

    
241
    MatrixEffectScale scaleEffect = new MatrixEffectScale(mObjectScale);
242
    MatrixEffectQuaternion quatEffect = new MatrixEffectQuaternion(mQuat, CENTER);
243
    MatrixEffectMove moveEffect = new MatrixEffectMove(move);
244

    
245
    boolean fromDMESH = (stream!=null && meshState==MESH_NICE);
246
    getQuatsAndShapes(fromDMESH,fromJSON);
247
    createMeshAndCubits(stream,meshState,fromDMESH);
248
    setUpTextures(fromDMESH,fromJSON);
249
    createDataStructuresForSolved();
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 void createQuaternionEffects()
262
    {
263
    if( mNumQuats<=ObjectControl.MAX_QUATS )
264
      {
265
      mIsInMixupMode = false;
266

    
267
      for( int q=0; q<mNumQuats; q++)
268
        {
269
        VertexEffectQuaternion vq = new VertexEffectQuaternion(mObjectQuats[q],CENTER);
270
        vq.setMeshAssociation(0,q);
271
        mEffects.apply(vq);
272
        }
273
      }
274
    else if( mNumCubits<=ObjectControl.MAX_QUATS )
275
      {
276
      mIsInMixupMode = true;
277
      mMixupModeQuats = new Static4D[mNumCubits];
278

    
279
      for( int q=0; q<mNumCubits; q++)
280
        {
281
        mMixupModeQuats[q] = new Static4D(mObjectQuats[0]);
282
        VertexEffectQuaternion vq = new VertexEffectQuaternion(mMixupModeQuats[q],CENTER);
283
        vq.setMeshAssociation(0,q);
284
        mEffects.apply(vq);
285
        }
286
      }
287
    else
288
      {
289
      android.util.Log.e("D", "object has too many quaternions ("+mNumQuats+") or too many cubits ("+mNumCubits+")");
290
      }
291
    }
292

    
293
///////////////////////////////////////////////////////////////////////////////////////////////////
294

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

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

    
309
    sumX /= len;
310
    sumY /= len;
311
    sumZ /= len;
312

    
313
    return new Static3D(sumX,sumY,sumZ);
314
    }
315

    
316
///////////////////////////////////////////////////////////////////////////////////////////////////
317

    
318
  private void createOuterFaces()
319
    {
320
    for(int v=0; v<mNumCubitVariants; v++)
321
      {
322
      int[][] indices = mShapes[v].getVertIndices();
323
      int faces = indices.length;
324
      mVariantFaceIsOuter[v] = new int[faces];
325
      }
326

    
327
    for( int cubit=0; cubit<mNumCubits; cubit++)
328
      {
329
      int variant = getCubitVariant(cubit,mNumLayers);
330
      int[][] indices = mShapes[variant].getVertIndices();
331
      int numFaces = indices.length;
332

    
333
      for(int face=0; face<numFaces; face++)
334
        if( getCubitFaceColor(cubit,face)>=0 )
335
          {
336
          mVariantFaceIsOuter[variant][face] = 1;
337
          }
338
      }
339
    }
340

    
341
///////////////////////////////////////////////////////////////////////////////////////////////////
342

    
343
  private void getQuatsAndShapes(boolean fromDMESH, boolean fromJSON)
344
    {
345
    mNumCubitVariants = getNumCubitVariants(mNumLayers);
346

    
347
    if( !fromDMESH || !fromJSON )
348
      {
349
      FactoryCubit factory = FactoryCubit.getInstance();
350
      factory.clear();
351

    
352
      mOrigQuat = new Static4D[mNumCubits];
353
      for(int i=0; i<mNumCubits; i++) mOrigQuat[i] = getCubitQuats(i,mNumLayers);
354

    
355
      mShapes = new ObjectShape[mNumCubitVariants];
356
      for(int i=0; i<mNumCubitVariants; i++) mShapes[i] = getObjectShape(i);
357
      mNumCubitFaces = ObjectShape.computeNumComponents(mShapes);
358
      mVariantFaceIsOuter = new int[mNumCubitVariants][];
359

    
360
      if( !fromJSON )
361
        {
362
        mCubitFaceColors = ObjectShape.computeColors(mShapes,mOrigPos,mOrigQuat,this);
363
        createOuterFaces();
364
        }
365

    
366
      if( fromDMESH )
367
        {
368
        for(int i=0; i<mNumCubitVariants; i++) factory.createNewFaceTransform(mShapes[i], mVariantFaceIsOuter[i]);
369
        }
370
      }
371
    }
372

    
373
///////////////////////////////////////////////////////////////////////////////////////////////////
374

    
375
  private void createMeshAndCubits(InputStream stream, int meshState, boolean fromDMESH)
376
    {
377
    mCubits = new Cubit[mNumCubits];
378

    
379
    if( fromDMESH )
380
      {
381
      DataInputStream dos = new DataInputStream(stream);
382
      mMesh = new MeshFile(dos);
383

    
384
      try
385
        {
386
        stream.close();
387
        }
388
      catch(IOException e)
389
        {
390
        android.util.Log.e("meshFile", "Error closing InputStream: "+e.toString());
391
        }
392
      }
393
    else
394
      {
395
      MeshBase[] cubitMesh = new MeshBase[mNumCubits];
396

    
397
      for(int i=0; i<mNumCubits; i++)
398
        {
399
        cubitMesh[i] = createCubitMesh(i,mNumLayers,meshState,mNumCubitFaces);
400
        Static3D pos = getPos(mOrigPos[i]);
401
        cubitMesh[i].apply(new MatrixEffectMove(pos),1,0);
402
        }
403

    
404
      mMesh = new MeshJoined(cubitMesh);
405
      }
406

    
407
    for(int i=0; i<mNumCubits; i++)
408
      {
409
      mCubits[i] = new Cubit(this,mOrigPos[i], mNumAxis);
410
      setCubitQuat(i,mCubits[i].computeAssociation(),0);
411
      }
412
    }
413

    
414
///////////////////////////////////////////////////////////////////////////////////////////////////
415

    
416
  private MeshBase createCubitMesh(int cubit, int[] numLayers, int meshState, int numComponents)
417
    {
418
    int variant = getCubitVariant(cubit,numLayers);
419

    
420
    if( mMeshes==null ) mMeshes = new MeshBase[mNumCubitVariants];
421

    
422
    if( mMeshes[variant]==null )
423
      {
424
      ObjectFaceShape faceShape = getObjectFaceShape(variant);
425
      FactoryCubit factory = FactoryCubit.getInstance();
426
      factory.createNewFaceTransform(mShapes[variant],mVariantFaceIsOuter[variant]);
427
      mMeshes[variant] = factory.createRoundedSolid(mShapes[variant],faceShape,meshState, numComponents);
428
      }
429

    
430
    MeshBase mesh = mMeshes[variant].copy(true);
431
    MatrixEffectQuaternion quat = new MatrixEffectQuaternion( mOrigQuat[cubit], CENTER );
432
    mesh.apply(quat,0xffffffff,0);
433

    
434
    return mesh;
435
    }
436

    
437
///////////////////////////////////////////////////////////////////////////////////////////////////
438

    
439
  private void setUpTextures(boolean fromDMESH, boolean fromJSON)
440
    {
441
    mTexture = new DistortedTexture();
442

    
443
    if( fromJSON )
444
      {
445
      mNumStickerTypes = getNumStickerTypes();
446
      mNumCubitFaces = getNumCubitFaces();
447
      }
448
    else
449
      {
450
      FactoryCubit factory = FactoryCubit.getInstance();
451
      mStickerCoords   = factory.getStickerCoords();
452
      mStickerVariants = factory.getStickerVariants();
453
      mStickerScales   = factory.getStickerScales();
454
      adjustStickerCoords();
455
      mNumStickerTypes = (mStickerCoords==null ? 0 : mStickerCoords.length);
456
      }
457

    
458
    mNumTextures= mNumFaceColors *mNumStickerTypes;
459
    mNumTexCols = NUM_STICKERS_IN_ROW;
460
    mNumTexRows = (mNumTextures+1)/NUM_STICKERS_IN_ROW;
461
    if( mNumTexCols*mNumTexRows < mNumTextures+1 ) mNumTexRows++;
462

    
463
    if( !fromDMESH || shouldResetTextureMaps() ) resetAllTextureMaps();
464
    setTexture();
465
    }
466

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

    
469
  private int getMultQuat(int index1, int index2)
470
    {
471
    if( mQuatMult==null )
472
      {
473
      mQuatMult = new int[mNumQuats][mNumQuats];
474

    
475
      for(int i=0; i<mNumQuats; i++)
476
        for(int j=0; j<mNumQuats; j++) mQuatMult[i][j] = -1;
477
      }
478

    
479
    if( mQuatMult[index1][index2]==-1 )
480
      {
481
      mQuatMult[index1][index2] = mulQuat(index1,index2);
482
      }
483

    
484
    return mQuatMult[index1][index2];
485
    }
486

    
487
///////////////////////////////////////////////////////////////////////////////////////////////////
488

    
489
  public boolean isInIconMode()
490
    {
491
    return mIconMode==MODE_ICON;
492
    }
493

    
494
///////////////////////////////////////////////////////////////////////////////////////////////////
495

    
496
  public int getVariantFaceColor(int variant, int face)
497
    {
498
    return face>=mStickerVariants[variant].length ? -1 : mStickerVariants[variant][face];
499
    }
500

    
501
///////////////////////////////////////////////////////////////////////////////////////////////////
502

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

    
508
///////////////////////////////////////////////////////////////////////////////////////////////////
509

    
510
  private void createDataStructuresForSolved()
511
    {
512
    mTmpQuats = new int[mNumQuats];
513
    mSolvedQuats = getSolvedQuats();
514
    }
515

    
516
///////////////////////////////////////////////////////////////////////////////////////////////////
517
// This is used to build internal data structures for the generic 'isSolved()'
518
//
519
// if this is an internal cubit (all faces black): return -1
520
// if this is a face cubit (one non-black face): return the color index of the only non-black face.
521
// Color index, i.e. the index into the 'FACE_COLORS' table.
522
// else (edge or corner cubit, more than one non-black face): return -2.
523

    
524
  protected int retCubitSolvedStatus(int cubit)
525
    {
526
    int numNonBlack=0, nonBlackIndex=-1, varColor, cubColor;
527
    int variant = getCubitVariant(cubit,mNumLayers);
528

    
529
    for(int face=0; face<mNumCubitFaces; face++)
530
      {
531
      varColor = getVariantFaceColor(variant,face);
532
      int numFaces = mCubitFaceColors[cubit].length;
533
      cubColor = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
534

    
535
      if( varColor>=0 && cubColor>=0 )
536
        {
537
        numNonBlack++;
538
        nonBlackIndex = cubColor;
539
        }
540
      }
541

    
542
    if( numNonBlack==0 ) return -1;
543
    if( numNonBlack>=2 ) return -2;
544

    
545
    return nonBlackIndex;
546
    }
547

    
548
///////////////////////////////////////////////////////////////////////////////////////////////////
549

    
550
  private boolean sticksOut(Static3D[] faceAxis, float[] dist, float x, float y, float z )
551
    {
552
    final float MAXERR = 0.05f;
553
    int numAxis = dist.length;
554

    
555
    for(int i=0; i<numAxis; i++)
556
      {
557
      Static3D ax = faceAxis[i];
558
      float len = ax.get0()*x + ax.get1()*y + ax.get2()*z;
559
      if( len>mSize*dist[i]+MAXERR ) return true;
560
      }
561

    
562
    return false;
563
    }
564

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

    
567
  private boolean doesNotStickOut(int variant, float px, float py, float pz, float[] tmp, Static4D quat)
568
    {
569
    ObjectShape shape = getObjectShape(variant);
570
    float[][] vertices = shape.getVertices();
571
    Static3D[] axis = getFaceAxis();
572
    float[] dist3D = getDist3D(mNumLayers);
573

    
574
    for( float[] vertex : vertices)
575
      {
576
      float x = vertex[0];
577
      float y = vertex[1];
578
      float z = vertex[2];
579

    
580
      QuatHelper.rotateVectorByQuat(tmp, x, y, z, 1, quat);
581

    
582
      float mx = tmp[0] + px;
583
      float my = tmp[1] + py;
584
      float mz = tmp[2] + pz;
585

    
586
      if( sticksOut(axis, dist3D, mx,my,mz) ) return false;
587
      }
588

    
589
    return true;
590
    }
591

    
592
///////////////////////////////////////////////////////////////////////////////////////////////////
593

    
594
  private float computeAvg(float[] pos, int offset)
595
    {
596
    int len = pos.length/3;
597
    float ret=0.0f;
598
    for(int i=0; i<len; i++) ret += pos[3*i+offset];
599
    ret /= len;
600

    
601
    return ret;
602
    }
603

    
604
///////////////////////////////////////////////////////////////////////////////////////////////////
605

    
606
  protected void displayCubitQuats()
607
    {
608
    StringBuilder builder = new StringBuilder();
609
    float[] tmp = new float[4];
610
    float ERR = 0.01f;
611

    
612
    for(int cubit=0; cubit<mNumCubits; cubit++)
613
      {
614
      builder.append(cubit);
615
      builder.append(" : ");
616

    
617
      int refCubit,variant = getCubitVariant(cubit,mNumLayers);
618

    
619
      for(refCubit=0; refCubit<mNumCubits; refCubit++)
620
        {
621
        if( getCubitVariant(refCubit,mNumLayers)==variant ) break;
622
        }
623

    
624
      float[] curpos = mOrigPos[cubit];
625
      float[] refpos = mOrigPos[refCubit];
626
      float refX = computeAvg(refpos,0);
627
      float refY = computeAvg(refpos,1);
628
      float refZ = computeAvg(refpos,2);
629
      float curX = computeAvg(curpos,0);
630
      float curY = computeAvg(curpos,1);
631
      float curZ = computeAvg(curpos,2);
632

    
633
      for(int quat=0; quat<mNumQuats; quat++)
634
        {
635
        QuatHelper.rotateVectorByQuat(tmp,refX,refY,refZ,0,mObjectQuats[quat]);
636

    
637
        float dx = tmp[0]-curX;
638
        float dy = tmp[1]-curY;
639
        float dz = tmp[2]-curZ;
640

    
641
        if( dx>-ERR && dx<ERR && dy>-ERR && dy<ERR && dz>-ERR && dz<ERR )
642
          {
643
          if( doesNotStickOut(variant,curX,curY,curZ,tmp,mObjectQuats[quat]) )
644
            {
645
            builder.append(quat);
646
            builder.append(',');
647
            }
648
          else
649
            {
650
            android.util.Log.e("D", "cubit: "+cubit+" quat: "+quat+" : center correct, but shape sticks out");
651
            }
652
          }
653
        }
654

    
655
      builder.append('\n');
656
      }
657

    
658
    android.util.Log.e("D", "cubitQuats: \n"+builder.toString() );
659
    }
660

    
661
///////////////////////////////////////////////////////////////////////////////////////////////////
662

    
663
  protected int[] buildSolvedQuats(Static3D faceAx)
664
    {
665
    final float MAXD = 0.0001f;
666
    float x = faceAx.get0();
667
    float y = faceAx.get1();
668
    float z = faceAx.get2();
669
    float a,dx,dy,dz,qx,qy,qz;
670
    Static4D quat;
671
    int place = 0;
672

    
673
    for(int q=1; q<mNumQuats; q++)
674
      {
675
      quat = mObjectQuats[q];
676
      qx = quat.get0();
677
      qy = quat.get1();
678
      qz = quat.get2();
679

    
680
           if( x!=0.0f ) { a = qx/x; }
681
      else if( y!=0.0f ) { a = qy/y; }
682
      else               { a = qz/z; }
683

    
684
      dx = a*x-qx;
685
      dy = a*y-qy;
686
      dz = a*z-qz;
687

    
688
      if( dx>-MAXD && dx<MAXD && dy>-MAXD && dy<MAXD && dz>-MAXD && dz<MAXD )
689
        {
690
        mTmpQuats[place++] = q;
691
        }
692
      }
693

    
694
    if( place!=0 )
695
      {
696
      int[] ret = new int[place];
697
      System.arraycopy(mTmpQuats,0,ret,0,place);
698
      return ret;
699
      }
700

    
701
    return null;
702
    }
703

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

    
706
  public int[][] getSolvedQuats()
707
    {
708
    int[] groups = new int[mNumCubits];
709
    int numGroups = 1;
710
    int numFirst  = 0;
711

    
712
    for(int cubit=0; cubit<mNumCubits; cubit++)
713
      {
714
      groups[cubit] = retCubitSolvedStatus(cubit);
715
      if( groups[cubit]>=0 ) numGroups++;
716
      else                   numFirst++;
717
      }
718

    
719
    int firstIndex = 1;
720
    int groupIndex = 1;
721
    int[][] solvedQuats = new int[numGroups][];
722
    solvedQuats[0] = new int[1+numFirst];
723
    solvedQuats[0][0] = numFirst;
724
    Static3D[] axis = getFaceAxis();
725

    
726
    for(int cubit=0; cubit<mNumCubits; cubit++)
727
      {
728
      int group = groups[cubit];
729

    
730
      if( group<0 )
731
        {
732
        solvedQuats[0][firstIndex] = cubit;
733
        firstIndex++;
734
        }
735
      else
736
        {
737
        int[] quats = buildSolvedQuats(axis[group]);
738
        int len = quats==null ? 0 : quats.length;
739
        solvedQuats[groupIndex] = new int[2+len];
740
        solvedQuats[groupIndex][0] = 1;
741
        solvedQuats[groupIndex][1] = cubit;
742
        for(int i=0; i<len; i++) solvedQuats[groupIndex][i+2] = quats[i];
743
        groupIndex++;
744
        }
745
      }
746
/*
747
    String dbg = "SOLVED GROUPS:\n";
748

    
749
    for(int g=0; g<numGroups; g++)
750
      {
751
      int len = solvedQuats[g].length;
752
      for(int i=0; i<len; i++) dbg += (" "+solvedQuats[g][i]);
753
      dbg+="\n";
754
      }
755

    
756
    android.util.Log.e("D", dbg);
757
*/
758
    return solvedQuats;
759
    }
760

    
761
///////////////////////////////////////////////////////////////////////////////////////////////////
762

    
763
  public int getSolvedFunctionIndex()
764
    {
765
    return 0;
766
    }
767

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

    
773
  private boolean isSolvedCentersOnly()
774
    {
775
    int numGroups = mSolvedQuats.length;
776

    
777
    for(int group=1; group<numGroups; group++)
778
      {
779
      int numEntries= mSolvedQuats[group].length;
780
      int numCubits = mSolvedQuats[group][0];
781
      int firstCubit= mSolvedQuats[group][1];
782
      int firstQuat = mCubits[firstCubit].mQuatIndex;
783

    
784
      for(int cubit=2; cubit<=numCubits; cubit++)
785
        {
786
        int currCubit= mSolvedQuats[group][cubit];
787
        int currQuat = mCubits[currCubit].mQuatIndex;
788
        boolean isGood= (firstQuat==currQuat);
789

    
790
        for(int q=numCubits+1; !isGood && q<numEntries; q++)
791
          {
792
          int quat = mSolvedQuats[group][q];
793
          if( firstQuat == getMultQuat(currQuat,quat) ) isGood = true;
794
          }
795

    
796
        if( !isGood ) return false;
797
        }
798
      }
799

    
800
    return true;
801
    }
802

    
803
///////////////////////////////////////////////////////////////////////////////////////////////////
804

    
805
  private boolean isSolved0()
806
    {
807
    if( mSolvedQuats[0][0]==0 ) return isSolvedCentersOnly();
808

    
809
    for( int[] solvedQuat : mSolvedQuats )
810
      {
811
      int numCubits = solvedQuat[0];
812
      int firstCubit= solvedQuat[1];
813
      int quat = mCubits[firstCubit].mQuatIndex;
814

    
815
      for( int cubit=2; cubit<=numCubits; cubit++ )
816
        {
817
        int c = solvedQuat[cubit];
818
        if( quat != mCubits[c].mQuatIndex ) return false;
819
        }
820
      }
821

    
822
    int cubit= mSolvedQuats[0][1];
823
    int quat0= mCubits[cubit].mQuatIndex;
824
    int numGroups = mSolvedQuats.length;
825

    
826
    for(int group=1; group<numGroups; group++)
827
      {
828
      int firstCubit= mSolvedQuats[group][1];
829
      int currQuat  = mCubits[firstCubit].mQuatIndex;
830

    
831
      if( quat0==currQuat ) continue;
832

    
833
      boolean isGood= false;
834
      int numEntries= mSolvedQuats[group].length;
835
      int numCubits = mSolvedQuats[group][0];
836

    
837
      for(int q=numCubits+1; q<numEntries; q++)
838
        {
839
        int quat = mSolvedQuats[group][q];
840

    
841
        if( quat0 == getMultQuat(currQuat,quat) )
842
          {
843
          isGood = true;
844
          break;
845
          }
846
        }
847

    
848
      if( !isGood ) return false;
849
      }
850

    
851
    return true;
852
    }
853

    
854
///////////////////////////////////////////////////////////////////////////////////////////////////
855

    
856
  private int computeScramble(int quatNum, int centerNum)
857
    {
858
    float MAXDIFF = 0.01f;
859
    float[] center= mOrigPos[centerNum];
860
    Static4D sc = new Static4D(center[0], center[1], center[2], 1.0f);
861
    Static4D result = QuatHelper.rotateVectorByQuat(sc,mObjectQuats[quatNum]);
862

    
863
    float x = result.get0();
864
    float y = result.get1();
865
    float z = result.get2();
866

    
867
    for(int c=0; c<mNumCubits; c++)
868
      {
869
      float[] cent = mOrigPos[c];
870

    
871
      float qx = cent[0] - x;
872
      float qy = cent[1] - y;
873
      float qz = cent[2] - z;
874

    
875
      if( qx>-MAXDIFF && qx<MAXDIFF &&
876
          qy>-MAXDIFF && qy<MAXDIFF &&
877
          qz>-MAXDIFF && qz<MAXDIFF  ) return c;
878
      }
879

    
880
    return -1;
881
    }
882

    
883
///////////////////////////////////////////////////////////////////////////////////////////////////
884
// Dino4 uses this. It is solved if and only if groups of cubits
885
// (0,3,7), (1,2,5), (4,8,9), (6,10,11)
886
// or
887
// (0,1,4), (2,3,6), (5,9,10), (7,8,11)
888
// are all the same color.
889

    
890
  private boolean isSolved1()
891
    {
892
    if( mScramble==null )
893
      {
894
      mScramble = new int[mNumQuats][mNumCubits];
895
      mColors   = new int[mNumCubits];
896

    
897
      for(int q=0; q<mNumQuats; q++)
898
        for(int c=0; c<mNumCubits; c++) mScramble[q][c] = computeScramble(q,c);
899
      }
900

    
901
    if( mFaceMap==null )
902
      {
903
      mFaceMap = new int[] { 4, 2, 2, 4, 0, 2, 1, 4, 0, 0, 1, 1 };
904
      }
905

    
906
    for(int c=0; c<mNumCubits; c++)
907
      {
908
      int index = mScramble[mCubits[c].mQuatIndex][c];
909
      mColors[index] = mFaceMap[c];
910
      }
911

    
912
    if( mColors[0]==mColors[3] && mColors[0]==mColors[7] &&
913
        mColors[1]==mColors[2] && mColors[1]==mColors[5] &&
914
        mColors[4]==mColors[8] && mColors[4]==mColors[9]  ) return true;
915

    
916
    if( mColors[0]==mColors[1] && mColors[0]==mColors[4] &&
917
        mColors[2]==mColors[3] && mColors[2]==mColors[6] &&
918
        mColors[5]==mColors[9] && mColors[5]==mColors[10] ) return true;
919

    
920
    return false;
921
    }
922

    
923
///////////////////////////////////////////////////////////////////////////////////////////////////
924

    
925
  int computeRow(float[] pos, int axisIndex)
926
    {
927
    int ret=0;
928
    int len = pos.length / 3;
929
    Static3D axis = mAxis[axisIndex];
930
    float axisX = axis.get0();
931
    float axisY = axis.get1();
932
    float axisZ = axis.get2();
933
    float casted;
934

    
935
    for(int i=0; i<len; i++)
936
      {
937
      casted = pos[3*i]*axisX + pos[3*i+1]*axisY + pos[3*i+2]*axisZ;
938
      ret |= computeSingleRow(axisIndex,casted);
939
      }
940

    
941
    return ret;
942
    }
943

    
944
///////////////////////////////////////////////////////////////////////////////////////////////////
945

    
946
  private int computeSingleRow(int axisIndex,float casted)
947
    {
948
    int num = mNumCuts[axisIndex];
949

    
950
    for(int i=0; i<num; i++)
951
      {
952
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
953
      }
954

    
955
    return (1<<num);
956
    }
957

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

    
960
  private boolean wasRotateApplied()
961
    {
962
    return mEffects.exists(mRotateEffect.getID());
963
    }
964

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

    
967
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
968
    {
969
    return (mCubits[cubit].getRotRow(axis) & rowBitmap) != 0;
970
    }
971

    
972
///////////////////////////////////////////////////////////////////////////////////////////////////
973
// note the minus in front of the sin() - we rotate counterclockwise
974
// when looking towards the direction where the axis increases in values.
975

    
976
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
977
    {
978
    Static3D axis = mAxis[axisIndex];
979

    
980
    while( angleInDegrees<0 ) angleInDegrees += 360;
981
    angleInDegrees %= 360;
982
    
983
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
984
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
985

    
986
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
987
    }
988

    
989
///////////////////////////////////////////////////////////////////////////////////////////////////
990

    
991
  private synchronized void setupPosition(int[][] moves)
992
    {
993
    if( moves!=null )
994
      {
995
      Static4D quat;
996
      int index, axis, row, rowBitmap, angle;
997

    
998
      for(int[] move: moves)
999
        {
1000
        axis     = move[0];
1001
        rowBitmap= computeBitmapFromRow( move[1],axis );
1002
        row      = computeRowFromBitmap( move[1] );
1003
        angle    = move[2]*(360/mBasicAngles[axis][row]);   // this assumes that all layers from
1004
                                                            // the bitmap have the same BasicAngle.
1005
                                                            // at the moment this is always true as
1006
                                                            // there are no bandaged objects with
1007
                                                            // different per-layer BasicAngles.
1008
        quat     = makeQuaternion(axis,angle);
1009

    
1010
        for(int j=0; j<mNumCubits; j++)
1011
          if( belongsToRotation(j,axis,rowBitmap) )
1012
            {
1013
            index = mCubits[j].removeRotationNow(quat);
1014
            setCubitQuat(j,mCubits[j].computeAssociation(),index);
1015
            }
1016
        }
1017
      }
1018
    }
1019

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

    
1022
  public int getScrambleType()
1023
    {
1024
    return 0;
1025
    }
1026

    
1027
///////////////////////////////////////////////////////////////////////////////////////////////////
1028

    
1029
  int computeBitmapFromRow(int rowBitmap, int axis)
1030
    {
1031
    if( mIsBandaged )
1032
      {
1033
      int bitmap, initBitmap=0;
1034

    
1035
      while( initBitmap!=rowBitmap )
1036
        {
1037
        initBitmap = rowBitmap;
1038

    
1039
        for(int cubit=0; cubit<mNumCubits; cubit++)
1040
          {
1041
          bitmap = mCubits[cubit].getRotRow(axis);
1042
          if( (rowBitmap & bitmap) != 0 ) rowBitmap |= bitmap;
1043
          }
1044
        }
1045
      }
1046

    
1047
    return rowBitmap;
1048
    }
1049

    
1050
///////////////////////////////////////////////////////////////////////////////////////////////////
1051

    
1052
  private int computeRowFromBitmap(int rowBitmap)
1053
    {
1054
    int index = 0;
1055

    
1056
    while(index<32)
1057
      {
1058
      if( (rowBitmap&0x1) != 0 ) return index;
1059
      rowBitmap>>=1;
1060
      index++;
1061
      }
1062
    return 0;
1063
    }
1064

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

    
1069
  void clampPos(float[] pos, int offset)
1070
    {
1071
    float currError, minError = Float.MAX_VALUE;
1072
    int minErrorIndex1 = -1;
1073
    int minErrorIndex2 = -1;
1074

    
1075
    float x = pos[offset  ];
1076
    float y = pos[offset+1];
1077
    float z = pos[offset+2];
1078

    
1079
    float xo,yo,zo;
1080

    
1081
    for(int i=0; i<mNumCubits; i++)
1082
      {
1083
      int len = mOrigPos[i].length / 3;
1084

    
1085
      for(int j=0; j<len; j++)
1086
        {
1087
        xo = mOrigPos[i][3*j  ];
1088
        yo = mOrigPos[i][3*j+1];
1089
        zo = mOrigPos[i][3*j+2];
1090

    
1091
        currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
1092

    
1093
        if( currError<minError )
1094
          {
1095
          minError = currError;
1096
          minErrorIndex1 = i;
1097
          minErrorIndex2 = j;
1098
          }
1099
        }
1100
      }
1101

    
1102
    if( minError< 0.1f ) // TODO: 0.1 ?
1103
      {
1104
      pos[offset  ] = mOrigPos[minErrorIndex1][3*minErrorIndex2  ];
1105
      pos[offset+1] = mOrigPos[minErrorIndex1][3*minErrorIndex2+1];
1106
      pos[offset+2] = mOrigPos[minErrorIndex1][3*minErrorIndex2+2];
1107
      }
1108
    }
1109

    
1110
///////////////////////////////////////////////////////////////////////////////////////////////////
1111
// remember about the double cover or unit quaternions!
1112

    
1113
  int mulQuat(int q1, int q2)
1114
    {
1115
    Static4D result = QuatHelper.quatMultiply(mObjectQuats[q1],mObjectQuats[q2]);
1116

    
1117
    float rX = result.get0();
1118
    float rY = result.get1();
1119
    float rZ = result.get2();
1120
    float rW = result.get3();
1121

    
1122
    final float MAX_ERROR = 0.1f;
1123
    float dX,dY,dZ,dW;
1124

    
1125
    for(int i=0; i<mNumQuats; i++)
1126
      {
1127
      dX = mObjectQuats[i].get0() - rX;
1128
      dY = mObjectQuats[i].get1() - rY;
1129
      dZ = mObjectQuats[i].get2() - rZ;
1130
      dW = mObjectQuats[i].get3() - rW;
1131

    
1132
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
1133
          dY<MAX_ERROR && dY>-MAX_ERROR &&
1134
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
1135
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
1136

    
1137
      dX = mObjectQuats[i].get0() + rX;
1138
      dY = mObjectQuats[i].get1() + rY;
1139
      dZ = mObjectQuats[i].get2() + rZ;
1140
      dW = mObjectQuats[i].get3() + rW;
1141

    
1142
      if( dX<MAX_ERROR && dX>-MAX_ERROR &&
1143
          dY<MAX_ERROR && dY>-MAX_ERROR &&
1144
          dZ<MAX_ERROR && dZ>-MAX_ERROR &&
1145
          dW<MAX_ERROR && dW>-MAX_ERROR  ) return i;
1146
      }
1147

    
1148
    return -1;
1149
    }
1150

    
1151
///////////////////////////////////////////////////////////////////////////////////////////////////
1152

    
1153
  private float getAngle()
1154
    {
1155
    int pointNum = mRotationAngle.getNumPoints();
1156

    
1157
    if( pointNum>=1 )
1158
      {
1159
      return mRotationAngle.getPoint(pointNum-1).get0();
1160
      }
1161
    else
1162
      {
1163
      mInterface.reportProblem("points in RotationAngle: "+pointNum, false);
1164
      return 0;
1165
      }
1166
    }
1167

    
1168
///////////////////////////////////////////////////////////////////////////////////////////////////
1169

    
1170
  void setLibInterface(ObjectLibInterface inter)
1171
    {
1172
    mInterface = inter;
1173
    }
1174

    
1175
///////////////////////////////////////////////////////////////////////////////////////////////////
1176

    
1177
  void initializeObject(int[][] moves)
1178
    {
1179
    solve();
1180
    setupPosition(moves);
1181
    }
1182

    
1183
///////////////////////////////////////////////////////////////////////////////////////////////////
1184

    
1185
  synchronized void removeRotationNow()
1186
    {
1187
    float angle = getAngle();
1188
    double nearestAngleInRadians = angle*Math.PI/180;
1189
    float sinA =-(float)Math.sin(nearestAngleInRadians*0.5);
1190
    float cosA = (float)Math.cos(nearestAngleInRadians*0.5);
1191
    float axisX = mAxis[mCurrentRotAxis].get0();
1192
    float axisY = mAxis[mCurrentRotAxis].get1();
1193
    float axisZ = mAxis[mCurrentRotAxis].get2();
1194
    Static4D quat = new Static4D( axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
1195

    
1196
    mRotationAngle.removeAll();
1197
    mRotationAngleStatic.set0(0);
1198

    
1199
    for(int i=0; i<mNumCubits; i++)
1200
      if( belongsToRotation(i, mCurrentRotAxis,mRotRowBitmap) )
1201
        {
1202
        int index = mCubits[i].removeRotationNow(quat);
1203
        setCubitQuat(i,mCubits[i].computeAssociation(),index);
1204
        }
1205
    }
1206

    
1207
///////////////////////////////////////////////////////////////////////////////////////////////////
1208

    
1209
  long finishRotationNow(EffectListener listener, int nearestAngleInDegrees)
1210
    {
1211
    if( wasRotateApplied() )
1212
      {
1213
      float angle = getAngle();
1214
      mRotationAngleStatic.set0(angle);
1215
      mRotationAngleFinal.set0(nearestAngleInDegrees);
1216
      mRotationAngleMiddle.set0( nearestAngleInDegrees + (nearestAngleInDegrees-angle)*0.2f );
1217

    
1218
      mRotationAngle.setDuration(POST_ROTATION_MILLISEC);
1219
      mRotationAngle.resetToBeginning();
1220
      mRotationAngle.removeAll();
1221
      mRotationAngle.add(mRotationAngleStatic);
1222
      mRotationAngle.add(mRotationAngleMiddle);
1223
      mRotationAngle.add(mRotationAngleFinal);
1224
      mRotateEffect.notifyWhenFinished(listener);
1225

    
1226
      return mRotateEffect.getID();
1227
      }
1228

    
1229
    return 0;
1230
    }
1231

    
1232
///////////////////////////////////////////////////////////////////////////////////////////////////
1233

    
1234
  synchronized long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
1235
    {
1236
    if( wasRotateApplied() )
1237
      {
1238
      mCurrentRotAxis = axis;
1239
      mRotRowBitmap= computeBitmapFromRow( rowBitmap,axis );
1240

    
1241
      mRotationAngleStatic.set0(0.0f);
1242
      mRotationAxis.set( mAxis[axis] );
1243
      mRotationAngle.setDuration(durationMillis);
1244
      mRotationAngle.resetToBeginning();
1245
      mRotationAngle.add(new Static1D(0));
1246
      mRotationAngle.add(new Static1D(angle));
1247
      mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1248
      mRotateEffect.notifyWhenFinished(listener);
1249

    
1250
      return mRotateEffect.getID();
1251
      }
1252

    
1253
    return 0;
1254
    }
1255

    
1256
///////////////////////////////////////////////////////////////////////////////////////////////////
1257

    
1258
  void continueRotation(float angleInDegrees)
1259
    {
1260
    mRotationAngleStatic.set0(angleInDegrees);
1261
    }
1262

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

    
1265
  synchronized void beginNewRotation(int axis, int row )
1266
    {
1267
    if( axis<0 || axis>=mNumAxis )
1268
      {
1269
      android.util.Log.e("object", "invalid rotation axis: "+axis);
1270
      return;
1271
      }
1272
    if( row<0 || row>=mNumLayers[axis] )
1273
      {
1274
      android.util.Log.e("object", "invalid rotation row: "+row);
1275
      return;
1276
      }
1277

    
1278
    mCurrentRotAxis = axis;
1279
    mRotRowBitmap= computeBitmapFromRow( (1<<row),axis );
1280
    mRotationAngleStatic.set0(0.0f);
1281
    mRotationAxis.set( mAxis[axis] );
1282
    mRotationAngle.add(mRotationAngleStatic);
1283
    mRotateEffect.setMeshAssociation( mRotRowBitmap<<(axis*mMaxNumLayers) , -1);
1284
    }
1285

    
1286
///////////////////////////////////////////////////////////////////////////////////////////////////
1287

    
1288
  void setTextureMap(int cubit, int face, int newColor)
1289
    {
1290
    final float ratioW = 1.0f/mNumTexCols;
1291
    final float ratioH = 1.0f/mNumTexRows;
1292
    final Static4D[] maps = new Static4D[mNumCubitFaces];
1293
    int row = (mNumTexRows-1) - newColor/mNumTexCols;
1294
    int col = newColor%mNumTexCols;
1295

    
1296
    maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1297
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1298
    }
1299

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

    
1302
  private int getCubitFaceColor(int cubit, int face)
1303
    {
1304
    int puzzleFace = getCubitFaceMap(cubit,face);
1305
    if( puzzleFace>=0 ) puzzleFace %= mNumFaceColors;
1306
    return puzzleFace;
1307
    }
1308

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

    
1311
  public int getCubitFaceMap(int cubit, int face)
1312
    {
1313
    int numFaces = mCubitFaceColors[cubit].length;
1314
    int puzzleFace = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
1315
    return puzzleFace<0 ? -1 : puzzleFace;
1316
    }
1317

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

    
1320
  void resetAllTextureMaps()
1321
    {
1322
    final float ratioW = 1.0f/mNumTexCols;
1323
    final float ratioH = 1.0f/mNumTexRows;
1324
    int cubColor, varColor, color, variant, row, col;
1325

    
1326
    for(int cubit=0; cubit<mNumCubits; cubit++)
1327
      {
1328
      final Static4D[] maps = new Static4D[mNumCubitFaces];
1329
      variant = getCubitVariant(cubit,mNumLayers);
1330

    
1331
      for(int face=0; face<mNumCubitFaces; face++)
1332
        {
1333
        cubColor = getCubitFaceColor(cubit,face);
1334
        varColor = getVariantFaceColor(variant,face);
1335
        color    = cubColor<0 || varColor<0 ? mNumTextures : varColor*mNumFaceColors + cubColor;
1336
        row      = (mNumTexRows-1) - color/mNumTexCols;
1337
        col      = color%mNumTexCols;
1338

    
1339
        maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1340
        }
1341

    
1342
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1343
      }
1344
    }
1345

    
1346
///////////////////////////////////////////////////////////////////////////////////////////////////
1347

    
1348
  void releaseResources()
1349
    {
1350
    mTexture.markForDeletion();
1351
    mMesh.markForDeletion();
1352
    mEffects.markForDeletion();
1353

    
1354
    for(int j=0; j<mNumCubits; j++)
1355
      {
1356
      mCubits[j].releaseResources();
1357
      }
1358
    }
1359

    
1360
///////////////////////////////////////////////////////////////////////////////////////////////////
1361

    
1362
  private void setCubitQuat(int cubit, int andAssociation, int equAssociation)
1363
    {
1364
    if( !mIsInMixupMode )
1365
      {
1366
      mMesh.setEffectAssociation(cubit,andAssociation,equAssociation);
1367
      }
1368
    else
1369
      {
1370
      mMesh.setEffectAssociation(cubit,andAssociation,cubit);
1371
      Static4D tmp = mObjectQuats[equAssociation];
1372
      mMixupModeQuats[cubit].set(tmp);
1373
      }
1374
    }
1375

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

    
1378
  synchronized void restorePreferences(SharedPreferences preferences)
1379
    {
1380
    boolean error = false;
1381
    String key = getShortName();
1382

    
1383
    for(int i=0; i<mNumCubits; i++)
1384
      {
1385
      mQuatDebug[i] = mCubits[i].restorePreferences(key,preferences);
1386

    
1387
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<mNumQuats )
1388
        {
1389
        mCubits[i].modifyCurrentPosition(mObjectQuats[mQuatDebug[i]]);
1390
        setCubitQuat(i,mCubits[i].computeAssociation(),mQuatDebug[i]);
1391
        }
1392
      else
1393
        {
1394
        error = true;
1395
        }
1396
      }
1397

    
1398
    if( error )
1399
      {
1400
      for(int i=0; i<mNumCubits; i++)
1401
        {
1402
        mCubits[i].solve();
1403
        setCubitQuat(i,mCubits[i].computeAssociation(),0);
1404
        }
1405
      }
1406
    }
1407

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

    
1410
  void savePreferences(SharedPreferences.Editor editor)
1411
    {
1412
    String key = getShortName();
1413
    for(int i=0; i<mNumCubits; i++) mCubits[i].savePreferences(key,editor);
1414
    }
1415

    
1416
///////////////////////////////////////////////////////////////////////////////////////////////////
1417

    
1418
  public void removePreferences(SharedPreferences.Editor editor)
1419
    {
1420
    String key = getShortName();
1421
    for(int i=0; i<mNumCubits; i++) mCubits[i].removePreferences(key,editor);
1422
    }
1423

    
1424
///////////////////////////////////////////////////////////////////////////////////////////////////
1425

    
1426
  private float computeRadiusCorrection(float[] sticker, int curr, int len)
1427
    {
1428
    final float A = 0.8f;  // 0<A<1
1429

    
1430
    int prev = curr>0 ? curr-1 : len-1;
1431
    int next = curr<len-1 ? curr+1 : 0;
1432

    
1433
    float v1x = sticker[2*prev  ]-sticker[2*curr  ];
1434
    float v1y = sticker[2*prev+1]-sticker[2*curr+1];
1435
    float v2x = sticker[2*next  ]-sticker[2*curr  ];
1436
    float v2y = sticker[2*next+1]-sticker[2*curr+1];
1437

    
1438
    float len1= v1x*v1x+v1y*v1y;
1439
    float len2= v2x*v2x+v2y*v2y;
1440

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

    
1443
    return 1-A*cos;
1444
    }
1445

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

    
1448
  public ObjectSticker retSticker(int sticker)
1449
    {
1450
    if( mStickers==null )
1451
      {
1452
      float rad = getStickerRadius();
1453
      float str = getStickerStroke();
1454
      float[][] angles = getStickerAngles();
1455
      int numStickers = mStickerCoords.length;
1456
      mStickers = new ObjectSticker[numStickers];
1457

    
1458
      for(int s=0; s<numStickers; s++)
1459
        {
1460
        float scale = mStickerScales[s];
1461
        float radius = rad / scale;
1462
        float stroke = str / scale;
1463
        int len = mStickerCoords[s].length/2;
1464
        float[] radii = new float[len];
1465
        for(int r=0; r<len; r++) radii[r] = radius*computeRadiusCorrection(mStickerCoords[s],r,len);
1466
        mStickers[s] = new ObjectSticker(mStickerCoords[s],angles==null ? null : angles[s],radii,stroke);
1467
        }
1468
      }
1469

    
1470
    return mStickers[sticker];
1471
    }
1472

    
1473
///////////////////////////////////////////////////////////////////////////////////////////////////
1474
// some objects (currently Kilominx,Ivy,Rex) might want to change the stickers.
1475

    
1476
  public void adjustStickerCoords()
1477
    {
1478

    
1479
    }
1480

    
1481
///////////////////////////////////////////////////////////////////////////////////////////////////
1482

    
1483
  public Static4D[] getQuats()
1484
    {
1485
    if( mObjectQuats==null )
1486
      {
1487
      mObjectQuats = QuatGroupGenerator.computeGroup(mAxis,mBasicAngles);
1488
      }
1489

    
1490
    return mObjectQuats;
1491
    }
1492

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

    
1495
  public int getInternalColor()
1496
    {
1497
    return COLOR_INTERNAL;
1498
    }
1499

    
1500
///////////////////////////////////////////////////////////////////////////////////////////////////
1501
// the getFaceColors + final black in a grid (so that we do not exceed the maximum texture size)
1502

    
1503
  private void createTexture()
1504
    {
1505
    Paint paint = new Paint();
1506
    mBitmap = Bitmap.createBitmap( mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, Bitmap.Config.ARGB_4444);
1507
    Canvas canvas = new Canvas(mBitmap);
1508

    
1509
    paint.setAntiAlias(true);
1510
    paint.setTextAlign(Paint.Align.CENTER);
1511
    paint.setStyle(Paint.Style.FILL);
1512

    
1513
    paint.setColor(getInternalColor());
1514
    canvas.drawRect(0, 0, mNumTexCols*TEXTURE_HEIGHT, mNumTexRows*TEXTURE_HEIGHT, paint);
1515

    
1516
    int texture = 0;
1517
    FactorySticker factory = FactorySticker.getInstance();
1518

    
1519
    for(int row=0; row<mNumTexRows; row++)
1520
      for(int col=0; col<mNumTexCols; col++)
1521
        {
1522
        if( texture>=mNumTextures ) break;
1523
        ObjectSticker sticker = retSticker(texture/mNumFaceColors);
1524
        int color = getColor(texture% mNumFaceColors);
1525
        factory.drawRoundedPolygon(canvas, paint, col*TEXTURE_HEIGHT, (mNumTexRows-row)*TEXTURE_HEIGHT, color, sticker);
1526
        texture++;
1527
        }
1528
    }
1529

    
1530
///////////////////////////////////////////////////////////////////////////////////////////////////
1531

    
1532
  void setTexture()
1533
    {
1534
    if( mBitmap==null ) createTexture();
1535

    
1536
    if( !mTexture.setTextureAlreadyInverted(mBitmap) )
1537
      {
1538
      int max = DistortedLibrary.getMaxTextureSize();
1539
      mInterface.reportProblem("failed to set texture of size "+mBitmap.getWidth()+"x"+mBitmap.getHeight()+" max is "+max, true);
1540
      }
1541
    }
1542

    
1543
///////////////////////////////////////////////////////////////////////////////////////////////////
1544

    
1545
  void setObjectRatioNow(float sc, int nodeSize)
1546
    {
1547
    mObjectScreenRatio = sc;
1548
    float scale = mObjectScreenRatio*mInitScreenRatio*nodeSize/mSize;
1549
    mObjectScale.set(scale,scale,scale);
1550

    
1551
    if( mTouchControl ==null ) mTouchControl = getTouchControl();
1552
    mTouchControl.setObjectRatio(mObjectScreenRatio*mInitScreenRatio);
1553
    }
1554

    
1555
///////////////////////////////////////////////////////////////////////////////////////////////////
1556

    
1557
  void setObjectRatio(float sizeChange, int nodeSize)
1558
    {
1559
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
1560

    
1561
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
1562
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
1563

    
1564
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1565
    }
1566

    
1567
///////////////////////////////////////////////////////////////////////////////////////////////////
1568

    
1569
  void setNodeSize(int nodeSize)
1570
    {
1571
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1572
    }
1573

    
1574
///////////////////////////////////////////////////////////////////////////////////////////////////
1575

    
1576
  public float getRatio()
1577
    {
1578
    return mObjectScreenRatio;
1579
    }
1580

    
1581
///////////////////////////////////////////////////////////////////////////////////////////////////
1582

    
1583
  public float getObjectRatio()
1584
    {
1585
    return mObjectScreenRatio*mInitScreenRatio;
1586
    }
1587

    
1588
///////////////////////////////////////////////////////////////////////////////////////////////////
1589

    
1590
  boolean isSolved()
1591
    {
1592
    if( mSolvedFunctionIndex==0 ) return isSolved0();
1593
    if( mSolvedFunctionIndex==1 ) return isSolved1();
1594

    
1595
    return false;
1596
    }
1597

    
1598
///////////////////////////////////////////////////////////////////////////////////////////////////
1599

    
1600
  int computeNearestAngle(int basicAngle, float angle, float speed)
1601
    {
1602
    int nearestAngle = 360/basicAngle;
1603
    int tmp = (int)((angle+nearestAngle/2)/nearestAngle);
1604
    if( angle< -(nearestAngle*0.5) ) tmp-=1;
1605

    
1606
    if( tmp!=0 ) return nearestAngle*tmp;
1607

    
1608
    return speed> 1.2f ? nearestAngle*(angle>0 ? 1:-1) : 0;
1609
    }
1610

    
1611
///////////////////////////////////////////////////////////////////////////////////////////////////
1612
// INTERNAL API - those are called from 'effects' package
1613
///////////////////////////////////////////////////////////////////////////////////////////////////
1614

    
1615
  public void randomizeNewScramble(int[][] scramble, Random rnd, int curr, int total)
1616
    {
1617
    mScrambler.randomizeNewScramble(scramble,rnd,curr,total, getSignature() );
1618
    }
1619

    
1620
///////////////////////////////////////////////////////////////////////////////////////////////////
1621

    
1622
  public Static4D getRotationQuat()
1623
    {
1624
    return mQuat;
1625
    }
1626

    
1627
///////////////////////////////////////////////////////////////////////////////////////////////////
1628

    
1629
  public float getSize()
1630
    {
1631
    return mSize;
1632
    }
1633

    
1634
///////////////////////////////////////////////////////////////////////////////////////////////////
1635

    
1636
  public void apply(Effect effect, int position)
1637
    {
1638
    mEffects.apply(effect, position);
1639
    }
1640

    
1641
///////////////////////////////////////////////////////////////////////////////////////////////////
1642

    
1643
  public void remove(long effectID)
1644
    {
1645
    mEffects.abortById(effectID);
1646
    }
1647

    
1648
///////////////////////////////////////////////////////////////////////////////////////////////////
1649

    
1650
  public MeshBase getObjectMesh()
1651
    {
1652
    return mMesh;
1653
    }
1654

    
1655
///////////////////////////////////////////////////////////////////////////////////////////////////
1656

    
1657
  public DistortedEffects getObjectEffects()
1658
    {
1659
    return mEffects;
1660
    }
1661

    
1662
///////////////////////////////////////////////////////////////////////////////////////////////////
1663
// PUBLIC API
1664
///////////////////////////////////////////////////////////////////////////////////////////////////
1665

    
1666
  public int getCubitFaceColorIndex(int cubit, int face)
1667
    {
1668
    Static4D texMap = mMesh.getTextureMap(mNumFaceColors *cubit + face);
1669

    
1670
    int x = (int)(texMap.get0()/texMap.get2());
1671
    int y = (int)(texMap.get1()/texMap.get3());
1672

    
1673
    return (mNumTexRows-1-y)*NUM_STICKERS_IN_ROW + x;
1674
    }
1675

    
1676
///////////////////////////////////////////////////////////////////////////////////////////////////
1677

    
1678
  public int[] getNumLayers()
1679
    {
1680
    return mNumLayers;
1681
    }
1682

    
1683
///////////////////////////////////////////////////////////////////////////////////////////////////
1684

    
1685
  public synchronized void solve()
1686
    {
1687
    for(int i=0; i<mNumCubits; i++)
1688
      {
1689
      mCubits[i].solve();
1690
      setCubitQuat(i,mCubits[i].computeAssociation(),0);
1691
      }
1692
    }
1693

    
1694
///////////////////////////////////////////////////////////////////////////////////////////////////
1695

    
1696
  public int getCubitQuatIndex(int cubit)
1697
    {
1698
    return (cubit>=0 && cubit<mNumCubits) ? mCubits[cubit].mQuatIndex : 0;
1699
    }
1700

    
1701
///////////////////////////////////////////////////////////////////////////////////////////////////
1702

    
1703
  public int getCubitRotRow(int cubit, int axis)
1704
    {
1705
    return mCubits[cubit].getRotRow(axis);
1706
    }
1707

    
1708
///////////////////////////////////////////////////////////////////////////////////////////////////
1709

    
1710
  public Bitmap getStickerBitmap()
1711
    {
1712
    return mBitmap;
1713
    }
1714

    
1715
///////////////////////////////////////////////////////////////////////////////////////////////////
1716

    
1717
  public DistortedNode getNode()
1718
    {
1719
    return mNode;
1720
    }
1721

    
1722
///////////////////////////////////////////////////////////////////////////////////////////////////
1723

    
1724
  public int getNumStickerTypes()
1725
    {
1726
    return mNumStickerTypes;
1727
    }
1728

    
1729
///////////////////////////////////////////////////////////////////////////////////////////////////
1730
// this is here only so it can be overridden in TwistyJSON soo that we can get this from JSON.
1731

    
1732
  public int getNumCubitFaces()
1733
    {
1734
    return 0;
1735
    }
1736

    
1737
///////////////////////////////////////////////////////////////////////////////////////////////////
1738

    
1739
  public TouchControl getTouchControl()
1740
    {
1741
    if( mTouchControl==null )
1742
      {
1743
      switch(getTouchControlType())
1744
        {
1745
        case TC_TETRAHEDRON      : mTouchControl = new TouchControlTetrahedron(this);
1746
                                   break;
1747
        case TC_HEXAHEDRON       : mTouchControl = new TouchControlHexahedron(this);
1748
                                   break;
1749
        case TC_OCTAHEDRON       : mTouchControl = new TouchControlOctahedron(this);
1750
                                   break;
1751
        case TC_DODECAHEDRON     : mTouchControl = new TouchControlDodecahedron(this);
1752
                                   break;
1753
        case TC_CUBOID           : int[] numLayers = getNumLayers();
1754
                                   mTouchControl = new TouchControlCuboids(this,getDist3D(numLayers));
1755
                                   break;
1756
        case TC_CHANGING_MIRROR  : mTouchControl = new TouchControlMirror(this);
1757
                                   break;
1758
        case TC_CHANGING_SQUARE  : mTouchControl = new TouchControlSquare(this);
1759
                                   break;
1760
        case TC_CHANGING_SHAPEMOD: mTouchControl = new TouchControlShapemod(this);
1761
                                   break;
1762
        }
1763
      }
1764
    return mTouchControl;
1765
    }
1766

    
1767
///////////////////////////////////////////////////////////////////////////////////////////////////
1768

    
1769
  protected void setReader(JsonReader reader)
1770
    {
1771
    // empty
1772
    }
1773

    
1774
///////////////////////////////////////////////////////////////////////////////////////////////////
1775
  // for JSON only
1776
  public abstract int getTouchControlType();
1777
  public abstract int getTouchControlSplit();
1778
  public abstract boolean[][] getLayerRotatable(int[] numLayers);
1779
  public abstract int[][][] getEnabled();
1780
  public abstract float[] getDist3D(int[] numLayers);
1781
  public abstract Static3D[] getFaceAxis();
1782
  public abstract ScrambleState[] getScrambleStates();
1783
  public abstract float[][] getCuts(int[] numLayers);
1784
  public abstract float getStickerRadius();
1785
  public abstract float getStickerStroke();
1786
  public abstract float[][] getStickerAngles();
1787
  public abstract int getCubitVariant(int cubit, int[] numLayers);
1788
  public abstract ObjectShape getObjectShape(int variant);
1789
  public abstract ObjectFaceShape getObjectFaceShape(int variant);
1790
  public abstract int getNumCubitVariants(int[] numLayers);
1791
  public abstract float[][] getCubitPositions(int[] numLayers);
1792
  public abstract Static4D getCubitQuats(int cubit, int[] numLayers);
1793
  public abstract int getNumFaceColors();
1794
  public abstract float getScreenRatio();
1795
  public abstract int getColor(int face);
1796
  public abstract String getShortName();
1797
  public abstract ObjectSignature getSignature();
1798

    
1799
  // not only for JSON
1800
  public abstract Static3D[] getRotationAxis();
1801
  public abstract int[][] getBasicAngles();
1802
  public abstract int getNumFaces();
1803
  public abstract String getObjectName();
1804
  public abstract String getInventor();
1805
  public abstract int getYearOfInvention();
1806
  public abstract int getComplexity();
1807
  public abstract int getFOV();
1808
  public abstract String[][] getTutorials();
1809
  }
(11-11/12)