Project

General

Profile

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

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

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.main.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

    
99
///////////////////////////////////////////////////////////////////////////////////////////////////
100

    
101
  public TouchControlShapeChanging(TwistyObject object)
102
    {
103
    super( object!=null ? object.getObjectRatio() : 1.0f );
104

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

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

    
124
///////////////////////////////////////////////////////////////////////////////////////////////////
125

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

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

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

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

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

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

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

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

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

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

    
173
    return infos;
174
    }
175

    
176
///////////////////////////////////////////////////////////////////////////////////////////////////
177

    
178
  private void prepare()
179
    {
180
    int[] numLayers = mObject.getNumLayers();
181
    float[][] positions = mObject.getCubitPositions(numLayers);
182
    float size = mObject.getSize();
183
    mNumCubits = positions.length;
184
    mNumFaces  = new int[mNumCubits];
185

    
186
    mInfos = new FaceInfo[mNumCubits][];
187

    
188
    for(int i=0; i<mNumCubits; i++)
189
      {
190
      int variant = mObject.getCubitVariant(i,numLayers);
191
      ObjectShape shape = mObject.getObjectShape(variant);
192
      Static4D quat = mObject.getCubitQuats(i,numLayers);
193
      float[][] vertices = shape.getVertices();
194
      int[][] indices = shape.getVertIndices();
195
      mInfos[i] = computeInfos(vertices,indices,positions[i],quat,size);
196
      mNumFaces[i] = indices.length;
197
      }
198

    
199
    Static4D[] quats = mObject.getQuats();
200
    int numQuats = quats.length;
201

    
202
    mQuats = new float[numQuats][4];
203

    
204
    for(int i=0; i<numQuats; i++)
205
      {
206
      Static4D q = quats[i];
207
      mQuats[i][0] = q.get0();
208
      mQuats[i][1] = q.get1();
209
      mQuats[i][2] = q.get2();
210
      mQuats[i][3] = q.get3();
211
      }
212

    
213
    mPreparationDone = true;
214
    }
215

    
216
///////////////////////////////////////////////////////////////////////////////////////////////////
217
// points A, B, C are co-linear. Return true iff B is between A and C on this line.
218
// Compute D1 = A-B, D2=C-B. Then D1 and D2 are parallel vectors.
219
// They disagree in direction iff |D1+D2|<|D1-D2|
220

    
221
  private boolean isBetween(float ax, float ay, float az,
222
                            float bx, float by, float bz,
223
                            float cx, float cy, float cz)
224
    {
225
    float d1x = ax-bx;
226
    float d1y = ay-by;
227
    float d1z = az-bz;
228

    
229
    float d2x = cx-bx;
230
    float d2y = cy-by;
231
    float d2z = cz-bz;
232

    
233
    float sx = d1x+d2x;
234
    float sy = d1y+d2y;
235
    float sz = d1z+d2z;
236

    
237
    float dx = d1x-d2x;
238
    float dy = d1y-d2y;
239
    float dz = d1z-d2z;
240

    
241
    return sx*sx+sy*sy+sz*sz < dx*dx+dy*dy+dz*dz;
242
    }
243

    
244
///////////////////////////////////////////////////////////////////////////////////////////////////
245
// General algorithm: shoot a half-line from the 'point' and count how many
246
// sides of the polygon it intersects with. The point is inside iff this number
247
// is odd. Note that this works also in case of concave polygons.
248
//
249
// Arbitrarily take point P on the plane ( we have decided on P=(vert[0]+vert[1])/2 )
250
// as the other point defining the half-line.
251
// 'point' and 'P' define a line L1 in 3D. Then for each side the pair of its vertices
252
// defines a line L2. If L1||L2 return false. Otherwise, the lines are skew so it's
253
// possible to compute points C1 and C2 on lines L1 and L2 which are closest to the
254
// other line and check if
255
//
256
// a) C1 and P are on the same side of 'point'
257
//    (which happens iff 'point' is not in between of C1 and P)
258
// b) C2 is between the two vertices.
259
//
260
// Both a) and b) together mean that the half-line intersects with side defined by (p2,d2)
261
//
262
// C1 and C2 can be computed in the following way:
263
// Let n = d1 x d2 - then vector n is perpendicular to both d1 and d2 --> (c1-c2) is
264
// parallel to n.
265
// There exist real numbers A,B,C such that
266
// c1 = p1 + A*d1
267
// c2 = p2 + B*d2 and
268
// c2 = c1 + C*n so that
269
// p1 + A*d1 + C*n = p2 + B*d2  --> (p1-p2) + A*d1 = B*d2 - C*n (*)
270
// Let n2 = n x d2. Let's multiply both sides of (*) by n2. Then
271
// (p1-p2)*n2 + A*(d1*n2) = 0 (0 because d1*n2 = n*n2 = 0)
272
// and from that A = [(p1-p2)*n2]/[d1*n2]
273
// Similarly     B = [(p2-p1)*n1]/[d2*n1]  where n1 = n x d1.
274

    
275
  private boolean isInside(float[] point, float[][] vertices)
