Project

General

Profile

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

distorted-objectlib / src / main / java / org / distorted / objectlib / main / TwistyObject.java @ 7ca7a08f

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2020 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Magic Cube.                                                              //
5
//                                                                                               //
6
// Magic Cube is proprietary software licensed under an EULA which you should have received      //
7
// along with the code. If not, check https://distorted.org/magic/License-Magic-Cube.html        //
8
///////////////////////////////////////////////////////////////////////////////////////////////////
9

    
10
package org.distorted.objectlib.main;
11

    
12
import java.io.DataInputStream;
13
import java.io.IOException;
14
import java.io.InputStream;
15
import java.util.Random;
16

    
17
import android.graphics.Bitmap;
18
import android.graphics.Canvas;
19
import android.graphics.Paint;
20

    
21
import org.distorted.library.effect.Effect;
22
import org.distorted.library.effect.MatrixEffectMove;
23
import org.distorted.library.effect.MatrixEffectQuaternion;
24
import org.distorted.library.effect.MatrixEffectScale;
25
import org.distorted.library.effect.VertexEffectQuaternion;
26
import org.distorted.library.effect.VertexEffectSink;
27
import org.distorted.library.main.DistortedEffects;
28
import org.distorted.library.main.DistortedLibrary;
29
import org.distorted.library.main.DistortedNode;
30
import org.distorted.library.main.DistortedTexture;
31
import org.distorted.library.helpers.QuatHelper;
32
import org.distorted.library.mesh.MeshBase;
33
import org.distorted.library.mesh.MeshFile;
34
import org.distorted.library.mesh.MeshJoined;
35
import org.distorted.library.message.EffectListener;
36
import org.distorted.library.type.Static1D;
37
import org.distorted.library.type.Static3D;
38
import org.distorted.library.type.Static4D;
39

    
40
import org.distorted.objectlib.helpers.FactoryCubit;
41
import org.distorted.objectlib.helpers.FactorySticker;
42
import org.distorted.objectlib.helpers.ObjectFaceShape;
43
import org.distorted.objectlib.helpers.ObjectLibInterface;
44
import org.distorted.objectlib.helpers.ObjectShape;
45
import org.distorted.objectlib.signature.ObjectSignature;
46
import org.distorted.objectlib.helpers.ObjectSticker;
47
import org.distorted.objectlib.helpers.ObjectStickerOverride;
48
import org.distorted.objectlib.helpers.ObjectVertexEffects;
49
import org.distorted.objectlib.helpers.OperatingSystemInterface;
50
import org.distorted.objectlib.helpers.QuatGroupGenerator;
51
import org.distorted.objectlib.scrambling.ObjectScrambler;
52
import org.distorted.objectlib.json.JsonReader;
53
import org.distorted.objectlib.scrambling.ScrambleEdgeGenerator;
54
import org.distorted.objectlib.tablebases.ImplementedTablebasesList;
55
import org.distorted.objectlib.tablebases.TablebasesAbstract;
56
import org.distorted.objectlib.touchcontrol.*;
57

    
58
import static org.distorted.objectlib.touchcontrol.TouchControl.*;
59

    
60
///////////////////////////////////////////////////////////////////////////////////////////////////
61

    
62
public abstract class TwistyObject
63
  {
64
  public static final int MODE_ICON = 0;
65
  public static final int MODE_NORM = 1;
66

    
67
  public static final int COLOR_YELLOW   = 0xffffff00;
68
  public static final int COLOR_WHITE    = 0xffffffff;
69
  public static final int COLOR_BLUE     = 0xff0000ff;
70
  public static final int COLOR_GREEN    = 0xff00bb00;
71
  public static final int COLOR_RED      = 0xff990000;
72
  public static final int COLOR_ORANGE   = 0xffff6200;
73
  public static final int COLOR_GREY     = 0xff727c7b;
74
  public static final int COLOR_VIOLET   = 0xff7700bb;
75
  public static final int COLOR_STROKE   = 0xff000000;
76
  public static final int COLOR_INTERNAL = 0xff000000;
77

    
78
  public static final int COLOR_RED_TET  = 0xffff1111;
79
  public static final int COLOR_BLUE_TET = 0xff4444ff;
80

    
81
  private static final int DEFAULT_TEXTURE_HEIGHT = 256;
82
  private static final int DEFAULT_TEXTURE_ROWS   = 8;
83

    
84
  public static final float SQ2 = (float)Math.sqrt(2);
85
  public static final float SQ3 = (float)Math.sqrt(3);
86
  public static final float SQ5 = (float)Math.sqrt(5);
87
  public static final float SQ6 = (float)Math.sqrt(6);
88

    
89
  private static final float MAX_SIZE_CHANGE = 1.35f;
90
  private static final float MIN_SIZE_CHANGE = 0.75f;
91

    
92
  private static final Static3D CENTER = new Static3D(0,0,0);
93

    
94
  protected float[][][][] mStickerCoords;
95
  protected Static4D[] mObjectQuats;
96

    
97
  private int[][] mStickerVariants;
98
  private float[] mStickerScales;
99
  private TwistyObjectCubit[] mCubits;
100
  private TwistyObjectSolved mSolved;
101
  private MeshBase[] mMeshes;
102
  private int mNumCubits, mNumQuats, mNumFaceColors, mNumTextures, mNumOverrides;
103
  private int mNumCubitFaces, mNumStickerTypes;
104
  private Static3D[] mAxis;
105
  private float[][] mCuts;
106
  private int[][] mMinimalCubiesInRow;
107
  private int[] mNumCuts;
108
  private float[][] mOrigPos;
109
  private Static4D[] mOrigQuat;
110
  private Static4D[] mMixupModeQuats;
111
  private boolean mIsInMixupMode;
112
  private Static4D mQuat;
113
  private int[] mNumLayers;
114
  private float mSize;
115
  private DistortedEffects mEffects;
116
  private Static3D mObjectScale;
117
  private int[] mQuatDebug;
118
  private DistortedTexture mTexture;
119
  private float mInitScreenRatio;
120
  private boolean mIsBandaged;
121
  private float mObjectScreenRatio;
122
  private int mNumTexRows, mNumTexCols, mTexHeight;
123
  private MeshBase mMesh;
124
  private ObjectScrambler mScrambler;
125
  private TouchControl mTouchControl;
126
  private DistortedNode mNode;
127
  private ObjectLibInterface mInterface;
128
  private Bitmap mBitmap;
129
  private ObjectSticker[] mStickers;
130
  private ObjectShape[] mShapes;
131
  private int mNumCubitVariants;
132
  private int[][] mCubitFaceColors;
133
  private int[][] mVariantFaceIsOuter;
134
  private int[][] mBasicAngles;
135
  private int mIconMode;
136
  private InitData mInitData;
137
  private float[][] mRowOffsets;
138
  private boolean[] mBelongs;
139
  private float[] mTmp;
140
  private int mNumPuzzleFaces;
141
  private ObjectStickerOverride[] mStickerOverrides;
142
  private boolean mError;
143
  private String mErrorString;
144
  private int mMaxNumLayers;
145
  private int mNumAxis;
146
  private boolean mThereAreDeciders;
147
  private TwistyLayerRotations mRotation;
148

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

    
151
  TwistyObject(int iconMode, Static4D quat, Static3D move, float scale, InitAssets asset)
152
    {
153
    try
154
      {
155
      InputStream jsonStream = asset!=null ? asset.getJsonStream(): null;
156
      JsonReader reader = new JsonReader();
157
      reader.parseJsonFile(jsonStream);
158
      setReader(reader);
159
      mNumLayers = reader.getNumLayers();
160
      mSize      = reader.getSize();
161
      mInitData  = null;
162
      initialize(iconMode,quat,move,scale,asset,true);
163
      if( asset!=null ) asset.close();
164
      mError = false;
165
      mErrorString=null;
166
      }
167
    catch(Exception ex)
168
      {
169
      mError = true;
170
      mErrorString = ex.getMessage();
171
      }
172
    }
173

    
174
///////////////////////////////////////////////////////////////////////////////////////////////////
175

    
176
  public TwistyObject(int iconMode, float size, Static4D quat, Static3D move, float scale, InitData data, InitAssets asset)
177
    {
178
    mNumLayers = data.getNumLayers();
179
    mSize      = size;
180
    mInitData  = data;
181
    initialize(iconMode,quat,move,scale,asset,false);
182
    if( asset!=null ) asset.close();
183
    mError = false;
184
    mErrorString = null;
185
    }
186

    
187
///////////////////////////////////////////////////////////////////////////////////////////////////
188

    
189
  private void debugQuat(Static4D quat, int cubitIndex, float axisX, float axisY, float axisZ, float angle, int place)
190
    {
191
    float[] tracking = mCubits[cubitIndex].getTrackingPoint();
192

    
193
    if( tracking!=null )
194
      {
195
      String problem = (getShortName()+" "+cubitIndex+" "+quat.get0()+" "+quat.get1()+" "+quat.get2()+" "+quat.get3());
196
      problem += (" "+angle+" "+place+" "+tracking[0]+" "+tracking[1]+" "+tracking[2]);
197
      problem += (" "+axisX+" "+axisY+" "+axisZ);
198

    
199
      mInterface.reportProblem(problem, true);
200
      }
201
    }
202

    
203
///////////////////////////////////////////////////////////////////////////////////////////////////
204

    
205
  private void initialize(int iconMode, Static4D quat, Static3D move, float scale, InitAssets asset, boolean fromJSON)
206
    {
207
    mIconMode = iconMode;
208
    mQuat = quat;
209
    mAxis = getRotationAxis();
210
    mInitScreenRatio = getScreenRatio();
211
    mBasicAngles = getBasicAngles();
212
    mObjectQuats = getQuats();
213
    mNumQuats = mObjectQuats.length;
214
    mOrigPos = getCubitPositions(mNumLayers);
215
    mNumPuzzleFaces = getNumFaces();
216
    mRowOffsets = new float[mNumPuzzleFaces][3];
217
    mTmp = new float[4];
218
    mNumAxis = mAxis.length;
219
    mCuts = getCuts(mNumLayers);
220
    mNumCuts = new int[mNumAxis];
221
    mMaxNumLayers = -1;
222
    for(int i=0; i<mNumAxis; i++)
223
      {
224
      if( mMaxNumLayers<mNumLayers[i] ) mMaxNumLayers = mNumLayers[i];
225
      mNumCuts[i] = (mCuts==null || mCuts[i]==null ? 0 : mCuts[i].length);
226
      }
227

    
228
    mMinimalCubiesInRow = getMinimalCubiesInRow();
229
    mNumCubits = mOrigPos.length;
230
    mNumFaceColors = getNumFaceColors();
231
    mBelongs = new boolean[mNumCubits];
232

    
233
    int scramblingType = getScrambleType();
234
    int[][] edges = getScrambleEdges();
235
    int[][] algorithms = getScrambleAlgorithms();
236

    
237
    OperatingSystemInterface os = asset==null ? null : asset.getOS();
238
    TablebasesAbstract tablebase = os!=null ? getTablebase(os) : null;
239
    mScrambler = new ObjectScrambler(scramblingType,mNumAxis,mNumLayers,algorithms,edges,tablebase);
240

    
241
    boolean bandaged=false;
242

    
243
    for( int c=0; c<mNumCubits; c++)
244
      {
245
      if( mOrigPos[c].length>3 )
246
        {
247
        bandaged=true;
248
        break;
249
        }
250
      }
251
    mIsBandaged = bandaged;
252
    mQuatDebug = new int[mNumCubits];
253

    
254
    mObjectScale = new Static3D(scale,scale,scale);
255
    setObjectRatioNow(scale,720);
256

    
257
    mEffects = new DistortedEffects();
258
    createQuaternionEffects();
259

    
260
    mRotation = new TwistyLayerRotations(this,mAxis,mNumLayers,getGhostAngle(),mEffects);
261

    
262
    MatrixEffectScale scaleEffect = new MatrixEffectScale(mObjectScale);
263
    MatrixEffectQuaternion quatEffect = new MatrixEffectQuaternion(mQuat, CENTER);
264
    MatrixEffectMove moveEffect = new MatrixEffectMove(move);
265

    
266
    InputStream meshStream = asset!=null ? asset.getMeshStream(): null;
267
    boolean fromDMESH = (meshStream!=null);
268
    getQuatsAndShapes(fromDMESH,fromJSON);
269
    createMeshAndCubits(meshStream,fromDMESH);
270
    setUpTextures(fromDMESH,fromJSON);
271

    
272
    int index = getSolvedFunctionIndex();
273
    mSolved = new TwistyObjectSolved(this,mOrigPos,index);
274
    mSolved.setupSolvedQuats(getSolvedQuats());
275

    
276
    mEffects.apply(quatEffect);
277
    mEffects.apply(scaleEffect);
278
    mEffects.apply(moveEffect);
279

    
280
    mNode = new DistortedNode(mTexture,mEffects,mMesh);
281
    }
282

    
283
///////////////////////////////////////////////////////////////////////////////////////////////////
284
// in degrees so that everything can be treated modulo 360
285

    
286
  public int getGhostAngle()
287
    {
288
    return 0;
289
    }
290

    
291
///////////////////////////////////////////////////////////////////////////////////////////////////
292

    
293
  private TablebasesAbstract getTablebase(OperatingSystemInterface os)
294
    {
295
    String shortName = getShortName();
296
    return ImplementedTablebasesList.createPacked(os,shortName);
297
    }
298

    
299
///////////////////////////////////////////////////////////////////////////////////////////////////
300

    
301
  private void createQuaternionEffects()
302
    {
303
    if( mNumQuats<=ObjectControl.MAX_QUATS )
304
      {
305
      mIsInMixupMode = false;
306

    
307
      for( int q=0; q<mNumQuats; q++)
308
        {
309
        VertexEffectQuaternion vq = new VertexEffectQuaternion(mObjectQuats[q],CENTER);
310
        vq.setMeshAssociation(0,q);
311
        mEffects.apply(vq);
312
        }
313
      }
314
    else if( mNumCubits<=ObjectControl.MAX_QUATS )
315
      {
316
      mIsInMixupMode = true;
317
      mMixupModeQuats = new Static4D[mNumCubits];
318

    
319
      for( int q=0; q<mNumCubits; q++)
320
        {
321
        mMixupModeQuats[q] = new Static4D(mObjectQuats[0]);
322
        VertexEffectQuaternion vq = new VertexEffectQuaternion(mMixupModeQuats[q],CENTER);
323
        vq.setMeshAssociation(0,q);
324
        mEffects.apply(vq);
325
        }
326
      }
327
    else
328
      {
329
      android.util.Log.e("D", "object has too many quaternions ("+mNumQuats+") or too many cubits ("+mNumCubits+")");
330
      }
331
    }
332

    
333
///////////////////////////////////////////////////////////////////////////////////////////////////
334

    
335
  private Static3D getPos(float[] origPos)
336
    {
337
    int len = origPos.length/3;
338
    float sumX = 0.0f;
339
    float sumY = 0.0f;
340
    float sumZ = 0.0f;
341

    
342
    for(int i=0; i<len; i++)
343
      {
344
      sumX += origPos[3*i  ];
345
      sumY += origPos[3*i+1];
346
      sumZ += origPos[3*i+2];
347
      }
348

    
349
    sumX /= len;
350
    sumY /= len;
351
    sumZ /= len;
352

    
353
    return new Static3D(sumX,sumY,sumZ);
354
    }
355

    
356
///////////////////////////////////////////////////////////////////////////////////////////////////
357

    
358
  private void createOuterFaces()
359
    {
360
    for(int v=0; v<mNumCubitVariants; v++)
361
      {
362
      int numFaces = mShapes[v].getNumFaces();
363
      mVariantFaceIsOuter[v] = new int[numFaces];
364
      }
365

    
366
    for( int cubit=0; cubit<mNumCubits; cubit++)
367
      {
368
      int variant = getCubitVariant(cubit,mNumLayers);
369
      int numFaces = mShapes[variant].getNumFaces();
370

    
371
      for(int face=0; face<numFaces; face++)
372
        if( getCubitFaceColor(cubit,face)>=0 )
373
          {
374
          mVariantFaceIsOuter[variant][face] = 1;
375
          }
376
      }
377
    }
378

    
379
///////////////////////////////////////////////////////////////////////////////////////////////////
380

    
381
  private void getQuatsAndShapes(boolean fromDMESH, boolean fromJSON)
382
    {
383
    mNumCubitVariants = getNumCubitVariants(mNumLayers);
384

    
385
    if( !fromDMESH || !fromJSON )
386
      {
387
      FactoryCubit factory = FactoryCubit.getInstance();
388
      factory.clear();
389

    
390
      mShapes = new ObjectShape[mNumCubitVariants];
391
      for(int v=0; v<mNumCubitVariants; v++) mShapes[v] = getObjectShape(v);
392
      mNumCubitFaces = ObjectShape.computeNumComponents(mShapes);
393
      mVariantFaceIsOuter = new int[mNumCubitVariants][];
394

    
395
      mOrigQuat = new Static4D[mNumCubits];
396
      for(int i=0; i<mNumCubits; i++) mOrigQuat[i] = getCubitQuats(i,mNumLayers);
397

    
398
      if( !fromJSON )
399
        {
400
        mCubitFaceColors = ObjectShape.computeColors(mShapes,mOrigPos,mOrigQuat,this);
401
        createOuterFaces();
402
        }
403

    
404
      if( fromDMESH )
405
        {
406
        for(int i=0; i<mNumCubitVariants; i++) factory.createNewFaceTransform(mShapes[i], mVariantFaceIsOuter[i]);
407
        }
408
      }
409
    }
410

    
411
///////////////////////////////////////////////////////////////////////////////////////////////////
412

    
413
  private void createMeshAndCubits(InputStream stream, boolean fromDMESH)
414
    {
415
    mCubits = new TwistyObjectCubit[mNumCubits];
416

    
417
    if( fromDMESH )
418
      {
419
      DataInputStream dos = new DataInputStream(stream);
420
      mMesh = new MeshFile(dos);
421

    
422
      try
423
        {
424
        stream.close();
425
        }
426
      catch(IOException e)
427
        {
428
        android.util.Log.e("meshFile", "Error closing InputStream: "+e);
429
        }
430
      }
431
    else
432
      {
433
      MeshBase[] cubitMesh = new MeshBase[mNumCubits];
434

    
435
      for(int i=0; i<mNumCubits; i++)
436
        {
437
        cubitMesh[i] = createCubitMesh(i,mNumLayers,mNumCubitFaces);
438
        Static3D pos = getPos(mOrigPos[i]);
439
        cubitMesh[i].apply(new MatrixEffectMove(pos),1,0);
440
        }
441

    
442
      mMesh = new MeshJoined(cubitMesh);
443

    
444
      float pillowCoeff = getPillowCoeff();
445

    
446
      if( pillowCoeff!=1.0f )
447
        {
448
        float radius = getCircumscribedRadius();
449
        Static1D coeff = new Static1D(pillowCoeff);
450
        Static4D region= new Static4D(0,0,0,radius);
451
        VertexEffectSink sink = new VertexEffectSink(coeff,CENTER,region);
452
        mMesh.apply(sink);
453
        }
454
      }
455

    
456
    for(int i=0; i<mNumCubits; i++)
457
      {
458
      mCubits[i] = new TwistyObjectCubit(this,mOrigPos[i],mNumAxis,mMaxNumLayers,i);
459
      setCubitQuat(i,0);
460

    
461
      if( !mThereAreDeciders && mCubits[i].getType()==TwistyObjectCubit.TYPE_DECIDER )
462
        {
463
        mThereAreDeciders = true;
464
        }
465
      }
466
    }
467

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

    
470
  private MeshBase createCubitMesh(int cubit, int[] numLayers, int numComponents)
471
    {
472
    int variant = getCubitVariant(cubit,numLayers);
473

    
474
    if( mMeshes==null ) mMeshes = new MeshBase[mNumCubitVariants];
475

    
476
    if( mMeshes[variant]==null )
477
      {
478
      ObjectFaceShape faceShape = getObjectFaceShape(variant);
479
      ObjectVertexEffects effects = getVertexEffects(variant);
480
      FactoryCubit factory = FactoryCubit.getInstance();
481
      factory.createNewFaceTransform(mShapes[variant],mVariantFaceIsOuter[variant]);
482
      mMeshes[variant] = factory.createRoundedSolid(mShapes[variant],faceShape,effects,numComponents);
483
      }
484

    
485
    MeshBase mesh = mMeshes[variant].copy(true);
486
    MatrixEffectQuaternion quat = new MatrixEffectQuaternion( mOrigQuat[cubit], CENTER );
487
    mesh.apply(quat,0xffffffff,0);
488

    
489
    return mesh;
490
    }
491

    
492
///////////////////////////////////////////////////////////////////////////////////////////////////
493

    
494
  private void figureOutBitmapDimensions(int numTextures)
495
    {
496
    int maxSize = DistortedLibrary.getMaxTextureSize();
497

    
498
    mTexHeight  = DEFAULT_TEXTURE_HEIGHT;
499

    
500
    while(true)
501
      {
502
      mNumTexCols = DEFAULT_TEXTURE_ROWS;
503
      mNumTexRows = numTextures/mNumTexCols + 1;
504

    
505
      if( mNumTexRows*mTexHeight <= maxSize &&
506
          mNumTexCols*mTexHeight <= maxSize  ) break;
507

    
508
      mTexHeight/=2;
509
      }
510
    }
511

    
512
///////////////////////////////////////////////////////////////////////////////////////////////////
513

    
514
  private void setUpTextures(boolean fromDMESH, boolean fromJSON)
515
    {
516
    mTexture = new DistortedTexture();
517

    
518
    if( fromJSON )
519
      {
520
      mNumStickerTypes = getNumStickerTypes();
521
      mNumCubitFaces = getNumCubitFaces();
522
      }
523
    else
524
      {
525
      FactoryCubit factory = FactoryCubit.getInstance();
526
      mStickerCoords   = factory.getStickerCoords();
527
      mStickerVariants = factory.getStickerVariants();
528
      mStickerScales   = factory.getStickerScales();
529
      adjustStickerCoords();
530
      mNumStickerTypes = (mStickerCoords==null ? 0 : mStickerCoords.length);
531
      }
532

    
533
    mStickerOverrides = getStickerOverrides();
534
    mNumOverrides = mStickerOverrides==null ? 0 : mStickerOverrides.length;
535

    
536
    mNumTextures= mNumFaceColors*mNumStickerTypes + mNumOverrides;
537
    figureOutBitmapDimensions(mNumTextures);
538
    if( mNumTexCols*mNumTexRows < mNumTextures+1 ) mNumTexRows++;
539

    
540
    if( !fromDMESH || shouldResetTextureMaps() ) resetAllTextureMaps();
541
    else overrideCubitFaceColor();
542

    
543
    setTexture();
544
    }
545

    
546
///////////////////////////////////////////////////////////////////////////////////////////////////
547

    
548
  public InitData getInitData()
549
    {
550
    return mInitData;
551
    }
552

    
553
///////////////////////////////////////////////////////////////////////////////////////////////////
554

    
555
  public boolean isInIconMode()
556
    {
557
    return mIconMode==MODE_ICON;
558
    }
559

    
560
///////////////////////////////////////////////////////////////////////////////////////////////////
561

    
562
  public int getVariantStickerShape(int variant, int face)
563
    {
564
    if( variant <mStickerVariants.length )
565
      {
566
      int[] var = mStickerVariants[variant];
567
      return face>=var.length ? -1 : var[face];
568
      }
569
    return -1;
570
    }
571

    
572
///////////////////////////////////////////////////////////////////////////////////////////////////
573

    
574
  public boolean shouldResetTextureMaps()
575
    {
576
    return false;
577
    }
578

    
579
///////////////////////////////////////////////////////////////////////////////////////////////////
580

    
581
  public int[][] getScrambleAlgorithms()
582
    {
583
    return ScrambleEdgeGenerator.getScramblingAlgorithms(mBasicAngles);
584
    }
585

    
586
///////////////////////////////////////////////////////////////////////////////////////////////////
587

    
588
  private boolean sticksOut(Static3D[] faceAxis, float[] dist, float x, float y, float z )
589
    {
590
    final float MAXERR = 0.05f;
591
    int numAxis = dist.length;
592

    
593
    for(int i=0; i<numAxis; i++)
594
      {
595
      Static3D ax = faceAxis[i];
596
      float len = ax.get0()*x + ax.get1()*y + ax.get2()*z;
597
      if( len>mSize*dist[i]+MAXERR ) return true;
598
      }
599

    
600
    return false;
601
    }
602

    
603
///////////////////////////////////////////////////////////////////////////////////////////////////
604

    
605
  private boolean doesNotStickOut(int variant, float px, float py, float pz, float[] tmp, Static4D quat)
606
    {
607
    float[][] vertices = mShapes[variant].getVertices();
608
    Static3D[] axis = getFaceAxis();
609
    float[] dist3D = getDist3D(mNumLayers);
610

    
611
    for( float[] vertex : vertices)
612
      {
613
      float x = vertex[0];
614
      float y = vertex[1];
615
      float z = vertex[2];
616

    
617
      QuatHelper.rotateVectorByQuat(tmp, x, y, z, 1, quat);
618

    
619
      float mx = tmp[0] + px;
620
      float my = tmp[1] + py;
621
      float mz = tmp[2] + pz;
622

    
623
      if( sticksOut(axis, dist3D, mx,my,mz) ) return false;
624
      }
625

    
626
    return true;
627
    }
628

    
629
///////////////////////////////////////////////////////////////////////////////////////////////////
630

    
631
  private float computeAvg(float[] pos, int offset)
632
    {
633
    int len = pos.length/3;
634
    float ret=0.0f;
635
    for(int i=0; i<len; i++) ret += pos[3*i+offset];
636
    ret /= len;
637

    
638
    return ret;
639
    }
640

    
641
///////////////////////////////////////////////////////////////////////////////////////////////////
642

    
643
  protected void displayCubitQuats()
644
    {
645
    StringBuilder builder = new StringBuilder();
646
    float[] tmp = new float[4];
647
    float ERR = 0.01f;
648

    
649
    for(int cubit=0; cubit<mNumCubits; cubit++)
650
      {
651
      builder.append(cubit);
652
      builder.append(" : ");
653

    
654
      int refCubit,variant = getCubitVariant(cubit,mNumLayers);
655

    
656
      for(refCubit=0; refCubit<mNumCubits; refCubit++)
657
        {
658
        if( getCubitVariant(refCubit,mNumLayers)==variant ) break;
659
        }
660

    
661
      float[] curpos = mOrigPos[cubit];
662
      float[] refpos = mOrigPos[refCubit];
663
      float refX = computeAvg(refpos,0);
664
      float refY = computeAvg(refpos,1);
665
      float refZ = computeAvg(refpos,2);
666
      float curX = computeAvg(curpos,0);
667
      float curY = computeAvg(curpos,1);
668
      float curZ = computeAvg(curpos,2);
669

    
670
      for(int quat=0; quat<mNumQuats; quat++)
671
        {
672
        QuatHelper.rotateVectorByQuat(tmp,refX,refY,refZ,0,mObjectQuats[quat]);
673

    
674
        float dx = tmp[0]-curX;
675
        float dy = tmp[1]-curY;
676
        float dz = tmp[2]-curZ;
677

    
678
        if( dx>-ERR && dx<ERR && dy>-ERR && dy<ERR && dz>-ERR && dz<ERR )
679
          {
680
          if( doesNotStickOut(variant,curX,curY,curZ,tmp,mObjectQuats[quat]) )
681
            {
682
            builder.append(quat);
683
            builder.append(',');
684
            }
685
          else
686
            {
687
            android.util.Log.e("D", "cubit: "+cubit+" quat: "+quat+" : center correct, but shape sticks out");
688
            }
689
          }
690
        }
691

    
692
      builder.append('\n');
693
      }
694

    
695
    android.util.Log.e("D", "cubitQuats: \n"+builder );
696
    }
697

    
698
///////////////////////////////////////////////////////////////////////////////////////////////////
699

    
700
  public int getCubitRotationType(int cubit)
701
    {
702
    return TwistyObjectCubit.TYPE_NORMAL;
703
    }
704

    
705
///////////////////////////////////////////////////////////////////////////////////////////////////
706

    
707
  float[] getTrackingPoint(int cubitIndex, int cubitType)
708
    {
709
    if( cubitType!=TwistyObjectCubit.TYPE_NORMAL )
710
      {
711
      int variant = getCubitVariant(cubitIndex,mNumLayers);
712

    
713
      // object must have been created from JSON
714
      if( mVariantFaceIsOuter==null || mVariantFaceIsOuter[variant]==null )
715
        {
716
        mVariantFaceIsOuter = getVariantFaceIsOuter();
717
        }
718
      if( mShapes==null )
719
        {
720
        mShapes = new ObjectShape[mNumCubitVariants];
721
        }
722
      if( mShapes[variant]==null )
723
        {
724
        mShapes[variant] = getObjectShape(variant);
725
        }
726
      if( mOrigQuat==null )
727
        {
728
        mOrigQuat = new Static4D[mNumCubits];
729
        }
730
      if( mOrigQuat[cubitIndex]==null )
731
        {
732
        mOrigQuat[cubitIndex] = getCubitQuats(cubitIndex,mNumLayers);
733
        }
734

    
735
      int outer=-1, faces = mShapes[variant].getNumFaces();
736

    
737
      for(int i=0; i<faces; i++)
738
        {
739
        if( mVariantFaceIsOuter[variant][i]==1 )
740
          {
741
          outer=i;
742
          break;
743
          }
744
        }
745

    
746
      if( outer>=0 )
747
        {
748
        float[] v = mShapes[variant].getFirstVertexInFace(outer);
749
        float[] ret = new float[3];
750
        float[] curpos = mOrigPos[cubitIndex];
751
        Static4D quat = mOrigQuat[cubitIndex];
752
        QuatHelper.rotateVectorByQuat(mTmp, v[0], v[1], v[2], 1, quat);
753

    
754
        ret[0] = mTmp[0]+computeAvg(curpos,0);
755
        ret[1] = mTmp[1]+computeAvg(curpos,1);
756
        ret[2] = mTmp[2]+computeAvg(curpos,2);
757

    
758
        return ret;
759
        }
760
      else
761
        {
762
        android.util.Log.e("D", "Error in getTrackingPoint: no outer face??");
763
        }
764
      }
765

    
766
    return null;
767
    }
768

    
769
///////////////////////////////////////////////////////////////////////////////////////////////////
770

    
771
  public int computeCurrentPuzzleFace(int type, float[] vertex)
772
    {
773
    if( type!=TwistyObjectCubit.TYPE_NORMAL )
774
      {
775
      Static3D[] axis = getFaceAxis();
776
      float[] dist3D = getDist3D(mNumLayers);
777
      final float MAXERR = 0.98f;
778
      int numAxis = axis.length;
779
      float x = vertex[0];
780
      float y = vertex[1];
781
      float z = vertex[2];
782

    
783
      for(int i=0; i<numAxis; i++)
784
        {
785
        Static3D ax = axis[i];
786
        float len = ax.get0()*x + ax.get1()*y + ax.get2()*z;
787
        if( len>mSize*dist3D[i]*MAXERR ) return i;
788
        }
789

    
790
      return -2;
791
      }
792

    
793
    return -1;
794
    }
795

    
796
///////////////////////////////////////////////////////////////////////////////////////////////////
797

    
798
  public float[] getCubitRowOffset(int cubitIndex)
799
    {
800
    return null;
801
    }
802

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

    
805
  void setRotationRowOffset(int puzzleFace, float[] offset)
806
    {
807
    mRowOffsets[puzzleFace][0] = offset[0];
808
    mRowOffsets[puzzleFace][1] = offset[1];
809
    mRowOffsets[puzzleFace][2] = offset[2];
810
    }
811

    
812
///////////////////////////////////////////////////////////////////////////////////////////////////
813

    
814
  int getNumAxis()
815
    {
816
    return mNumAxis;
817
    }
818

    
819
///////////////////////////////////////////////////////////////////////////////////////////////////
820

    
821
  public int[][] getSolvedQuats()
822
    {
823
    return mSolved.getSolvedQuats(mNumLayers,mNumCubitFaces,mCubitFaceColors);
824
    }
825

    
826
///////////////////////////////////////////////////////////////////////////////////////////////////
827

    
828
  public int getSolvedFunctionIndex()
829
    {
830
    return 0;
831
    }
832

    
833
///////////////////////////////////////////////////////////////////////////////////////////////////
834

    
835
  int computeRow(float[] pos, int axisIndex, int cubitType, int puzzleFace)
836
    {
837
    int ret=0;
838
    int len = pos.length / 3;
839
    Static3D axis = mAxis[axisIndex];
840
    float axisX = axis.get0();
841
    float axisY = axis.get1();
842
    float axisZ = axis.get2();
843
    float casted, xoff=0, yoff=0, zoff=0;
844

    
845
    if( cubitType!=TwistyObjectCubit.TYPE_NORMAL )
846
      {
847
      xoff = mRowOffsets[puzzleFace][0];
848
      yoff = mRowOffsets[puzzleFace][1];
849
      zoff = mRowOffsets[puzzleFace][2];
850
      }
851

    
852
    for(int i=0; i<len; i++)
853
      {
854
      casted = (pos[3*i]+xoff)*axisX + (pos[3*i+1]+yoff)*axisY + (pos[3*i+2]+zoff)*axisZ;
855
      ret |= computeSingleRow(axisIndex,casted);
856
      }
857

    
858
    return ret;
859
    }
860

    
861
///////////////////////////////////////////////////////////////////////////////////////////////////
862

    
863
  private int computeSingleRow(int axisIndex,float casted)
864
    {
865
    int num = mNumCuts[axisIndex];
866

    
867
    for(int i=0; i<num; i++)
868
      {
869
      if( casted<mCuts[axisIndex][i] ) return (1<<i);
870
      }
871

    
872
    return (1<<num);
873
    }
874

    
875
///////////////////////////////////////////////////////////////////////////////////////////////////
876

    
877
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
878
    {
879
    return (mCubits[cubit].getRotRow(axis) & rowBitmap) != 0;
880
    }
881

    
882
///////////////////////////////////////////////////////////////////////////////////////////////////
883
// note the minus in front of the sin() - we rotate counterclockwise
884
// when looking towards the direction where the axis increases in values.
885

    
886
  private Static4D makeQuaternion(float axisX, float axisY, float axisZ, int angleInDegrees)
887
    {
888
    while( angleInDegrees<0 ) angleInDegrees += 360;
889
    angleInDegrees %= 360;
890
    
891
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
892
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
893

    
894
    return new Static4D(axisX*sinA, axisY*sinA, axisZ*sinA, cosA);
895
    }
896

    
897
///////////////////////////////////////////////////////////////////////////////////////////////////
898

    
899
  void rotateAllCubits(int axisIndex, int rowBitmap, int angle)
900
    {
901
    Static3D axis = mAxis[axisIndex];
902
    float axisX = axis.get0();
903
    float axisY = axis.get1();
904
    float axisZ = axis.get2();
905
    Static4D quat = makeQuaternion(axisX,axisY,axisZ,angle);
906

    
907
    for(int i=0; i<mNumCubits; i++)
908
      {
909
      mBelongs[i] = belongsToRotation(i,axisIndex,rowBitmap);
910
      if( mBelongs[i] )
911
        {
912
        boolean result = mCubits[i].rotateCubit(quat,false);
913
        if( !result ) debugQuat(quat,i,axisX,axisY,axisZ,angle,1);
914
        }
915
      }
916

    
917
    recomputeFaceOffsets();
918

    
919
    for(int i=0; i<mNumCubits; i++)
920
      {
921
      if( mBelongs[i] )
922
        {
923
        int index = mCubits[i].postRotateCubit(quat);
924
        setCubitQuat(i,index);
925
        }
926
      else if( mCubits[i].getType()==TwistyObjectCubit.TYPE_FOLLOWER )
927
        {
928
        mCubits[i].computeRotationRow();
929
        setCubitQuat(i,mCubits[i].mQuatIndex);
930
        }
931
      }
932
    }
933

    
934
///////////////////////////////////////////////////////////////////////////////////////////////////
935

    
936
  private synchronized void setupPosition(int[][] moves)
937
    {
938
    if( moves!=null )
939
      {
940
      int axisIndex, row, rowBitmap, basic, angle;
941

    
942
      for(int[] move: moves)
943
        {
944
        axisIndex= move[0];
945
        rowBitmap= computeBandagedBitmap( move[1],axisIndex);
946
        row      = computeRowFromBitmap( move[1] );
947
        basic    = mBasicAngles[axisIndex][row];
948
        angle    = move[2]*(360/basic);   // this assumes that all layers from
949
                                          // the bitmap have the same BasicAngle.
950
                                          // at the moment this is always true as
951
                                          // there are no bandaged objects with
952
                                          // different per-layer BasicAngles.
953

    
954
        rotateAllCubits(axisIndex,rowBitmap,angle);
955
        }
956

    
957
      for(int i=0; i<mNumCubits; i++)
958
        {
959
        float[] pos = mCubits[i].getCurrentPos();
960
        int len = pos.length/3;
961
        for(int j=0; j<len; j++) clampPos(pos,3*j);
962
        }
963
      }
964
    }
965

    
966
///////////////////////////////////////////////////////////////////////////////////////////////////
967

    
968
  public int getScrambleType()
969
    {
970
    return ObjectScrambler.SCRAMBLING_ALGORITHMS;
971
    }
972

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

    
975
  public int[][] getMinimalCubiesInRow()
976
    {
977
    return null;
978
    }
979

    
980
///////////////////////////////////////////////////////////////////////////////////////////////////
981

    
982
  int computeBandagedBitmap(int rowBitmap, int axisIndex)
983
    {
984
    if( mIsBandaged )
985
      {
986
      int bitmap, initBitmap=0;
987

    
988
      while( initBitmap!=rowBitmap )
989
        {
990
        initBitmap = rowBitmap;
991

    
992
        for(int cubit=0; cubit<mNumCubits; cubit++)
993
          {
994
          bitmap = mCubits[cubit].getRotRow(axisIndex);
995
          if( (rowBitmap & bitmap) != 0 ) rowBitmap |= bitmap;
996
          }
997
        }
998
      }
999

    
1000
    if( mMinimalCubiesInRow!=null )
1001
      {
1002
      int[] minC = mMinimalCubiesInRow[axisIndex];
1003
      int numL = minC.length;
1004
      int[] numC = new int[numL];
1005

    
1006
      for(int cubit=0; cubit<mNumCubits; cubit++)
1007
        {
1008
        int bitmap = mCubits[cubit].getRotRow(axisIndex);
1009

    
1010
        for(int i=0; i<numL; i++)
1011
          {
1012
          if( (bitmap&0x1)!=0 ) numC[i]++;
1013
          bitmap>>=1;
1014
          }
1015
        }
1016

    
1017
      int bitmap,initBitmap = 0;
1018

    
1019
      while( initBitmap!=rowBitmap )
1020
        {
1021
        initBitmap = rowBitmap;
1022
        bitmap = rowBitmap;
1023
        int last = 0;
1024

    
1025
        for(int i=0; i<numL; i++)
1026
          {
1027
          if( numC[i]<minC[i] && numC[i]>0 )
1028
            {
1029
            if( (bitmap&0x1)!=0 )
1030
              {
1031
              if( i>0     ) rowBitmap |= (1<<(i-1));
1032
              if( i<numL-1) rowBitmap |= (1<<(i+1));
1033
              }
1034
            else if( (bitmap&0x2)!=0 || last>0 ) // we are not rotating this row, but
1035
                                                 // we are rotating the next or the prev
1036
              {
1037
              rowBitmap |= (1<<i);
1038
              }
1039
            }
1040

    
1041
          last = (bitmap&0x1);
1042
          bitmap>>=1;
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.05f ) // TODO: 0.05 ?
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

    
1112
  void setLibInterface(ObjectLibInterface inter)
1113
    {
1114
    mInterface = inter;
1115
    }
1116

    
1117
///////////////////////////////////////////////////////////////////////////////////////////////////
1118

    
1119
  void applyScrambles(int[][] moves)
1120
    {
1121
    setupPosition(moves);
1122
    }
1123

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

    
1126
  void initializeObject(int[][] moves)
1127
    {
1128
    solve();
1129
    setupPosition(moves);
1130
    }
1131

    
1132
///////////////////////////////////////////////////////////////////////////////////////////////////
1133

    
1134
  private void recomputeFaceOffsets()
1135
    {
1136
    if( mThereAreDeciders )
1137
      {
1138
      for(int i=0; i<mNumPuzzleFaces; i++)
1139
        {
1140
        mRowOffsets[i][0] =0;
1141
        mRowOffsets[i][1] =0;
1142
        mRowOffsets[i][2] =0;
1143
        }
1144

    
1145
      for(int i=0; i<mNumCubits; i++)
1146
        if( mCubits[i].getType()==TwistyObjectCubit.TYPE_DECIDER )
1147
          {
1148
          float[] offset = mCubits[i].getOffset();
1149
          int face = mCubits[i].getPuzzleFace();
1150
          mRowOffsets[face][0] = offset[0];
1151
          mRowOffsets[face][1] = offset[1];
1152
          mRowOffsets[face][2] = offset[2];
1153
          }
1154
      }
1155
    }
1156

    
1157
///////////////////////////////////////////////////////////////////////////////////////////////////
1158

    
1159
  synchronized float removeRotation()
1160
    {
1161
    return mRotation.removeRotation();
1162
    }
1163

    
1164
///////////////////////////////////////////////////////////////////////////////////////////////////
1165

    
1166
  long finishRotation(ObjectPreRender pre, int finishAx, int finishRow, float finishAngle, float avgSpeed)
1167
    {
1168
    int basicAngle = mBasicAngles[finishAx][finishRow];
1169
    return mRotation.finishRotation(pre,finishAx,finishRow,basicAngle,finishAngle,avgSpeed);
1170
    }
1171

    
1172
///////////////////////////////////////////////////////////////////////////////////////////////////
1173

    
1174
  void continueRotation(float angleInDegrees)
1175
    {
1176
    mRotation.continueRotation(angleInDegrees);
1177
    }
1178

    
1179
///////////////////////////////////////////////////////////////////////////////////////////////////
1180

    
1181
  synchronized long addRotation(EffectListener listener, int axis, int rowBitmap, int angle, long durationMillis )
1182
    {
1183
    return mRotation.addRotation(listener,axis,rowBitmap,angle,durationMillis);
1184
    }
1185

    
1186
///////////////////////////////////////////////////////////////////////////////////////////////////
1187

    
1188
  void enableGhostAxis(int axNum, boolean enable)
1189
    {
1190
    mTouchControl.enableGhostAxis(axNum,enable);
1191
    }
1192

    
1193
///////////////////////////////////////////////////////////////////////////////////////////////////
1194

    
1195
  synchronized boolean beginRotation(int axis, int row )
1196
    {
1197
    if( axis<0 || axis>=mNumAxis )
1198
      {
1199
      android.util.Log.e("object", "invalid rotation axis: "+axis);
1200
      return false;
1201
      }
1202

    
1203
    return mRotation.beginRotation(axis,row);
1204
    }
1205

    
1206
///////////////////////////////////////////////////////////////////////////////////////////////////
1207

    
1208
  void setTextureMap(int cubit, int face, int color)
1209
    {
1210
    int variant  = getCubitVariant(cubit,mNumLayers);
1211
    int shape    = getVariantStickerShape(variant,face);
1212
    int texIndex = color<0 || shape<0 ? mNumTextures-mNumOverrides : shape*mNumFaceColors + color;
1213
    int row      = (mNumTexRows-1) - texIndex/mNumTexCols;
1214
    int col      = texIndex%mNumTexCols;
1215

    
1216
    final float ratioW = 1.0f/mNumTexCols;
1217
    final float ratioH = 1.0f/mNumTexRows;
1218
    final Static4D[] maps = new Static4D[1];
1219
    maps[0] = new Static4D(col*ratioW, row*ratioH, ratioW, ratioH);
1220
    mMesh.setTextureMap(maps,mNumCubitFaces*cubit+face);
1221
    }
1222

    
1223
///////////////////////////////////////////////////////////////////////////////////////////////////
1224

    
1225
  private int getCubitFaceColor(int cubit, int face)
1226
    {
1227
    int puzzleFace = getCubitFaceMap(cubit,face);
1228
    if( puzzleFace>=0 ) puzzleFace %= mNumFaceColors;
1229
    return puzzleFace;
1230
    }
1231

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

    
1234
  public int getCubitFaceMap(int cubit, int face)
1235
    {
1236
    int numFaces = mCubitFaceColors[cubit].length;
1237
    int puzzleFace = face<numFaces ? mCubitFaceColors[cubit][face] : -1;
1238
    return puzzleFace<0 ? -1 : puzzleFace;
1239
    }
1240

    
1241
///////////////////////////////////////////////////////////////////////////////////////////////////
1242

    
1243
  void resetAllTextureMaps()
1244
    {
1245
    final float ratioW = 1.0f/mNumTexCols;
1246
    final float ratioH = 1.0f/mNumTexRows;
1247
    int cubColor, stiShape, texIndex, variant, row, col;
1248

    
1249
    for(int cubit=0; cubit<mNumCubits; cubit++)
1250
      {
1251
      final Static4D[] maps = new Static4D[mNumCubitFaces];
1252
      variant = getCubitVariant(cubit,mNumLayers);
1253

    
1254
      for(int face=0; face<mNumCubitFaces; face++)
1255
        {
1256
        cubColor = getCubitFaceColor(cubit,face);
1257
        stiShape = getVariantStickerShape(variant,face);
1258
        texIndex = cubColor<0 || stiShape<0 ? mNumTextures-mNumOverrides : stiShape*mNumFaceColors + cubColor;
1259
        row      = (mNumTexRows-1) - texIndex/mNumTexCols;
1260
        col      = texIndex%mNumTexCols;
1261

    
1262
        maps[face] = new Static4D( col*ratioW, row*ratioH, ratioW, ratioH);
1263
        }
1264

    
1265
      mMesh.setTextureMap(maps,mNumCubitFaces*cubit);
1266
      }
1267

    
1268
    overrideCubitFaceColor();
1269
    }
1270

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

    
1273
  private void overrideCubitFaceColor()
1274
    {
1275
    final float ratioW = 1.0f/mNumTexCols;
1276
    final float ratioH = 1.0f/mNumTexRows;
1277

    
1278
    for(int i=0; i<mNumOverrides; i++)
1279
      {
1280
      int[] cubitFaces = mStickerOverrides[i].getCubitFaces();
1281
      int length = cubitFaces.length/2;
1282

    
1283
      for(int j=0; j<length; j++)
1284
        {
1285
        final Static4D[] maps = new Static4D[1];
1286
        int color = mNumTextures-mNumOverrides+1+i;
1287
        int row   = (mNumTexRows-1) - color/mNumTexCols;
1288
        int col   = color%mNumTexCols;
1289
        int cubit = cubitFaces[2*j];
1290
        int face  = cubitFaces[2*j+1];
1291
        maps[0] = new Static4D(col*ratioW, row*ratioH, ratioW, ratioH);
1292
        mMesh.setTextureMap(maps,mNumCubitFaces*cubit+face);
1293
        }
1294
      }
1295
    }
1296

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

    
1299
  void releaseResources()
1300
    {
1301
    mTexture.markForDeletion();
1302
    mMesh.markForDeletion();
1303
    mEffects.markForDeletion();
1304

    
1305
    if( mBitmap!=null )
1306
      {
1307
      mBitmap.recycle();
1308
      mBitmap = null;
1309
      }
1310

    
1311
    for(int j=0; j<mNumCubits; j++)
1312
      {
1313
      mCubits[j].releaseResources();
1314
      }
1315
    }
1316

    
1317
///////////////////////////////////////////////////////////////////////////////////////////////////
1318

    
1319
  private void setCubitQuat(int cubit, int equAssociation)
1320
    {
1321
    int andAssociation = mCubits[cubit].computeAssociation();
1322

    
1323
    if( !mIsInMixupMode )
1324
      {
1325
      mMesh.setEffectAssociation(cubit,andAssociation,equAssociation);
1326
      }
1327
    else
1328
      {
1329
      mMesh.setEffectAssociation(cubit,andAssociation,cubit);
1330
      Static4D tmp = mObjectQuats[equAssociation];
1331
      mMixupModeQuats[cubit].set(tmp);
1332
      }
1333
    }
1334

    
1335
///////////////////////////////////////////////////////////////////////////////////////////////////
1336

    
1337
  synchronized void restorePreferences(OperatingSystemInterface os)
1338
    {
1339
    boolean error = false;
1340
    String key = getShortName();
1341

    
1342
    for(int i=0; i<mNumCubits; i++)
1343
      {
1344
      mQuatDebug[i] = mCubits[i].restorePreferences(key,os);
1345

    
1346
      if( mQuatDebug[i]>=0 && mQuatDebug[i]<mNumQuats )
1347
        {
1348
        boolean result = mCubits[i].rotateCubit(mObjectQuats[mQuatDebug[i]],true);
1349
        if( !result ) debugQuat(mObjectQuats[mQuatDebug[i]],i,0,0,0,mQuatDebug[i],3);
1350
        }
1351
      else { error = true; break; }
1352
      }
1353

    
1354
    if( !error )
1355
      {
1356
      recomputeFaceOffsets();
1357

    
1358
      for(int i=0; i<mNumCubits; i++)
1359
        {
1360
        if( mQuatDebug[i]>=0 && mQuatDebug[i]<mNumQuats )
1361
          {
1362
          mCubits[i].computeRotationRow();
1363
          setCubitQuat(i,mQuatDebug[i]);
1364
          }
1365
        else { error = true; break; }
1366
        }
1367
      }
1368

    
1369
    if( error )
1370
      {
1371
      for(int i=0; i<mNumCubits; i++)
1372
        {
1373
        mCubits[i].solve();
1374
        setCubitQuat(i,0);
1375
        }
1376
      }
1377
    }
1378

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

    
1381
  void savePreferences(OperatingSystemInterface os)
1382
    {
1383
    String key = getShortName();
1384
    for(int i=0; i<mNumCubits; i++) mCubits[i].savePreferences(key,os);
1385
    }
1386

    
1387
///////////////////////////////////////////////////////////////////////////////////////////////////
1388

    
1389
  public void removePreferences(OperatingSystemInterface os)
1390
    {
1391
    String key = getShortName();
1392
    for(int i=0; i<mNumCubits; i++) mCubits[i].removePreferences(key,os);
1393
    }
1394

    
1395
///////////////////////////////////////////////////////////////////////////////////////////////////
1396

    
1397
  private float computeRadiusCorrection(float[][] sticker, int curr, int len)
1398
    {
1399
    final float A = 0.8f;  // 0<A<1
1400

    
1401
    int prev = curr>0 ? curr-1 : len-1;
1402
    int next = curr<len-1 ? curr+1 : 0;
1403

    
1404
    float v1x = sticker[prev][0]-sticker[curr][0];
1405
    float v1y = sticker[prev][1]-sticker[curr][1];
1406
    float v2x = sticker[next][0]-sticker[curr][0];
1407
    float v2y = sticker[next][1]-sticker[curr][1];
1408

    
1409
    float len1= v1x*v1x+v1y*v1y;
1410
    float len2= v2x*v2x+v2y*v2y;
1411

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

    
1414
    return 1-A*cos;
1415
    }
1416

    
1417
///////////////////////////////////////////////////////////////////////////////////////////////////
1418
// Radius of the sphere circumscribed on the puzzle. Needed for pillowing.
1419
//
1420
// This won't work correctly for pillowing off-center puzzles (e.g. mirrors) - for those we'd need
1421
// to introduce the concept of a 'sink center' as well.
1422
//
1423
// public because needed in TouchControlShapemod
1424

    
1425
  public float getCircumscribedRadius()
1426
    {
1427
    switch(mNumPuzzleFaces)
1428
      {
1429
      case  4: return (SQ6/4)*mSize;
1430
      case  6: return (SQ3/2)*mSize;
1431
      case  8: return (SQ2/2)*mSize;
1432
      case 12: return (SQ3/2)*((SQ5+1)/2)*mSize;
1433
      case 16: return 0.50f*mSize;
1434
      }
1435

    
1436
    return 0.0f;
1437
    }
1438

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

    
1441
  public ObjectSticker retSticker(int sticker)
1442
    {
1443
    if( mStickers==null )
1444
      {
1445
      float rad = getStickerRadius();
1446
      float str = getStickerStroke();
1447
      float[][][] angles = getStickerAngles();
1448
      int numStickers = mStickerCoords.length;
1449
      mStickers = new ObjectSticker[numStickers];
1450

    
1451
      for(int s=0; s<numStickers; s++)
1452
        {
1453
        float scale = mStickerScales.length>s ? mStickerScales[s] : 1.0f;
1454
        float radius = rad / scale;
1455
        float stroke = str / scale;
1456
        int numLoops = mStickerCoords[s].length;
1457
        float[][] radii = new float[numLoops][];
1458

    
1459
        for(int l=0; l<numLoops; l++)
1460
          {
1461
          int numVerts = mStickerCoords[s][l].length;
1462
          radii[l] = new float[numVerts];
1463

    
1464
          for(int v=0; v<numVerts; v++)
1465
            radii[l][v] = radius*computeRadiusCorrection(mStickerCoords[s][l],v,numVerts);
1466
          }
1467

    
1468
        mStickers[s] = new ObjectSticker(mStickerCoords[s], (angles==null ? null : angles[s]) ,radii,stroke);
1469
        }
1470
      }
1471

    
1472
    return mStickers[sticker];
1473
    }
1474

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

    
1478
  public void adjustStickerCoords()
1479
    {
1480

    
1481
    }
1482

    
1483
///////////////////////////////////////////////////////////////////////////////////////////////////
1484

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

    
1492
    return mObjectQuats;
1493
    }
1494

    
1495
///////////////////////////////////////////////////////////////////////////////////////////////////
1496

    
1497
  public int[][] getVariantFaceIsOuter()
1498
    {
1499
    return mVariantFaceIsOuter;
1500
    }
1501

    
1502
///////////////////////////////////////////////////////////////////////////////////////////////////
1503

    
1504
  public int getInternalColor()
1505
    {
1506
    return COLOR_INTERNAL;
1507
    }
1508

    
1509
///////////////////////////////////////////////////////////////////////////////////////////////////
1510
// the getFaceColors + final INTERNAL_COLOR in a grid (so that we do not exceed the maximum texture size)
1511

    
1512
  private void createTexture()
1513
    {
1514
    Paint paint = new Paint();
1515
    mBitmap = Bitmap.createBitmap( mNumTexCols*mTexHeight, mNumTexRows*mTexHeight, Bitmap.Config.ARGB_4444);
1516
    Canvas canvas = new Canvas(mBitmap);
1517

    
1518
    paint.setAntiAlias(true);
1519
    paint.setTextAlign(Paint.Align.CENTER);
1520
    paint.setStyle(Paint.Style.FILL);
1521
    paint.setColor(getInternalColor());
1522
    canvas.drawRect(0, 0, mNumTexCols*mTexHeight, mNumTexRows*mTexHeight, paint);
1523

    
1524
    int texture = 0;
1525
    FactorySticker factory = FactorySticker.getInstance();
1526

    
1527
    for(int row=0; row<mNumTexRows; row++)
1528
      for(int col=0; col<mNumTexCols; col++)
1529
        {
1530
        if( texture<mNumTextures-mNumOverrides )
1531
          {
1532
          ObjectSticker sticker = retSticker(texture/mNumFaceColors);
1533
          int color = getColor(texture%mNumFaceColors);
1534
          factory.drawRoundedPolygons(canvas, paint, col*mTexHeight, (mNumTexRows-row)*mTexHeight, color, mTexHeight, sticker);
1535
          }
1536
        else if( texture>mNumTextures-mNumOverrides && texture<=mNumTextures )
1537
          {
1538
          int color = mStickerOverrides[mNumTextures-texture].getColor();
1539
          factory.drawSolidColor(canvas, paint, col*mTexHeight, (mNumTexRows-row)*mTexHeight, color, mTexHeight);
1540
          }
1541

    
1542
        texture++;
1543
        }
1544
    }
1545

    
1546
///////////////////////////////////////////////////////////////////////////////////////////////////
1547

    
1548
  void setTexture()
1549
    {
1550
    if( mBitmap==null ) createTexture();
1551

    
1552
    if( !mTexture.setTextureAlreadyInverted(mBitmap) )
1553
      {
1554
      int max = DistortedLibrary.getMaxTextureSize();
1555
      mInterface.reportProblem("failed to set texture of size "+mBitmap.getWidth()+"x"+mBitmap.getHeight()+" max is "+max, true);
1556
      }
1557
    }
1558

    
1559
///////////////////////////////////////////////////////////////////////////////////////////////////
1560

    
1561
  void setObjectRatioNow(float sc, int nodeSize)
1562
    {
1563
    mObjectScreenRatio = sc;
1564
    float scale = mObjectScreenRatio*mInitScreenRatio*nodeSize/mSize;
1565
    mObjectScale.set(scale,scale,scale);
1566

    
1567
    if( mTouchControl ==null ) mTouchControl = getTouchControl();
1568
    mTouchControl.setObjectRatio(mObjectScreenRatio*mInitScreenRatio);
1569
    }
1570

    
1571
///////////////////////////////////////////////////////////////////////////////////////////////////
1572

    
1573
  void setObjectRatio(float sizeChange, int nodeSize)
1574
    {
1575
    mObjectScreenRatio *= (1.0f+sizeChange)/2;
1576

    
1577
    if( mObjectScreenRatio>MAX_SIZE_CHANGE) mObjectScreenRatio = MAX_SIZE_CHANGE;
1578
    if( mObjectScreenRatio<MIN_SIZE_CHANGE) mObjectScreenRatio = MIN_SIZE_CHANGE;
1579

    
1580
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1581
    }
1582

    
1583
///////////////////////////////////////////////////////////////////////////////////////////////////
1584

    
1585
  void setNodeSize(int nodeSize)
1586
    {
1587
    setObjectRatioNow(mObjectScreenRatio, nodeSize);
1588
    }
1589

    
1590
///////////////////////////////////////////////////////////////////////////////////////////////////
1591

    
1592
  public float getRatio()
1593
    {
1594
    return mObjectScreenRatio;
1595
    }
1596

    
1597
///////////////////////////////////////////////////////////////////////////////////////////////////
1598

    
1599
  public float getObjectRatio()
1600
    {
1601
    return mObjectScreenRatio*mInitScreenRatio;
1602
    }
1603

    
1604
///////////////////////////////////////////////////////////////////////////////////////////////////
1605

    
1606
  boolean isSolved()
1607
    {
1608
    boolean solved = mSolved.isSolved(mCubits);
1609
    return mRotation.isSolved(solved);
1610
    }
1611

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

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

    
1621
///////////////////////////////////////////////////////////////////////////////////////////////////
1622

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

    
1628
///////////////////////////////////////////////////////////////////////////////////////////////////
1629

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

    
1635
///////////////////////////////////////////////////////////////////////////////////////////////////
1636

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

    
1642
///////////////////////////////////////////////////////////////////////////////////////////////////
1643

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

    
1649
///////////////////////////////////////////////////////////////////////////////////////////////////
1650

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

    
1656
///////////////////////////////////////////////////////////////////////////////////////////////////
1657

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

    
1663
///////////////////////////////////////////////////////////////////////////////////////////////////
1664

    
1665
  public int getCubitType(int cubit)
1666
    {
1667
    return mCubits[cubit].getType();
1668
    }
1669

    
1670
///////////////////////////////////////////////////////////////////////////////////////////////////
1671

    
1672
  public float[] getCubitOffset(int cubit)
1673
    {
1674
    return mCubits[cubit].getOffset();
1675
    }
1676

    
1677
///////////////////////////////////////////////////////////////////////////////////////////////////
1678

    
1679
  public ObjectStickerOverride[] getStickerOverrides()
1680
    {
1681
    return null;
1682
    }
1683

    
1684
///////////////////////////////////////////////////////////////////////////////////////////////////
1685

    
1686
  public boolean getError()
1687
    {
1688
    return mError;
1689
    }
1690

    
1691
///////////////////////////////////////////////////////////////////////////////////////////////////
1692

    
1693
  public String getErrorString()
1694
    {
1695
    return mErrorString;
1696
    }
1697

    
1698
///////////////////////////////////////////////////////////////////////////////////////////////////
1699
// PUBLIC API
1700
///////////////////////////////////////////////////////////////////////////////////////////////////
1701

    
1702
  public int getCubitFaceStickerIndex(int cubit, int face)
1703
    {
1704
    Static4D texMap = mMesh.getTextureMap(mNumCubitFaces*cubit + face);
1705

    
1706
    int x = (int)(texMap.get0()/texMap.get2());
1707
    int y = (int)(texMap.get1()/texMap.get3());
1708

    
1709
    return (mNumTexRows-1-y)*mNumTexCols + x;
1710
    }
1711

    
1712
///////////////////////////////////////////////////////////////////////////////////////////////////
1713

    
1714
  public int[] getNumLayers()
1715
    {
1716
    return mNumLayers;
1717
    }
1718

    
1719
///////////////////////////////////////////////////////////////////////////////////////////////////
1720

    
1721
  public synchronized void solve()
1722
    {
1723
    for(int i=0; i<mNumCubits; i++) mCubits[i].solve();
1724

    
1725
    recomputeFaceOffsets();
1726

    
1727
    for(int i=0; i<mNumCubits; i++)
1728
      {
1729
      mCubits[i].computeRotationRow();
1730
      setCubitQuat(i,0);
1731
      }
1732
    }
1733

    
1734
///////////////////////////////////////////////////////////////////////////////////////////////////
1735

    
1736
  public int getCubitQuatIndex(int cubit)
1737
    {
1738
    return (cubit>=0 && cubit<mNumCubits) ? mCubits[cubit].mQuatIndex : 0;
1739
    }
1740

    
1741
///////////////////////////////////////////////////////////////////////////////////////////////////
1742

    
1743
  public int getCubitRotRow(int cubit, int axis)
1744
    {
1745
    return mCubits[cubit].getRotRow(axis);
1746
    }
1747

    
1748
///////////////////////////////////////////////////////////////////////////////////////////////////
1749

    
1750
  public Bitmap getStickerBitmap()
1751
    {
1752
    return mBitmap;
1753
    }
1754

    
1755
///////////////////////////////////////////////////////////////////////////////////////////////////
1756

    
1757
  public DistortedNode getNode()
1758
    {
1759
    return mNode;
1760
    }
1761

    
1762
///////////////////////////////////////////////////////////////////////////////////////////////////
1763

    
1764
  public int getNumStickerTypes()
1765
    {
1766
    return mNumStickerTypes;
1767
    }
1768

    
1769
///////////////////////////////////////////////////////////////////////////////////////////////////
1770

    
1771
  public String reportState()
1772
    {
1773
    StringBuilder builder = new StringBuilder();
1774

    
1775
    for(int i=0; i<mNumCubits; i++ )
1776
      {
1777
      if( i>0 ) builder.append('.');
1778
      builder.append(mCubits[i].mQuatIndex);
1779
      }
1780

    
1781
    return builder.toString();
1782
    }
1783

    
1784
///////////////////////////////////////////////////////////////////////////////////////////////////
1785
// this is here only so it can be overridden in TwistyJSON so that we can get this from JSON.
1786

    
1787
  public int getNumCubitFaces()
1788
    {
1789
    return 0;
1790
    }
1791

    
1792
///////////////////////////////////////////////////////////////////////////////////////////////////
1793
// 1.0 - i.e. no pillowing - by default.
1794
// The coeff is really param of the 'sink' vertex effect - if it is not equal to 1.0, we apply the
1795
// sink effect [centered at (0,0,0)] to the whole mesh as the last step of composing it.
1796

    
1797
  public float getPillowCoeff()
1798
    {
1799
    return 1.0f;
1800
    }
1801

    
1802
///////////////////////////////////////////////////////////////////////////////////////////////////
1803

    
1804
  public TouchControl getTouchControl()
1805
    {
1806
    if( mTouchControl==null )
1807
      {
1808
      switch(getTouchControlType())
1809
        {
1810
        case TC_TETRAHEDRON      : mTouchControl = new TouchControlTetrahedron(this);
1811
                                   break;
1812
        case TC_HEXAHEDRON       : mTouchControl = new TouchControlHexahedron(this);
1813
                                   break;
1814
        case TC_OCTAHEDRON       : mTouchControl = new TouchControlOctahedron(this);
1815
                                   break;
1816
        case TC_DODECAHEDRON     : mTouchControl = new TouchControlDodecahedron(this);
1817
                                   break;
1818
        case TC_ICOSAHEDRON      : mTouchControl = new TouchControlIcosahedron(this);
1819
                                   break;
1820
        case TC_CUBOID           : int[] numLayers = getNumLayers();
1821
                                   mTouchControl = new TouchControlCuboids(this,getDist3D(numLayers));
1822
                                   break;
1823
        case TC_BALL             : mTouchControl = new TouchControlBall(this);
1824
                                   break;
1825
        case TC_CHANGING_MIRROR  : mTouchControl = new TouchControlMirror(this);
1826
                                   break;
1827
        case TC_CHANGING_SQUARE  : mTouchControl = new TouchControlSquare(this);
1828
                                   break;
1829
        case TC_CHANGING_SHAPEMOD: mTouchControl = new TouchControlShapemod(this);
1830
                                   break;
1831
        }
1832
      }
1833
    return mTouchControl;
1834
    }
1835

    
1836
///////////////////////////////////////////////////////////////////////////////////////////////////
1837

    
1838
  public float[][] returnRotationFactor()
1839
    {
1840
    float[][] factor = new float[mNumAxis][];
1841

    
1842
    for(int ax=0; ax<mNumAxis; ax++)
1843
      {
1844
      int numL = mNumLayers[ax];
1845
      factor[ax] = new float[numL];
1846
      for(int la=0; la<numL; la++) factor[ax][la] = 1.0f;
1847
      }
1848

    
1849
    return factor;
1850
    }
1851

    
1852
///////////////////////////////////////////////////////////////////////////////////////////////////
1853

    
1854
  protected void setReader(JsonReader reader)
1855
    {
1856
    // empty
1857
    }
1858

    
1859
///////////////////////////////////////////////////////////////////////////////////////////////////
1860
  // for JSON only
1861
  public abstract int getTouchControlType();
1862
  public abstract int getTouchControlSplit();
1863
  public abstract boolean[][] getLayerRotatable(int[] numLayers);
1864
  public abstract int[][][] getEnabled();
1865
  public abstract float[] getDist3D(int[] numLayers);
1866
  public abstract Static3D[] getFaceAxis();
1867
  public abstract int[][] getScrambleEdges();
1868
  public abstract float[][] getCuts(int[] numLayers);
1869
  public abstract float getStickerRadius();
1870
  public abstract float getStickerStroke();
1871
  public abstract float[][][] getStickerAngles();
1872
  public abstract int getCubitVariant(int cubit, int[] numLayers);
1873
  public abstract ObjectShape getObjectShape(int variant);
1874
  public abstract ObjectFaceShape getObjectFaceShape(int variant);
1875
  public abstract ObjectVertexEffects getVertexEffects(int variant);
1876
  public abstract int getNumCubitVariants(int[] numLayers);
1877
  public abstract float[][] getCubitPositions(int[] numLayers);
1878
  public abstract Static4D getCubitQuats(int cubit, int[] numLayers);
1879
  public abstract int getNumFaceColors();
1880
  public abstract float getScreenRatio();
1881
  public abstract int getColor(int face);
1882
  public abstract String getShortName();
1883
  public abstract ObjectSignature getSignature();
1884

    
1885
  // not only for JSON
1886
  public abstract Static3D[] getRotationAxis();
1887
  public abstract int[][] getBasicAngles();
1888
  public abstract int getNumFaces();
1889
  public abstract String getObjectName();
1890
  public abstract String getInventor();
1891
  public abstract int getYearOfInvention();
1892
  public abstract int getComplexity();
1893
  public abstract int getFOV();
1894
  public abstract String[][] getTutorials();
1895
  }
(8-8/11)