Project

General

Profile

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

distorted-objectlib / src / main / java / org / distorted / objectlib / touchcontrol / TouchControlShapeChanging.java @ a0ef8a1d

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2021 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.touchcontrol;
11

    
12
import org.distorted.library.helpers.QuatHelper;
13
import org.distorted.library.type.Static3D;
14
import org.distorted.library.type.Static4D;
15
import org.distorted.objectlib.helpers.ObjectShape;
16
import org.distorted.objectlib.main.TwistyObject;
17

    
18
///////////////////////////////////////////////////////////////////////////////////////////////////
19

    
20
public class TouchControlShapeChanging extends TouchControl
21
  {
22
  private static final float NOT_TOUCHED = 1000000.0f;
23
  static final float[] mTmp = new float[4];
24

    
25
  static class FaceInfo
26
    {
27
    private final float[] normal;      // vector normal to the surface of the face, pointing outside.
28
    private final float distance;      // distance from (0,0,0) to the surface of the face
29
    private final float[][] vertices;  // vertices of the face. Already rotated by the initQuat and
30
                                       // moved by 'position' (arithmetic average of all positions)
31
    private final float[][] rotated;   // temp array to store vertices times rotation quaternion.
32

    
33
    //////////////////////////////////////////////////////////
34

    
35
    FaceInfo(float[][] verts, float size)
36
      {
37
      int numV = verts.length;
38

    
39
      vertices = new float[numV][];
40
      rotated  = new float[numV][];
41

    
42
      for(int i=0; i<numV; i++)
43
        {
44
        int len = verts[i].length;
45
        vertices[i]= new float[len];
46
        rotated[i] = new float[len];
47

    
48
        for(int j=0; j<len; j++) vertices[i][j] = verts[i][j]/size;
49
        }
50

    
51
      // assuming the first three vertices are linearly independent
52
      float a1 = vertices[0][0] - vertices[1][0];
53
      float a2 = vertices[0][1] - vertices[1][1];
54
      float a3 = vertices[0][2] - vertices[1][2];
55
      float b1 = vertices[1][0] - vertices[2][0];
56
      float b2 = vertices[1][1] - vertices[2][1];
57
      float b3 = vertices[1][2] - vertices[2][2];
58

    
59
      float vx = a2*b3-a3*b2;
60
      float vy = a3*b1-a1*b3;
61
      float vz = a1*b2-a2*b1;
62

    
63
      float len = (float)Math.sqrt(vx*vx+vy*vy+vz*vz);
64

    
65
      vx/=len;
66
      vy/=len;
67
      vz/=len;
68

    
69
      distance = vx*vertices[0][0] + vy*vertices[0][1] + vz*vertices[0][2];
70

    
71
      normal = new float[4];
72
      normal[0] = vx;
73
      normal[1] = vy;
74
      normal[2] = vz;
75
      normal[3] = 0.0f;
76
      }
77

    
78
    //////////////////////////////////////////////////////////
79

    
80
    public float[] getNormal()
81
      {
82
      return normal;
83
      }
84
    }
85

    
86
  private final float[] mTouch;
87
  private final Static4D mTmpAxis;
88
  private int mNumCubits;
89
  private int[] mNumFaces;
90
  private boolean mPreparationDone;
91

    
92
  final float[] mCamera, mPoint;
93
  final Static3D[] mRotAxis;
94
  final TwistyObject mObject;
95
  int mTouchedCubit, mTouchedFace, mNumAxis;
96
  FaceInfo[][] mInfos;
97
  float[][] mQuats;
98
  boolean mGhostAxisEnabled;
99

    
100
///////////////////////////////////////////////////////////////////////////////////////////////////
101

    
102
  public TouchControlShapeChanging(TwistyObject object)
103
    {
104
    super(object);
105

    
106
    mPoint = new float[3];
107
    mCamera= new float[3];
108
    mTouch = new float[3];
109
    mObject= object;
110
    mPreparationDone = false;
111
    mTmpAxis = new Static4D(0,0,0,0);
112

    
113
    if( object!=null )
114
      {
115
      mRotAxis = object.getRotationAxis() ;
116
      mNumAxis = mRotAxis.length;
117
      }
118
    else
119
      {
120
      mRotAxis = null;
121
      mNumAxis = 0;
122
      }
123
    }
124

    
125
///////////////////////////////////////////////////////////////////////////////////////////////////
126

    
127
  private FaceInfo[] computeInfos(float[][] vertices, int[][] indices, float[] position, Static4D quat, float size)
128
    {
129
    int numFaces = indices.length;
130

    
131
    int len = position.length/3;
132
    float avgX = 0.0f;
133
    float avgY = 0.0f;
134
    float avgZ = 0.0f;
135

    
136
    for(int i=0; i<len; i++)
137
      {
138
      avgX += position[3*i  ];
139
      avgY += position[3*i+1];
140
      avgZ += position[3*i+2];
141
      }
142

    
143
    avgX /= len;
144
    avgY /= len;
145
    avgZ /= len;
146

    
147
    FaceInfo[] infos = new FaceInfo[numFaces];
148
    Static4D tmp;
149

    
150
    for(int i=0; i<numFaces; i++)
151
      {
152
      int numVerts = indices[i].length;
153
      float[][] verts = new float[numVerts][4];
154

    
155
      for(int j=0; j<numVerts; j++)
156
        {
157
        int index = indices[i][j];
158
        float x = vertices[index][0];
159
        float y = vertices[index][1];
160
        float z = vertices[index][2];
161
        float w = 1.0f;
162

    
163
        tmp = QuatHelper.rotateVectorByQuat(x,y,z,w,quat);
164

    
165
        verts[j][0] = tmp.get0() + avgX;
166
        verts[j][1] = tmp.get1() + avgY;
167
        verts[j][2] = tmp.get2() + avgZ;
168
        verts[j][3] = 1.0f;
169
        }
170

    
171
      infos[i] = new FaceInfo(verts,size);
172
      }
173

    
174
    return infos;
175
    }
176

    
177
///////////////////////////////////////////////////////////////////////////////////////////////////
178
// software implementation of DistortedLibrary.mainVertexShader.degree() function.
179
// (limited to regions centered at [0,0,0])
180

    
181
  private float computeVertexDegree(float radius, float[] vert)
182
    {
183
    float x = vert[0];
184
    float y = vert[1];
185
    float z = vert[2];
186

    
187
    float len = (float)Math.sqrt(x*x + y*y + z*z);
188
    return len>radius ? 0.0f : 1.0f-len/radius;
189
    }
190

    
191
///////////////////////////////////////////////////////////////////////////////////////////////////
192
// software implementation of DistortedLibrary.VertexEffectSink
193

    
194
  private float[] adjustVert(float pillow, float radius, float[] vert)
195
    {
196
    float[] output = new float[3];
197
    float deg = computeVertexDegree(radius,vert);
198
    float t = 1.0f - deg*(1.0f-pillow)/pillow;
199
    output[0] = t*vert[0];
200
    output[1] = t*vert[1];
201
    output[2] = t*vert[2];
202

    
203
    return output;
204
    }
205

    
206
///////////////////////////////////////////////////////////////////////////////////////////////////
207

    
208
  private float[][] adjustVerticesForPillow(float pillow, float radius, float[][] verts)
209
    {
210
    int num = verts.length;
211
    float[][] output = new float[num][3];
212
    for(int i=0; i<num; i++) output[i] = adjustVert(pillow,radius,verts[i]);
213
    return output;
214
    }
215

    
216
///////////////////////////////////////////////////////////////////////////////////////////////////
217

    
218
  private void prepare()
219
    {
220
    int[] numLayers = mObject.getNumLayers();
221
    float[][] positions = mObject.getCubitPositions(numLayers);
222
    float size = mObject.getSize();
223
    mNumCubits = positions.length;
224
    mNumFaces  = new int[mNumCubits];
225

    
226
    mInfos = new FaceInfo[mNumCubits][];
227
    float pillow = mObject.getPillowCoeff();
228
    float radius = mObject.getCircumscribedRadius();
229

    
230
    for(int i=0; i<mNumCubits; i++)
231
      {
232
      int variant = mObject.getCubitVariant(i,numLayers);
233
      ObjectShape shape = mObject.getObjectShape(variant);
234
      Static4D quat = mObject.getCubitQuats(i,numLayers);
235
      float[][] vertices = shape.getVertices();
236
      int[][] indices = shape.getVertIndices();
237
      if( pillow!=1.0f ) vertices = adjustVerticesForPillow(pillow,radius,vertices);
238

    
239
      mInfos[i] = computeInfos(vertices,indices,positions[i],quat,size);
240
      mNumFaces[i] =shape.getNumFaces();
241
      }
242

    
243
    Static4D[] quats = mObject.getQuats();
244
    int numQuats = quats.length;
245

    
246
    mQuats = new float[numQuats][4];
247

    
248
    for(int i=0; i<numQuats; i++)
249
      {
250
      Static4D q = quats[i];
251
      mQuats[i][0] = q.get0();
252
      mQuats[i][1] = q.get1();
253
      mQuats[i][2] = q.get2();
254
      mQuats[i][3] = q.get3();
255
      }
256

    
257
    mPreparationDone = true;
258
    }
259

    
260
///////////////////////////////////////////////////////////////////////////////////////////////////
261
// points A, B, C are co-linear. Return true iff B is between A and C on this line.
262
// Compute D1 = A-B, D2=C-B. Then D1 and D2 are parallel vectors.
263
// They disagree in direction iff |D1+D2|<|D1-D2|
264

    
265
  private boolean isBetween(float ax, float ay, float az,
266
                            float bx, float by, float bz,
267
                            float cx, float cy, float cz)
268
    {
269
    float d1x = ax-bx;
270
    float d1y = ay-by;
271
    float d1z = az-bz;
272

    
273
    float d2x = cx-bx;
274
    float d2y = cy-by;
275
    float d2z = cz-bz;
276

    
277
    float sx = d1x+d2x;
278
    float sy = d1y+d2y;
279
    float sz = d1z+d2z;
280

    
281
    float dx = d1x-d2x;
282
    float dy = d1y-d2y;
283
    float dz = d1z-d2z;
284

    
285
    return sx*sx+sy*sy+sz*sz < dx*dx+dy*dy+dz*dz;
286
    }
287

    
288
///////////////////////////////////////////////////////////////////////////////////////////////////
289
// General algorithm: shoot a half-line from the 'point' and count how many
290
// sides of the polygon it intersects with. The point is inside iff this number
291
// is odd. Note that this works also in case of concave polygons.
292
//
293
// Arbitrarily take point P on the plane ( we have decided on P=(vert[0]+vert[1])/2 )
294
// as the other point defining the half-line.
295
// 'point' and 'P' define a line L1 in 3D. Then for each side the pair of its vertices
296
// defines a line L2. If L1||L2 return false. Otherwise, the lines are skew so it's
297
// possible to compute points C1 and C2 on lines L1 and L2 which are closest to the
298
// other line and check if
299
//
300
// a) C1 and P are on the same side of 'point'
301
//    (which happens iff 'point' is not in between of C1 and P)
302
// b) C2 is between the two vertices.
303
//
304
// Both a) and b) together mean that the half-line intersects with side defined by (p2,d2)
305
//
306
// C1 and C2 can be computed in the following way:
307
// Let n = d1 x d2 - then vector n is perpendicular to both d1 and d2 --> (c1-c2) is
308
// parallel to n.
309
// There exist real numbers A,B,C such that
310
// c1 = p1 + A*d1
311
// c2 = p2 + B*d2 and
312
// c2 = c1 + C*n so that
313
// p1 + A*d1 + C*n = p2 + B*d2  --> (p1-p2) + A*d1 = B*d2 - C*n (*)
314
// Let n2 = n x d2. Let's multiply both sides of (*) by n2. Then
315
// (p1-p2)*n2 + A*(d1*n2) = 0 (0 because d1*n2 = n*n2 = 0)
316
// and from that A = [(p1-p2)*n2]/[d1*n2]
317
// Similarly     B = [(p2-p1)*n1]/[d2*n1]  where n1 = n x d1.
318

    
319
  private boolean isInside(float[] point, float[][] vertices)
320
    {
321
    float e1x = (vertices[0][0]+vertices[1][0])/2;
322
    float e1y = (vertices[0][1]+vertices[1][1])/2;
323
    float e1z = (vertices[0][2]+vertices[1][2])/2;
324

    
325
    float d1x = e1x - point[0];
326
    float d1y = e1y - point[1];
327
    float d1z = e1z - point[2];
328

    
329
    float ax = vertices[0][0] - vertices[1][0];
330
    float ay = vertices[0][1] - vertices[1][1];
331
    float az = vertices[0][2] - vertices[1][2];
332

    
333
    float normX = d1y*az - d1z*ay;
334
    float normY = d1z*ax - d1x*az;
335
    float normZ = d1x*ay - d1y*ax;
336

    
337
    float n1x = d1y*normZ - d1z*normY;
338
    float n1y = d1z*normX - d1x*normZ;
339
    float n1z = d1x*normY - d1y*normX;
340

    
341
    float p1x = point[0];
342
    float p1y = point[1];
343
    float p1z = point[2];
344

    
345
    int len = vertices.length;
346
    int numCrossings = 0;
347

    
348
    for(int side=0; side<len; side++)
349
      {
350
      float p2x = vertices[side][0];
351
      float p2y = vertices[side][1];
352
      float p2z = vertices[side][2];
353

    
354
      int next = side==len-1 ? 0 : side+1;
355

    
356
      float e2x = vertices[next][0];
357
      float e2y = vertices[next][1];
358
      float e2z = vertices[next][2];
359

    
360
      float d2x = e2x-p2x;
361
      float d2y = e2y-p2y;
362
      float d2z = e2z-p2z;
363

    
364
      float nx = d2y*d1z - d2z*d1y;
365
      float ny = d2z*d1x - d2x*d1z;
366
      float nz = d2x*d1y - d2y*d1x;
367

    
368
      float n2x = d2y*nz - d2z*ny;
369
      float n2y = d2z*nx - d2x*nz;
370
      float n2z = d2x*ny - d2y*nx;
371

    
372
      float dpx = p1x-p2x;
373
      float dpy = p1y-p2y;
374
      float dpz = p1z-p2z;
375

    
376
      float A1 =-dpx*n2x-dpy*n2y-dpz*n2z;
377
      float B1 = d1x*n2x+d1y*n2y+d1z*n2z;
378

    
379
      float A2 = dpx*n1x+dpy*n1y+dpz*n1z;
380
      float B2 = d2x*n1x+d2y*n1y+d2z*n1z;
381

    
382
      if( B1==0 || B2==0 ) continue;
383

    
384
      float C1 = A1/B1;
385
      float C2 = A2/B2;
386

    
387
      float c1x = p1x + C1*d1x;
388
      float c1y = p1y + C1*d1y;
389
      float c1z = p1z + C1*d1z;
390

    
391
      float c2x = p2x + C2*d2x;
392
      float c2y = p2y + C2*d2y;
393
      float c2z = p2z + C2*d2z;
394

    
395
      if( !isBetween(c1x,c1y,c1z, p1x,p1y,p1z, e1x,e1y,e1z ) &&
396
           isBetween(p2x,p2y,p2z, c2x,c2y,c2z, e2x,e2y,e2z )  )
397
        {
398
        numCrossings++;
399
        }
400
      }
401

    
402
    return (numCrossings%2)==1;
403
    }
404

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

    
407
  private void rotateVertices(float[][] points, float[][] rotated, float[] quat)
408
    {
409
    int numPoints = points.length;
410

    
411
    for(int i=0; i<numPoints; i++)
412
      {
413
      QuatHelper.rotateVectorByQuat(rotated[i],points[i],quat);
414
      }
415
    }
416

    
417
///////////////////////////////////////////////////////////////////////////////////////////////////
418
// given precomputed mCamera and mPoint, respectively camera and touch point positions in ScreenSpace,
419
// a normalVec (nx,ny,nz) and distance (which together define a plane) compute point 'output[]' which:
420
// 1) lies on this plane
421
// 2) is co-linear with mCamera and mPoint
422
//
423
// output = camera + alpha*(point-camera), where alpha = [dist-normalVec*camera] / [normalVec*(point-camera)]
424

    
425
  void castTouchPointOntoFace(float nx, float ny, float nz, float distance, float[] output)
426
    {
427
    float d0 = mPoint[0]-mCamera[0];
428
    float d1 = mPoint[1]-mCamera[1];
429
    float d2 = mPoint[2]-mCamera[2];
430

    
431
    float denom = nx*d0 + ny*d1 + nz*d2;
432

    
433
    if( denom != 0.0f )
434
      {
435
      float axisCam = nx*mCamera[0] + ny*mCamera[1] + nz*mCamera[2];
436
      float alpha = (distance-axisCam)/denom;
437

    
438
      output[0] = mCamera[0] + d0*alpha;
439
      output[1] = mCamera[1] + d1*alpha;
440
      output[2] = mCamera[2] + d2*alpha;
441
      }
442
    }
443

    
444
///////////////////////////////////////////////////////////////////////////////////////////////////
445

    
446
  private boolean cubitFaceIsVisible(float nx, float ny, float nz, float distance)
447
    {
448
    return mCamera[0]*nx + mCamera[1]*ny + mCamera[2]*nz > distance;
449
    }
450

    
451
///////////////////////////////////////////////////////////////////////////////////////////////////
452
// FaceInfo defines a 3D plane (by means of a unit normal vector 'vector' and distance from the origin
453
// 'distance') and a list of points on the plane ('vertices').
454
//
455
// 0) rotate the face normal vector by quat
456
// 1) see if the face is visible. If not, return NOT_TOUCHED
457
// 2) else, cast the line passing through mPoint and mCamera onto this plane
458
// 3) if Z of this point is further from us than the already computed closestSoFar, return NOT_TOUCHED
459
// 4) else, rotate 'vertices' by quat and see if the casted point lies inside the polygon defined by them
460
// 5) if yes, return the distance from this point to the camera; otherwise, return NOT_TOUCHED
461

    
462
  private float cubitFaceTouched(FaceInfo info, float[] quat, float closestSoFar)
463
    {
464
    QuatHelper.rotateVectorByQuat(mTmp,info.normal,quat);
465
    float nx = mTmp[0];
466
    float ny = mTmp[1];
467
    float nz = mTmp[2];
468

    
469
    if( cubitFaceIsVisible(nx,ny,nz,info.distance) )
470
      {
471
      castTouchPointOntoFace(nx,ny,nz,info.distance,mTouch);
472

    
473
      float dx = mTouch[0]-mCamera[0];
474
      float dy = mTouch[1]-mCamera[1];
475
      float dz = mTouch[2]-mCamera[2];
476
      float dist = dx*dx + dy*dy + dz*dz;
477

    
478
      if( dist<closestSoFar )
479
        {
480
        rotateVertices(info.vertices,info.rotated,quat);
481
        if( isInside(mTouch,info.rotated) ) return dist;
482
        }
483
      }
484

    
485
    return NOT_TOUCHED;
486
    }
487

    
488
///////////////////////////////////////////////////////////////////////////////////////////////////
489

    
490
  int computeRow(int cubit, int rotIndex)
491
    {
492
    int row = mObject.getCubitRotRow(cubit,rotIndex);
493

    
494
    for(int index=0; index<32; index++)
495
      {
496
      if( (row&1)==1 ) return index;
497
      row>>=1;
498
      }
499

    
500
    return 0;
501
    }
502

    
503
///////////////////////////////////////////////////////////////////////////////////////////////////
504
// PUBLIC API
505
///////////////////////////////////////////////////////////////////////////////////////////////////
506

    
507
  public boolean objectTouched(Static4D rotatedTouchPoint, Static4D rotatedCamera)
508
    {
509
    if( !mPreparationDone ) prepare();
510

    
511
    mPoint[0]  = rotatedTouchPoint.get0()/mObjectRatio;
512
    mPoint[1]  = rotatedTouchPoint.get1()/mObjectRatio;
513
    mPoint[2]  = rotatedTouchPoint.get2()/mObjectRatio;
514

    
515
    mCamera[0] = rotatedCamera.get0()/mObjectRatio;
516
    mCamera[1] = rotatedCamera.get1()/mObjectRatio;
517
    mCamera[2] = rotatedCamera.get2()/mObjectRatio;
518

    
519
    float closestSoFar = NOT_TOUCHED;
520
    mTouchedCubit = -1;
521
    mTouchedFace  = -1;
522
    int numQuats = mQuats.length;
523

    
524
    for(int cubit=0; cubit<mNumCubits; cubit++)
525
      {
526
      int quatIndex = mObject.getCubitQuatIndex(cubit);
527

    
528
      if( quatIndex<numQuats )
529
        {
530
        float[] quat = mQuats[quatIndex];
531

    
532
        for(int face=0; face<mNumFaces[cubit]; face++)
533
          {
534
          float dist = cubitFaceTouched(mInfos[cubit][face],quat,closestSoFar);
535

    
536
          if( dist!=NOT_TOUCHED )
537
            {
538
            mTouchedCubit= cubit;
539
            mTouchedFace = face;
540
            closestSoFar = dist;
541
            }
542
          }
543
        }
544
      }
545
/*
546
    if( closestSoFar!=NOT_TOUCHED )
547
      {
548
      android.util.Log.e("D", "cubit="+mTouchedCubit+" face="+mTouchedFace+" result: "+closestSoFar);
549
      }
550
*/
551
    return closestSoFar!=NOT_TOUCHED;
552
    }
553

    
554
///////////////////////////////////////////////////////////////////////////////////////////////////
555
// really implemented in derived classes; here present only because we need to be able to
556
// instantiate an object of this class for MODE_REPLACE.
557

    
558
  public void newRotation(int[] output, Static4D rotatedTouchPoint, Static4D quat)
559
    {
560

    
561
    }
562

    
563
///////////////////////////////////////////////////////////////////////////////////////////////////
564

    
565
  public void getCastedRotAxis(float[] output, Static4D quat, int axisIndex)
566
    {
567
    Static3D rotAxis = mRotAxis[axisIndex];
568
    float rx = rotAxis.get0();
569
    float ry = rotAxis.get1();
570
    float rz = rotAxis.get2();
571

    
572
    mTmpAxis.set(rx,ry,rz,0);
573
    Static4D result = QuatHelper.rotateVectorByQuat(mTmpAxis, quat);
574

    
575
    float cx =result.get0();
576
    float cy =result.get1();
577

    
578
    float len = (float)Math.sqrt(cx*cx+cy*cy);
579

    
580
    if( len!=0 )
581
      {
582
      output[0] = cx/len;
583
      output[1] = cy/len;
584
      }
585
    else
586
      {
587
      output[0] = 1;
588
      output[1] = 0;
589
      }
590
    }
591

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

    
594
  public boolean axisAndFaceAgree(int axisIndex)
595
    {
596
    return false;
597
    }
598

    
599
///////////////////////////////////////////////////////////////////////////////////////////////////
600

    
601
  public float[] getTouchedPuzzleCenter()
602
    {
603
    return null;
604
    }
605

    
606
///////////////////////////////////////////////////////////////////////////////////////////////////
607

    
608
  public int getTouchedCubitFace()
609
    {
610
    return mTouchedFace;
611
    }
612

    
613
///////////////////////////////////////////////////////////////////////////////////////////////////
614

    
615
  public int getTouchedCubit()
616
    {
617
    return mTouchedCubit;
618
    }
619

    
620
///////////////////////////////////////////////////////////////////////////////////////////////////
621

    
622
  public void enableGhostAxis(boolean enable)
623
    {
624
    mGhostAxisEnabled = enable;
625
    }
626
  }
(9-9/13)