276
    {
277
    float e1x = (vertices[0][0]+vertices[1][0])/2;
278
    float e1y = (vertices[0][1]+vertices[1][1])/2;
279
    float e1z = (vertices[0][2]+vertices[1][2])/2;
280

    
281
    float d1x = e1x - point[0];
282
    float d1y = e1y - point[1];
283
    float d1z = e1z - point[2];
284

    
285
    float ax = vertices[0][0] - vertices[1][0];
286
    float ay = vertices[0][1] - vertices[1][1];
287
    float az = vertices[0][2] - vertices[1][2];
288

    
289
    float normX = d1y*az - d1z*ay;
290
    float normY = d1z*ax - d1x*az;
291
    float normZ = d1x*ay - d1y*ax;
292

    
293
    float n1x = d1y*normZ - d1z*normY;
294
    float n1y = d1z*normX - d1x*normZ;
295
    float n1z = d1x*normY - d1y*normX;
296

    
297
    float p1x = point[0];
298
    float p1y = point[1];
299
    float p1z = point[2];
300

    
301
    int len = vertices.length;
302
    int numCrossings = 0;
303

    
304
    for(int side=0; side<len; side++)
305
      {
306
      float p2x = vertices[side][0];
307
      float p2y = vertices[side][1];
308
      float p2z = vertices[side][2];
309

    
310
      int next = side==len-1 ? 0 : side+1;
311

    
312
      float e2x = vertices[next][0];
313
      float e2y = vertices[next][1];
314
      float e2z = vertices[next][2];
315

    
316
      float d2x = e2x-p2x;
317
      float d2y = e2y-p2y;
318
      float d2z = e2z-p2z;
319

    
320
      float nx = d2y*d1z - d2z*d1y;
321
      float ny = d2z*d1x - d2x*d1z;
322
      float nz = d2x*d1y - d2y*d1x;
323

    
324
      float n2x = d2y*nz - d2z*ny;
325
      float n2y = d2z*nx - d2x*nz;
326
      float n2z = d2x*ny - d2y*nx;
327

    
328
      float dpx = p1x-p2x;
329
      float dpy = p1y-p2y;
330
      float dpz = p1z-p2z;
331

    
332
      float A1 =-dpx*n2x-dpy*n2y-dpz*n2z;
333
      float B1 = d1x*n2x+d1y*n2y+d1z*n2z;
334

    
335
      float A2 = dpx*n1x+dpy*n1y+dpz*n1z;
336
      float B2 = d2x*n1x+d2y*n1y+d2z*n1z;
337

    
338
      if( B1==0 || B2==0 ) continue;
339

    
340
      float C1 = A1/B1;
341
      float C2 = A2/B2;
342

    
343
      float c1x = p1x + C1*d1x;
344
      float c1y = p1y + C1*d1y;
345
      float c1z = p1z + C1*d1z;
346

    
347
      float c2x = p2x + C2*d2x;
348
      float c2y = p2y + C2*d2y;
349
      float c2z = p2z + C2*d2z;
350

    
351
      if( !isBetween(c1x,c1y,c1z, p1x,p1y,p1z, e1x,e1y,e1z ) &&
352
           isBetween(p2x,p2y,p2z, c2x,c2y,c2z, e2x,e2y,e2z )  )
353
        {
354
        numCrossings++;
355
        }
356
      }
357

    
358
    return (numCrossings%2)==1;
359
    }
