Project

General

Profile

Download (18 KB) Statistics
| Branch: | Tag: | Revision:

magiccube / src / main / java / org / distorted / objects / RubikObject.java @ ca292407

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.objects;
21

    
22
import android.content.SharedPreferences;
23
import android.graphics.Bitmap;
24
import android.graphics.Canvas;
25
import android.graphics.Paint;
26

    
27
import org.distorted.library.effect.Effect;
28
import org.distorted.library.effect.MatrixEffectQuaternion;
29
import org.distorted.library.effect.MatrixEffectScale;
30
import org.distorted.library.effect.VertexEffectSink;
31
import org.distorted.library.main.DistortedEffects;
32
import org.distorted.library.main.DistortedNode;
33
import org.distorted.library.main.DistortedTexture;
34
import org.distorted.library.mesh.MeshBase;
35
import org.distorted.library.mesh.MeshRectangles;
36
import org.distorted.library.message.EffectListener;
37
import org.distorted.library.type.Dynamic1D;
38
import org.distorted.library.type.Static1D;
39
import org.distorted.library.type.Static3D;
40
import org.distorted.library.type.Static4D;
41

    
42
///////////////////////////////////////////////////////////////////////////////////////////////////
43

    
44
public abstract class RubikObject extends DistortedNode
45
  {
46
  public static final int NODE_FBO_SIZE = 600;
47

    
48
  private static final int TEXTURE_HEIGHT = 128;
49
  final float[] LEGAL_QUATS;
50
  final Static3D[] ROTATION_AXIS;
51

    
52
  static float OBJECT_SCREEN_RATIO;
53

    
54
  private static final int POST_ROTATION_MILLISEC = 500;
55
  private final int NUM_CUBITS;
56
  private int mRotRowBitmap;
57
  private int mRotAxis;
58
  private Static3D[] mOrigPos;
59
  private Static3D mNodeScale;
60
  private Static4D mQuatAccumulated;
61
  private Cubit[] mCubits;
62
  private int mSize;
63
  private RubikObjectList mList;
64

    
65
  float mStart, mStep;
66

    
67
  Static1D mRotationAngleStatic, mRotationAngleMiddle, mRotationAngleFinal;
68
  DistortedTexture mTexture;
69

    
70
  VertexEffectSink mSinkEffect;
71
  MatrixEffectScale mScaleEffect;
72
  MatrixEffectQuaternion mQuatCEffect;
73
  MatrixEffectQuaternion mQuatAEffect;
74

    
75
///////////////////////////////////////////////////////////////////////////////////////////////////
76

    
77
  RubikObject(int size, int fov, Static4D quatCur, Static4D quatAcc, DistortedTexture nodeTexture,
78
              MeshRectangles nodeMesh, DistortedEffects nodeEffects, int[][] moves, RubikObjectList list)
79
    {
80
    super(nodeTexture,nodeEffects,nodeMesh);
81

    
82
    resizeFBO(NODE_FBO_SIZE, NODE_FBO_SIZE);
83

    
84
    mList = list;
85
    mOrigPos = getCubitPositions(size);
86

    
87
    LEGAL_QUATS = getLegalQuats();
88
    NUM_CUBITS  = mOrigPos.length;
89
    ROTATION_AXIS = getRotationAxis();
90
    OBJECT_SCREEN_RATIO = getScreenRatio();
91

    
92
    mSize = size;
93
    computeStartAndStep(mOrigPos);
94
    mNodeScale= new Static3D(1,1,1);
95
    mQuatAccumulated = quatAcc;
96
    mSinkEffect  = getSink(mSize);
97

    
98
    mRotationAngleStatic = new Static1D(0);
99
    mRotationAngleMiddle = new Static1D(0);
100
    mRotationAngleFinal  = new Static1D(0);
101

    
102
    Static3D center = new Static3D(0,0,0);
103
    float scale = OBJECT_SCREEN_RATIO*NODE_FBO_SIZE/mSize;
104
    mScaleEffect = new MatrixEffectScale(new Static3D(scale,scale,scale));
105
    mQuatCEffect = new MatrixEffectQuaternion(quatCur, center);
106
    mQuatAEffect = new MatrixEffectQuaternion(quatAcc, center);
107

    
108
    MatrixEffectScale nodeScaleEffect = new MatrixEffectScale(mNodeScale);
109
    nodeEffects.apply(nodeScaleEffect);
110

    
111
    mCubits = new Cubit[NUM_CUBITS];
112
    mTexture = new DistortedTexture();
113

    
114
    int vertices = (int)(24.0f/mSize + 2.0f);
115

    
116
    for(int i=0; i<NUM_CUBITS; i++)
117
      {
118
      MeshBase cubitMesh = createCubitMesh(i,vertices);
119
      mCubits[i] = new Cubit(this,cubitMesh,mOrigPos[i]);
120
      textureCubitMesh(cubitMesh,i);
121

    
122
      attach(mCubits[i].mNode);
123
      }
124

    
125
    setupPosition(moves);
126

    
127
    setProjection(fov, 0.1f);
128
    }
129

    
130
///////////////////////////////////////////////////////////////////////////////////////////////////
131

    
132
  private void textureCubitMesh(MeshBase mesh, int cubit)
133
    {
134
    boolean belongs;
135
    final int numFaces = getNumFaces();
136
    final Static4D[] maps = new Static4D[numFaces];
137
    final float ratio = 1.0f/(numFaces+1);
138

    
139
    if( 2*ROTATION_AXIS.length == numFaces )  // i.e. there are faces on both ends of the axis (cube)
140
      {
141
      for(int i=0; i<numFaces; i++)
142
        {
143
        belongs = isOnFace(cubit, i/2, i%2==0 ? mSize-1:0 );
144
        maps[i] = new Static4D( (belongs?i:6)*ratio, 0.0f, ratio, 1.0f);
145
        }
146
      }
147
    else if( ROTATION_AXIS.length == numFaces )  // just a single face on the right end of an axis (pyraminx)
148
      {
149
      for(int i=0; i<numFaces; i++)
150
        {
151
        belongs = isOnFace(cubit, i, 0 );
152
        maps[i] = new Static4D( (belongs?i:6)*ratio, 0.0f, ratio, 1.0f);
153
        }
154
      }
155

    
156
    mesh.setTextureMap(maps);
157
    }
158

    
159
///////////////////////////////////////////////////////////////////////////////////////////////////
160
// Cast centers of all Cubits on the first rotation Axis and compute the leftmost and rightmost
161
// one. From there compute the 'start' (i.e. the leftmost) and 'step' (i.e. distance between two
162
// consecutive).
163
// it is assumed that other rotation axis have the same 'start' and 'step' - this is the case with
164
// the Cube and the Pyraminx.
165
// Start and Step are then needed to compute which rotation row (with respect to a given axis) a
166
// given Cubit belongs to.
167

    
168
  private void computeStartAndStep(Static3D[] pos)
169
    {
170
    float min = Float.MAX_VALUE;
171
    float max = Float.MIN_VALUE;
172
    float axisX = ROTATION_AXIS[0].get0();
173
    float axisY = ROTATION_AXIS[0].get1();
174
    float axisZ = ROTATION_AXIS[0].get2();
175
    float tmp;
176

    
177
    for(int i=0; i<NUM_CUBITS; i++)
178
      {
179
      tmp = pos[i].get0()*axisX + pos[i].get1()*axisY + pos[i].get2()*axisZ;
180
      if( tmp<min ) min=tmp;
181
      if( tmp>max ) max=tmp;
182
      }
183

    
184
    mStart = min;
185
    mStep  = (max-min+1.0f)/mSize;
186
    }
187

    
188
///////////////////////////////////////////////////////////////////////////////////////////////////
189

    
190
  private boolean belongsToRotation( int cubit, int axis, int rowBitmap)
191
    {
192
    int cubitRow = (int)(mCubits[cubit].mRotationRow[axis]+0.5f);
193
    return ((1<<cubitRow)&rowBitmap)!=0;
194
    }
195

    
196
///////////////////////////////////////////////////////////////////////////////////////////////////
197
// we cannot use belongsToRotation for deciding if to texture a face. Counterexample: the 'rotated'
198
// tetrahedrons of Pyraminx nearby the edge: they belong to rotation but their face which is rotated
199
// away from the face of the Pyraminx shouldn't be textured.
200

    
201
  private boolean isOnFace( int cubit, int axis, int row)
202
    {
203
    final float MAX_ERROR = 0.0001f;
204
    float diff = mCubits[cubit].mRotationRow[axis] - row;
205
    return diff*diff < MAX_ERROR;
206
    }
207

    
208
///////////////////////////////////////////////////////////////////////////////////////////////////
209

    
210
  private void resetRotationAngle(Dynamic1D rotationAngle)
211
    {
212
    rotationAngle.setDuration(POST_ROTATION_MILLISEC);
213
    rotationAngle.resetToBeginning();
214
    rotationAngle.removeAll();
215
    rotationAngle.add(mRotationAngleStatic);
216
    rotationAngle.add(mRotationAngleMiddle);
217
    rotationAngle.add(mRotationAngleFinal);
218
    }
219

    
220
///////////////////////////////////////////////////////////////////////////////////////////////////
221
// note the minus in front of the sin() - we rotate counterclockwise
222
// when looking towards the direction where the axis increases in values.
223

    
224
  private Static4D makeQuaternion(int axisIndex, int angleInDegrees)
225
    {
226
    Static3D axis = ROTATION_AXIS[axisIndex];
227

    
228
    while( angleInDegrees<0 ) angleInDegrees += 360;
229
    angleInDegrees %= 360;
230
    
231
    float cosA = (float)Math.cos(Math.PI*angleInDegrees/360);
232
    float sinA =-(float)Math.sqrt(1-cosA*cosA);
233

    
234
    return new Static4D(axis.get0()*sinA, axis.get1()*sinA, axis.get2()*sinA, cosA);
235
    }
236

    
237
///////////////////////////////////////////////////////////////////////////////////////////////////
238

    
239
  private void setupPosition(int[][] moves)
240
    {
241
    if( moves!=null )
242
      {
243
      Static4D quat;
244
      int axis, rowBitmap, angle;
245
      int corr = (360/getBasicAngle());
246

    
247
      for(int[] move: moves)
248
        {
249
        axis     = move[0];
250
        rowBitmap= move[1];
251
        angle    = move[2]*corr;
252
        quat     = makeQuaternion(axis,angle);
253

    
254
        for(int j=0; j<NUM_CUBITS; j++)
255
          if( belongsToRotation(j,axis,rowBitmap) )
256
            {
257
            mCubits[j].removeRotationNow(quat);
258
            }
259
        }
260
      }
261
    }
262

    
263
///////////////////////////////////////////////////////////////////////////////////////////////////
264
// Clamp all rotated positions to one of those original ones to avoid accumulating errors.
265

    
266
  void clampPos(Static3D pos)
267
    {
268
    float currError, minError = Float.MAX_VALUE;
269
    int minErrorIndex= -1;
270
    float x = pos.get0();
271
    float y = pos.get1();
272
    float z = pos.get2();
273
    float xo,yo,zo;
274

    
275
    for(int i=0; i<NUM_CUBITS; i++)
276
      {
277
      xo = mOrigPos[i].get0();
278
      yo = mOrigPos[i].get1();
279
      zo = mOrigPos[i].get2();
280

    
281
      currError = (xo-x)*(xo-x) + (yo-y)*(yo-y) + (zo-z)*(zo-z);
282

    
283
      if( currError<minError )
284
        {
285
        minError = currError;
286
        minErrorIndex = i;
287
        }
288
      }
289

    
290
    pos.set( mOrigPos[minErrorIndex] );
291
    }
292

    
293
///////////////////////////////////////////////////////////////////////////////////////////////////
294
// the getFaceColors + final black in a horizontal strip.
295

    
296
  public void createTexture()
297
    {
298
    Bitmap bitmap;
299

    
300
    final int numColors = getNumFaces();
301

    
302
    Paint paint = new Paint();
303
    bitmap = Bitmap.createBitmap( (numColors+1)*TEXTURE_HEIGHT, TEXTURE_HEIGHT, Bitmap.Config.ARGB_8888);
304
    Canvas canvas = new Canvas(bitmap);
305

    
306
    paint.setAntiAlias(true);
307
    paint.setTextAlign(Paint.Align.CENTER);
308
    paint.setStyle(Paint.Style.FILL);
309

    
310
    paint.setColor(0xff000000);
311
    canvas.drawRect(0, 0, (numColors+1)*TEXTURE_HEIGHT, TEXTURE_HEIGHT, paint);
312

    
313
    for(int i=0; i<numColors; i++)
314
      {
315
      createFaceTexture(canvas, paint, i, i*TEXTURE_HEIGHT, 0, TEXTURE_HEIGHT);
316
      }
317

    
318
    mTexture.setTexture(bitmap);
319
    }
320

    
321
///////////////////////////////////////////////////////////////////////////////////////////////////
322

    
323
  public int getSize()
324
    {
325
    return mSize;
326
    }
327

    
328
///////////////////////////////////////////////////////////////////////////////////////////////////
329

    
330
  public void continueRotation(float angleInDegrees)
331
    {
332
    mRotationAngleStatic.set0(angleInDegrees);
333
    }
334

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

    
337
  public Static4D getRotationQuat()
338
      {
339
      return mQuatAccumulated;
340
      }
341

    
342
///////////////////////////////////////////////////////////////////////////////////////////////////
343

    
344
  public void recomputeScaleFactor(int scrWidth, int scrHeight)
345
    {
346
    float factor = Math.min(scrWidth,scrHeight);
347
    mNodeScale.set(factor,factor,factor);
348
    }
349

    
350
///////////////////////////////////////////////////////////////////////////////////////////////////
351

    
352
  public void savePreferences(SharedPreferences.Editor editor)
353
    {
354
    for(int i=0; i<NUM_CUBITS; i++) mCubits[i].savePreferences(editor);
355
    }
356

    
357
///////////////////////////////////////////////////////////////////////////////////////////////////
358

    
359
  public void restorePreferences(SharedPreferences preferences)
360
    {
361
    for(int i=0; i<NUM_CUBITS; i++) mCubits[i].restorePreferences(preferences);
362
    }
363

    
364
///////////////////////////////////////////////////////////////////////////////////////////////////
365

    
366
  public long finishRotationNow(EffectListener listener)
367
    {
368
    boolean first = true;
369
    long effectID=0;
370

    
371
    for(int i=0; i<NUM_CUBITS; i++)
372
      {
373
      if( belongsToRotation(i,mRotAxis,mRotRowBitmap) )
374
        {
375
        if( first )
376
          {
377
          first=false;
378
          effectID = mCubits[i].finishRotationNow(listener);
379
          }
380
        resetRotationAngle(mCubits[i].mRotationAngle);
381
        }
382
      }
383

    
384
    return effectID;
385
    }
386

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

    
389
  public void releaseResources()
390
    {
391
    mTexture.markForDeletion();
392

    
393
    for(int i=0; i<NUM_CUBITS; i++) mCubits[i].releaseResources();
394
    }
395

    
396
///////////////////////////////////////////////////////////////////////////////////////////////////
397

    
398
  public void apply(Effect effect, int position)
399
    {
400
    for(int i=0; i<NUM_CUBITS; i++) mCubits[i].mEffect.apply(effect, position);
401
    }
402

    
403
///////////////////////////////////////////////////////////////////////////////////////////////////
404

    
405
  public void remove(long effectID)
406
    {
407
    for(int i=0; i<NUM_CUBITS; i++) mCubits[i].mEffect.abortById(effectID);
408
    }
409

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

    
412
  public void solve()
413
    {
414
    for(int i=0; i<NUM_CUBITS; i++) mCubits[i].solve();
415
    }
416

    
417
///////////////////////////////////////////////////////////////////////////////////////////////////
418

    
419
  public boolean isSolved()
420
    {
421
    Static4D q = mCubits[0].mQuatScramble;
422

    
423
    for(int i=1; i<NUM_CUBITS; i++)
424
      {
425
      if( !mCubits[i].thereIsNoVisibleDifference(q) ) return false;
426
      }
427

    
428
    return true;
429
    }
430

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

    
433
  public void resetAllTextureMaps()
434
    {
435
    for(int i=0; i<NUM_CUBITS; i++)
436
      {
437
      textureCubitMesh( mCubits[i].getMesh() , i );
438
      }
439
    }
440

    
441
///////////////////////////////////////////////////////////////////////////////////////////////////
442

    
443
  public void setTextureMap(int cubit, int face, int newColor)
444
    {
445
    final int numFaces = getNumFaces();
446
    final float ratio = 1.0f/(numFaces+1);
447

    
448
    final Static4D[] maps = new Static4D[numFaces];
449
    maps[face] = new Static4D( newColor*ratio, 0.0f, ratio, 1.0f);
450

    
451
    mCubits[cubit].getMesh().setTextureMap(maps);
452
    }
453

    
454
///////////////////////////////////////////////////////////////////////////////////////////////////
455

    
456
  public void beginNewRotation(int axis, int row )
457
    {
458
    if( axis<0 || axis>=ROTATION_AXIS.length )
459
      {
460
      android.util.Log.e("object", "invalid rotation axis: "+axis);
461
      return;
462
      }
463
    if( row<0 || row>=mSize )
464
      {
465
      android.util.Log.e("object", "invalid rotation row: "+row);
466
      return;
467
      }
468

    
469
    mRotAxis       = axis;
470
    mRotRowBitmap  = (1<<row);
471

    
472
    mRotationAngleStatic.set0(0.0f);
473

    
474
    for(int i=0; i<NUM_CUBITS; i++)
475
      if( belongsToRotation(i,mRotAxis,mRotRowBitmap) )
476
        {
477
        mCubits[i].beginNewRotation(axis);
478
        }
479
     }
480

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

    
483
  public long addNewRotation( int axis, int rowBitmap, int angle, long durationMillis, EffectListener listener )
484
     {
485
     long effectID=0;
486
     boolean first = true;
487

    
488
     mRotAxis       = axis;
489
     mRotRowBitmap  = rowBitmap;
490

    
491
     mRotationAngleStatic.set0(0.0f);
492

    
493
     for(int i=0; i<NUM_CUBITS; i++)
494
       if( belongsToRotation(i,mRotAxis,mRotRowBitmap) )
495
         {
496
         mCubits[i].addNewRotation(axis,durationMillis,angle);
497

    
498
         if( first )
499
           {
500
           first = false;
501
           effectID = mCubits[i].setUpCallback(listener);
502
           }
503
         }
504

    
505
     return effectID;
506
     }
507

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

    
510
  public void removeRotationNow()
511
     {
512
     boolean first = true;
513
     Static4D quat = null;
514

    
515
     for(int i=0; i<NUM_CUBITS; i++)
516
       if( belongsToRotation(i,mRotAxis,mRotRowBitmap) )
517
         {
518
         if( first )
519
           {
520
           first = false;
521
           quat = mCubits[i].returnRotationQuat(mRotAxis);
522
           }
523

    
524
         mCubits[i].removeRotationNow(quat);
525
         }
526

    
527
     mRotationAngleStatic.set0(0);
528
     }
529

    
530
///////////////////////////////////////////////////////////////////////////////////////////////////
531

    
532
  public void initializeObject(int[][] moves)
533
    {
534
    solve();
535
    setupPosition(moves);
536
    }
537

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

    
540
  public RubikObjectList getObjectList()
541
    {
542
    return mList;
543
    }
544

    
545
///////////////////////////////////////////////////////////////////////////////////////////////////
546

    
547
  abstract float getScreenRatio();
548
  abstract VertexEffectSink getSink(int size);
549
  abstract Static3D[] getCubitPositions(int size);
550
  abstract float[] getLegalQuats();
551
  abstract int getNumFaces();
552
  abstract MeshBase createCubitMesh(int cubit, int vertices);
553
  abstract void createFaceTexture(Canvas canvas, Paint paint, int face, int left, int top, int side);
554
  public abstract Static3D[] getRotationAxis();
555
  public abstract int getBasicAngle();
556
  public abstract int returnRowFromOffset(float offset);
557
  public abstract float returnRotationFactor(float offset);
558
  }
(4-4/8)