360

    
361
///////////////////////////////////////////////////////////////////////////////////////////////////
362

    
363
  private void rotateVertices(float[][] points, float[][] rotated, float[] quat)
364
    {
365
    int numPoints = points.length;
366

    
367
    for(int i=0; i<numPoints; i++)
368
      {
369
      QuatHelper.rotateVectorByQuat(rotated[i],points[i],quat);
370
      }
371
    }
372

    
373
///////////////////////////////////////////////////////////////////////////////////////////////////
374
// given precomputed mCamera and mPoint, respectively camera and touch point positions in ScreenSpace,
375
// a normalVec (nx,ny,nz) and distance (which together define a plane) compute point 'output[]' which:
376
// 1) lies on this plane
377
// 2) is co-linear with mCamera and mPoint
378
//
379
// output = camera + alpha*(point-camera), where alpha = [dist-normalVec*camera] / [normalVec*(point-camera)]
380

    
381
  void castTouchPointOntoFace(float nx, float ny, float nz, float distance, float[] output)
382
    {
383
    float d0 = mPoint[0]-mCamera[0];
384
    float d1 = mPoint[1]-mCamera[1];
385
    float d2 = mPoint[2]-mCamera[2];
386

    
387
    float denom = nx*d0 + ny*d1 + nz*d2;
388

    
389
    if( denom != 0.0f )
390
      {
391
      float axisCam = nx*mCamera[0] + ny*mCamera[1] + nz*mCamera[2];
392
      float alpha = (distance-axisCam)/denom;
393

    
394
      output[0] = mCamera[0] + d0*alpha;
395
      output[1] = mCamera[1] + d1*alpha;
396
      output[2] = mCamera[2] + d2*alpha;
397
      }
398
    }
399

    
400
///////////////////////////////////////////////////////////////////////////////////////////////////
401

    
402
  private boolean cubitFaceIsVisible(float nx, float ny, float nz, float distance)
403
    {
404
    return mCamera[0]*nx + mCamera[1]*ny + mCamera[2]*nz > distance;
405
    }
406

    
407
///////////////////////////////////////////////////////////////////////////////////////////////////
408
// FaceInfo defines a 3D plane (by means of a unit normal vector 'vector' and distance from the origin
409
// 'distance') and a list of points on the plane ('vertices').
410
//
411
// 0) rotate the face normal vector by quat
412
// 1) see if the face is visible. If not, return NOT_TOUCHED
413
// 2) else, cast the line passing through mPoint and mCamera onto this plane
414
// 3) if Z of this point is further from us than the already computed closestSoFar, return NOT_TOUCHED
415
// 4) else, rotate 'vertices' by quat and see if the casted point lies inside the polygon defined by them
416
// 5) if yes, return the distance form this point to the camera; otherwise, return NOT_TOUCHED
417

    
418
  private float cubitFaceTouched(FaceInfo info, float[] quat, float closestSoFar)
419
    {
420
    QuatHelper.rotateVectorByQuat(mTmp,info.normal,quat);
421
    float nx = mTmp[0];
422
    float ny = mTmp[1];
423
    float nz = mTmp[2];
424

    
425
    if( cubitFaceIsVisible(nx,ny,nz,info.distance) )
426
      {
427
      castTouchPointOntoFace(nx,ny,nz,info.distance,mTouch);
428

    
429
      float dx = mTouch[0]-mCamera[0];
430
      float dy = mTouch[1]-mCamera[1];
431
      float dz = mTouch[2]-mCamera[2];
432
      float dist = dx*dx + dy*dy + dz*dz;
433

    
434
      if( dist<closestSoFar )
435
        {
436
        rotateVertices(info.vertices,info.rotated,quat);
437
        if( isInside(mTouch,info.rotated) ) return dist;
438
        }
439
      }
440

    
441
    return NOT_TOUCHED;
442
    }
443

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

    
446
  int computeRow(int cubit, int rotIndex)
447
    {
448
    int row = mObject.getCubitRotRow(cubit,rotIndex);
449

    
450
    for(int index=0; index<32; index++)
451
      {
452
      if( (row&1)==1 ) return index;
453
      row>>=1;
454
      }
455

    
456
    return 0;
457
    }
458

    
459
///////////////////////////////////////////////////////////////////////////////////////////////////
460
// PUBLIC API
461
///////////////////////////////////////////////////////////////////////////////////////////////////
462

    
463
  public boolean objectTouched(Static4D rotatedTouchPoint, Static4D rotatedCamera)
464
    {
465
    if( !mPreparationDone ) prepare();
466

    
467
    mPoint[0]  = rotatedTouchPoint.get0()/mObjectRatio;
468
    mPoint[1]  = rotatedTouchPoint.get1()/mObjectRatio;
469
    mPoint[2]  = rotatedTouchPoint.get2()/mObjectRatio;
470

    
471
    mCamera[0] = rotatedCamera.get0()/mObjectRatio;
472
    mCamera[1] = rotatedCamera.get1()/mObjectRatio;
473
    mCamera[2] = rotatedCamera.get2()/mObjectRatio;
474

    
475
    float closestSoFar = NOT_TOUCHED;
476
    mTouchedCubit = -1;
477
    mTouchedFace  = -1;
478
    int numQuats = mQuats.length;
479

    
480
    for(int cubit=0; cubit<mNumCubits; cubit++)
481
      {
482
      int quatIndex = mObject.getCubitQuatIndex(cubit);
483

    
484
      if( quatIndex<numQuats )
485
        {
486
        float[] quat = mQuats[quatIndex];
487

    
488
        for(int face=0; face<mNumFaces[cubit]; face++)
489
          {
490
          float dist = cubitFaceTouched(mInfos[cubit][face],quat,closestSoFar);
491

    
492
          if( dist!=NOT_TOUCHED )
493
            {
494
            mTouchedCubit= cubit;
495
            mTouchedFace = face;
496
            closestSoFar = dist;
497
            }
498
          }
499
        }
500
      }
501
/*
502
    if( closestSoFar!=NOT_TOUCHED )
503
      {
504
      android.util.Log.e("D", "cubit="+mTouchedCubit+" face="+mTouchedFace+" result: "+closestSoFar);
505
      }
506
*/
507
    return closestSoFar!=NOT_TOUCHED;
508
    }
509

    
510
///////////////////////////////////////////////////////////////////////////////////////////////////
511
// really implemented in derived classes; here present only because we need to be able to
512
// instantiate an object of this class for MODE_REPLACE.
513

    
514
  public void newRotation(int[] output, Static4D rotatedTouchPoint, Static4D quat)
515
    {
516

    
517
    }
518

    
519
///////////////////////////////////////////////////////////////////////////////////////////////////
520

    
521
  public void getCastedRotAxis(float[] output, Static4D quat, int rotIndex)
522
    {
523
    Static3D rotAxis = mRotAxis[rotIndex];
524
    float rx = rotAxis.get0();
525
    float ry = rotAxis.get1();
526
    float rz = rotAxis.get2();
527

    
528
    mTmpAxis.set(rx,ry,rz,0);
529
    Static4D result = QuatHelper.rotateVectorByQuat(mTmpAxis, quat);
530

    
531
    float cx =result.get0();
532
    float cy =result.get1();
533

    
534
    float len = (float)Math.sqrt(cx*cx+cy*cy);
535

    
536
    if( len!=0 )
537
      {
538
      output[0] = cx/len;
539
      output[1] = cy/len;
540
      }
541
    else
542
      {
543
      output[0] = 1;
544
      output[1] = 0;
545
      }
546
    }
547

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

    
550
  public int getTouchedCubitFace()
551
    {
552
    return mTouchedFace;
553
    }
554

    
555
///////////////////////////////////////////////////////////////////////////////////////////////////
556

    
557
  public int getTouchedCubit()
558
    {
559
    return mTouchedCubit;
560
    }
561

    
562
///////////////////////////////////////////////////////////////////////////////////////////////////
563

    
564
  public float returnRotationFactor(int[] numLayers, int row)
565
    {
566
    return 1.0f;
567
    }
568
  }
(7-7/11)