Project

General

Profile

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

library / src / main / java / org / distorted / library / type / Dynamic.java @ 2c8310b1

1
////////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2016 Leszek Koltunski  leszek@koltunski.pl                                          //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// This library is free software; you can redistribute it and/or                                 //
7
// modify it under the terms of the GNU Lesser General Public                                    //
8
// License as published by the Free Software Foundation; either                                  //
9
// version 2.1 of the License, or (at your option) any later version.                            //
10
//                                                                                               //
11
// This library 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 GNU                             //
14
// Lesser General Public License for more details.                                               //
15
//                                                                                               //
16
// You should have received a copy of the GNU Lesser General Public                              //
17
// License along with this library; if not, write to the Free Software                           //
18
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA                //
19
///////////////////////////////////////////////////////////////////////////////////////////////////
20

    
21
package org.distorted.library.type;
22

    
23
import java.util.Random;
24
import java.util.Vector;
25

    
26
///////////////////////////////////////////////////////////////////////////////////////////////////
27
/** A class to interpolate between a list of Statics.
28
* <p><ul>
29
* <li>if there is only one Point, just return it.
30
* <li>if there are two Points, linearly bounce between them
31
* <li>if there are more, interpolate a path between them. Exact way we interpolate depends on the MODE.
32
* </ul>
33
*/
34

    
35
// The way Interpolation between more than 2 Points is done:
36
// 
37
// Def: let V[i] = (V[i](x), V[i](y), V[i](z)) be the direction and speed (i.e. velocity) we have to
38
// be flying at Point P[i]
39
//
40
// Time it takes to fly though one segment P[i] --> P[i+1] : 0.0 --> 1.0
41
//
42
// We arbitrarily decide that V[i] should be equal to (|curr|*prev + |prev|*curr) / min(|prev|,|curr|)
43
// where prev = P[i]-P[i-1] and curr = P[i+1]-P[i]
44
//
45
// Given that the flight route (X(t), Y(t), Z(t)) from P(i) to P(i+1)  (0<=t<=1) has to satisfy
46
// X(0) = P[i  ](x), Y(0)=P[i  ](y), Z(0)=P[i  ](z), X'(0) = V[i  ](x), Y'(0) = V[i  ](y), Z'(0) = V[i  ](z)
47
// X(1) = P[i+1](x), Y(1)=P[i+1](y), Z(1)=P[i+1](z), X'(1) = V[i+1](x), Y'(1) = V[i+1](y), Z'(1) = V[i+1](z)
48
//
49
// we have the solution:  X(t) = at^3 + bt^2 + ct + d where
50
// a =  2*P[i](x) +   V[i](x) - 2*P[i+1](x) + V[i+1](x)
51
// b = -3*P[i](x) - 2*V[i](x) + 3*P[i+1](x) - V[i+1](x)
52
// c =                V[i](x)
53
// d =    P[i](x)
54
//
55
// and similarly Y(t) and Z(t).
56

    
57
public abstract class Dynamic
58
  {
59
  /**
60
   * Keep the speed of interpolation always changing. Time to cover one segment (distance between
61
   * two consecutive points) always the same. Smoothly interpolate the speed between two segments.
62
   */
63
  public static final int SPEED_MODE_SMOOTH            = 0;
64
  /**
65
   * Make each segment have constant speed. Time to cover each segment is still the same, thus the
66
   * speed will jump when passing through a point and then keep constant.
67
   */
68
  public static final int SPEED_MODE_SEGMENT_CONSTANT  = 1;
69
  /**
70
   * Have the speed be always, globally the same across all segments. Time to cover one segment will
71
   * thus generally no longer be the same.
72
   */
73
  public static final int SPEED_MODE_GLOBALLY_CONSTANT = 2;  // TODO: not supported yet
74

    
75
  /**
76
   * One revolution takes us from the first point to the last and back to first through the shortest path.
77
   */
78
  public static final int MODE_LOOP = 0; 
79
  /**
80
   * One revolution takes us from the first point to the last and back to first through the same path.
81
   */
82
  public static final int MODE_PATH = 1; 
83
  /**
84
   * One revolution takes us from the first point to the last and jumps straight back to the first point.
85
   */
86
  public static final int MODE_JUMP = 2; 
87

    
88
  /**
89
   * The default mode of access. When in this mode, we are able to call interpolate() with points in time
90
   * in any random order. This means one single Dynamic can be used in many effects simultaneously.
91
   * On the other hand, when in this mode, it is not possible to smoothly interpolate when mDuration suddenly
92
   * changes.
93
   */
94
  public static final int ACCESS_TYPE_RANDOM     = 0;
95
  /**
96
   * Set the mode to ACCESS_SEQUENTIAL if you need to change mDuration and you would rather have the Dynamic
97
   * keep on smoothly interpolating.
98
   * On the other hand, in this mode, a Dynamic can only be accessed in sequential manner, which means one
99
   * Dynamic can only be used in one effect at a time.
100
   */
101
  public static final int ACCESS_TYPE_SEQUENTIAL = 1;
102

    
103
  protected int mDimension;
104
  protected int numPoints;
105
  protected int mSegment;       // between which pair of points are we currently? (in case of PATH this is a bit complicated!)
106
  protected boolean cacheDirty; // VectorCache not up to date
107
  protected int mMode;          // LOOP, PATH or JUMP
108
  protected long mDuration;     // number of milliseconds it takes to do a full loop/path from first vector to the last and back to the first
109
  protected float mCount;       // number of loops/paths we will do; mCount = 1.5 means we go from the first vector to the last, back to first, and to the last again. 
110
  protected double mLastPos;
111
  protected int mAccessType;
112
  protected int mSpeedMode;
113
  protected float mTmpTime;
114
  protected int mTmpVec, mTmpSeg;
115

    
116
  protected class VectorNoise
117
    {
118
    float[][] n;
119

    
120
    VectorNoise()
121
      {
122
      n = new float[mDimension][NUM_NOISE];
123
      }
124

    
125
    void computeNoise()
126
      {
127
      n[0][0] = mRnd.nextFloat();
128
      for(int i=1; i<NUM_NOISE; i++) n[0][i] = n[0][i-1]+mRnd.nextFloat();
129

    
130
      float sum = n[0][NUM_NOISE-1] + mRnd.nextFloat();
131

    
132
      for(int i=0; i<NUM_NOISE; i++)
133
        {
134
        n[0][i] /=sum;
135
        for(int j=1; j<mDimension; j++) n[j][i] = mRnd.nextFloat()-0.5f;
136
        }
137
      }
138
    }
139

    
140
  protected Vector<VectorNoise> vn;
141
  protected float[] mFactor;
142
  protected float[] mNoise;
143
  protected float[][] baseV;
144

    
145
  ///////////////////////////////////////////////////////////////////////////////////////////////////
146
  // the coefficients of the X(t), Y(t) and Z(t) polynomials: X(t) = a[0]*T^3 + b[0]*T^2 + c[0]*t + d[0]  etc.
147
  // (velocity) is the velocity vector.
148
  // (cached) is the original vector from vv (copied here so when interpolating we can see if it is
149
  // still valid and if not - rebuild the Cache
150

    
151
  protected class VectorCache
152
    {
153
    float[] a;
154
    float[] b;
155
    float[] c;
156
    float[] d;
157
    float[] velocity;
158
    float[] cached;
159
    float[] path_ratio;
160

    
161
    VectorCache()
162
      {
163
      a = new float[mDimension];
164
      b = new float[mDimension];
165
      c = new float[mDimension];
166
      d = new float[mDimension];
167

    
168
      velocity   = new float[mDimension];
169
      cached     = new float[mDimension];
170
      path_ratio = new float[NUM_RATIO];
171
      }
172
    }
173

    
174
  protected Vector<VectorCache> vc;
175
  protected VectorCache tmpCache1, tmpCache2;
176
  protected float mConvexity;
177

    
178
  private static final int NUM_RATIO = 10; // we attempt to 'smooth out' the speed in each segment -
179
                                           // remember this many 'points' inside the Cache for each segment.
180

    
181
  protected static final float[] mTmpRatio = new float[NUM_RATIO];
182

    
183
  private float[] buf;
184
  private float[] old;
185
  private static final Random mRnd = new Random();
186
  private static final int NUM_NOISE = 5; // used iff mNoise>0.0. Number of intermediary points between each pair of adjacent vectors
187
                                          // where we randomize noise factors to make the way between the two vectors not so smooth.
188
  private long mStartTime;
189
  private long mCorrectedTime;
190
  private static long mPausedTime;
191

    
192
///////////////////////////////////////////////////////////////////////////////////////////////////
193
// hide this from Javadoc
194
  
195
  protected Dynamic()
196
    {
197

    
198
    }
199

    
200
///////////////////////////////////////////////////////////////////////////////////////////////////
201

    
202
  protected Dynamic(int duration, float count, int dimension)
203
    {
204
    vc         = new Vector<>();
205
    vn         = null;
206
    numPoints  = 0;
207
    cacheDirty = false;
208
    mMode      = MODE_LOOP;
209
    mDuration  = duration;
210
    mCount     = count;
211
    mDimension = dimension;
212
    mSegment   = -1;
213
    mLastPos   = -1;
214
    mAccessType= ACCESS_TYPE_RANDOM;
215
    mSpeedMode = SPEED_MODE_SMOOTH;
216
    mConvexity = 1.0f;
217
    mStartTime = -1;
218
    mCorrectedTime = 0;
219

    
220
    baseV      = new float[mDimension][mDimension];
221
    buf        = new float[mDimension];
222
    old        = new float[mDimension];
223
    }
224

    
225
///////////////////////////////////////////////////////////////////////////////////////////////////
226

    
227
  void initDynamic()
228
    {
229
    mStartTime = -1;
230
    mCorrectedTime = 0;
231
    }
232

    
233
///////////////////////////////////////////////////////////////////////////////////////////////////
234

    
235
  public static void onPause()
236
    {
237
    mPausedTime = System.currentTimeMillis();
238
    }
239

    
240
///////////////////////////////////////////////////////////////////////////////////////////////////
241

    
242
  protected void computeSegmentAndTime(float time)
243
    {
244
    switch(mMode)
245
      {
246
      case MODE_LOOP: mTmpTime= time*numPoints;
247
                      mTmpSeg = (int)mTmpTime;
248
                      mTmpVec = mTmpSeg;
249
                      break;
250
      case MODE_PATH: mTmpSeg = (int)(2*time*(numPoints-1));
251

    
252
                      if( time<=0.5f )  // this has to be <= (otherwise when effect ends at t=0.5, then time=1.0
253
                        {               // and end position is slightly not equal to the end point => might not get autodeleted!
254
                        mTmpTime = 2*time*(numPoints-1);
255
                        mTmpVec = mTmpSeg;
256
                        }
257
                      else
258
                        {
259
                        mTmpTime = 2*(1-time)*(numPoints-1);
260
                        mTmpVec  = 2*numPoints-3-mTmpSeg;
261
                        }
262
                      break;
263
      case MODE_JUMP: mTmpTime= time*(numPoints-1);
264
                      mTmpSeg = (int)mTmpTime;
265
                      mTmpVec = mTmpSeg;
266
                      break;
267
      default       : mTmpVec = 0;
268
                      mTmpSeg = 0;
269
      }
270
    }
271

    
272
///////////////////////////////////////////////////////////////////////////////////////////////////
273

    
274
  private float valueAtPoint(float t, VectorCache cache)
275
    {
276
    float tmp,sum = 0.0f;
277

    
278
    for(int d=0; d<mDimension; d++)
279
      {
280
      tmp = (3*cache.a[d]*t + 2*cache.b[d])*t + cache.c[d];
281
      sum += tmp*tmp;
282
      }
283

    
284
    return (float)Math.sqrt(sum);
285
    }
286

    
287
///////////////////////////////////////////////////////////////////////////////////////////////////
288

    
289
  protected float smoothSpeed(float time, VectorCache cache)
290
    {
291
    float fndex = time*NUM_RATIO;
292
    int index = (int)fndex;
293
    float prev = index==0 ? 0.0f : cache.path_ratio[index-1];
294
    float next = cache.path_ratio[index];
295

    
296
    return prev + (next-prev)*(fndex-index);
297
    }
298

    
299
///////////////////////////////////////////////////////////////////////////////////////////////////
300
// First, compute the approx length of the segment from time=0 to time=(i+1)/NUM_TIME and store this
301
// in cache.path_ratio[i]. Then the last path_ratio is the length from 0 to 1, i.e. the total length
302
// of the segment.
303
// We do this by computing the integral from 0 to 1 of sqrt( (dx/dt)^2 + (dy/dt)^2 ) (i.e. the length
304
// of the segment) using the approx 'trapezoids' integration method.
305
//
306
// Then, for every i, divide path_ratio[i] by the total length to get the percentage of total path
307
// length covered at time i. At this time, path_ratio[3] = 0.45 means 'at time 3/NUM_RATIO, we cover
308
// 0.45 = 45% of the total length of the segment.
309
//
310
// Finally, invert this function (for quicker lookups in smoothSpeed) so that after this step,
311
// path_ratio[3] = 0.45 means 'at 45% of the time, we cover 3/NUM_RATIO distance'.
312

    
313
  protected void smoothOutSegment(VectorCache cache)
314
    {
315
    float vPrev, sum = 0.0f;
316
    float vNext = valueAtPoint(0.0f,cache);
317

    
318
    for(int i=0; i<NUM_RATIO; i++)
319
      {
320
      vPrev = vNext;
321
      vNext = valueAtPoint( (float)(i+1)/NUM_RATIO,cache);
322
      sum += (vPrev+vNext);
323
      cache.path_ratio[i] = sum;
324
      }
325

    
326
    float total = cache.path_ratio[NUM_RATIO-1];
327

    
328
    for(int i=0; i<NUM_RATIO; i++) cache.path_ratio[i] /= total;
329

    
330
    int writeIndex = 0;
331
    float prev=0.0f, next, ratio= 1.0f/NUM_RATIO;
332

    
333
    for(int readIndex=0; readIndex<NUM_RATIO; readIndex++)
334
      {
335
      next = cache.path_ratio[readIndex];
336

    
337
      while( prev<ratio && ratio<=next )
338
        {
339
        float a = (next-ratio)/(next-prev);
340
        mTmpRatio[writeIndex] = (readIndex+1-a)/NUM_RATIO;
341
        writeIndex++;
342
        ratio = (writeIndex+1.0f)/NUM_RATIO;
343
        }
344

    
345
      prev = next;
346
      }
347

    
348
    System.arraycopy(mTmpRatio, 0, cache.path_ratio, 0, NUM_RATIO);
349
    }
350

    
351
///////////////////////////////////////////////////////////////////////////////////////////////////
352

    
353
  protected float noise(float time,int vecNum)
354
    {
355
    float lower, upper, len;
356
    float d = time*(NUM_NOISE+1);
357
    int index = (int)d;
358
    if( index>=NUM_NOISE+1 ) index=NUM_NOISE;
359
    VectorNoise tmpN = vn.elementAt(vecNum);
360

    
361
    float t = d-index;
362
    t = t*t*(3-2*t);
363

    
364
    switch(index)
365
      {
366
      case 0        : for(int i=0;i<mDimension-1;i++) mFactor[i] = mNoise[i+1]*tmpN.n[i+1][0]*t;
367
                      return time + mNoise[0]*(d*tmpN.n[0][0]-time);
368
      case NUM_NOISE: for(int i=0;i<mDimension-1;i++) mFactor[i] = mNoise[i+1]*tmpN.n[i+1][NUM_NOISE-1]*(1-t);
369
                      len = ((float)NUM_NOISE)/(NUM_NOISE+1);
370
                      lower = len + mNoise[0]*(tmpN.n[0][NUM_NOISE-1]-len);
371
                      return (1.0f-lower)*(d-NUM_NOISE) + lower;
372
      default       : float ya,yb;
373

    
374
                      for(int i=0;i<mDimension-1;i++)
375
                        {
376
                        yb = tmpN.n[i+1][index  ];
377
                        ya = tmpN.n[i+1][index-1];
378
                        mFactor[i] = mNoise[i+1]*((yb-ya)*t+ya);
379
                        }
380

    
381
                      len = ((float)index)/(NUM_NOISE+1);
382
                      lower = len + mNoise[0]*(tmpN.n[0][index-1]-len);
383
                      len = ((float)index+1)/(NUM_NOISE+1);
384
                      upper = len + mNoise[0]*(tmpN.n[0][index  ]-len);
385

    
386
                      return (upper-lower)*(d-index) + lower;
387
      }
388
    }
389

    
390
///////////////////////////////////////////////////////////////////////////////////////////////////
391
// debugging only
392

    
393
  private void printBase(String str)
394
    {
395
    String s;
396
    float t;
397

    
398
    for(int i=0; i<mDimension; i++)
399
      {
400
      s = "";
401

    
402
      for(int j=0; j<mDimension; j++)
403
        {
404
        t = ((int)(1000*baseV[i][j]))/(1000.0f);
405
        s+=(" "+t);
406
        }
407
      android.util.Log.e("dynamic", str+" base "+i+" : " + s);
408
      }
409
    }
410

    
411
///////////////////////////////////////////////////////////////////////////////////////////////////
412
// debugging only
413

    
414
  @SuppressWarnings("unused")
415
  private void checkBase()
416
    {
417
    float tmp, cosA;
418
    float[] len= new float[mDimension];
419
    boolean error=false;
420

    
421
    for(int i=0; i<mDimension; i++)
422
      {
423
      len[i] = 0.0f;
424

    
425
      for(int k=0; k<mDimension; k++)
426
        {
427
        len[i] += baseV[i][k]*baseV[i][k];
428
        }
429

    
430
      if( len[i] == 0.0f || len[0]/len[i] < 0.95f || len[0]/len[i]>1.05f )
431
        {
432
        android.util.Log.e("dynamic", "length of vector "+i+" : "+Math.sqrt(len[i]));
433
        error = true;
434
        }
435
      }
436

    
437
    for(int i=0; i<mDimension; i++)
438
      for(int j=i+1; j<mDimension; j++)
439
        {
440
        tmp = 0.0f;
441

    
442
        for(int k=0; k<mDimension; k++)
443
          {
444
          tmp += baseV[i][k]*baseV[j][k];
445
          }
446

    
447
        cosA = ( (len[i]==0.0f || len[j]==0.0f) ? 0.0f : tmp/(float)Math.sqrt(len[i]*len[j]));
448

    
449
        if( cosA > 0.05f || cosA < -0.05f )
450
          {
451
          android.util.Log.e("dynamic", "cos angle between vectors "+i+" and "+j+" : "+cosA);
452
          error = true;
453
          }
454
        }
455

    
456
    if( error ) printBase("");
457
    }
458

    
459
///////////////////////////////////////////////////////////////////////////////////////////////////
460

    
461
  int getNext(int curr, float time)
462
    {
463
    switch(mMode)
464
      {
465
      case MODE_LOOP: return curr==numPoints-1 ? 0:curr+1;
466
      case MODE_PATH: return time<0.5f ? (curr+1) : (curr==0 ? 1 : curr-1);
467
      case MODE_JUMP: return curr==numPoints-1 ? 1:curr+1;
468
      default       : return 0;
469
      }
470
    }
471

    
472
///////////////////////////////////////////////////////////////////////////////////////////////////
473

    
474
  private void checkAngle(int index)
475
    {
476
    float cosA = 0.0f;
477

    
478
    for(int k=0;k<mDimension; k++)
479
      cosA += baseV[index][k]*old[k];
480

    
481
    if( cosA<0.0f )
482
      {
483
      for(int j=0; j<mDimension; j++)
484
        baseV[index][j] = -baseV[index][j];
485
      }
486
    }
487

    
488
///////////////////////////////////////////////////////////////////////////////////////////////////
489
// helper function in case we are interpolating through exactly 2 points
490

    
491
  protected void computeOrthonormalBase2(Static curr, Static next)
492
    {
493
    switch(mDimension)
494
      {
495
      case 1: Static1D curr1 = (Static1D)curr;
496
              Static1D next1 = (Static1D)next;
497
              baseV[0][0] = (next1.x-curr1.x);
498
              break;
499
      case 2: Static2D curr2 = (Static2D)curr;
500
              Static2D next2 = (Static2D)next;
501
              baseV[0][0] = (next2.x-curr2.x);
502
              baseV[0][1] = (next2.y-curr2.y);
503
              break;
504
      case 3: Static3D curr3 = (Static3D)curr;
505
              Static3D next3 = (Static3D)next;
506
              baseV[0][0] = (next3.x-curr3.x);
507
              baseV[0][1] = (next3.y-curr3.y);
508
              baseV[0][2] = (next3.z-curr3.z);
509
              break;
510
      case 4: Static4D curr4 = (Static4D)curr;
511
              Static4D next4 = (Static4D)next;
512
              baseV[0][0] = (next4.x-curr4.x);
513
              baseV[0][1] = (next4.y-curr4.y);
514
              baseV[0][2] = (next4.z-curr4.z);
515
              baseV[0][3] = (next4.w-curr4.w);
516
              break;
517
      case 5: Static5D curr5 = (Static5D)curr;
518
              Static5D next5 = (Static5D)next;
519
              baseV[0][0] = (next5.x-curr5.x);
520
              baseV[0][1] = (next5.y-curr5.y);
521
              baseV[0][2] = (next5.z-curr5.z);
522
              baseV[0][3] = (next5.w-curr5.w);
523
              baseV[0][4] = (next5.v-curr5.v);
524
              break;
525
      default: throw new RuntimeException("Unsupported dimension");
526
      }
527

    
528
    if( baseV[0][0] == 0.0f )
529
      {
530
      baseV[1][0] = 1.0f;
531
      baseV[1][1] = 0.0f;
532
      }
533
    else
534
      {
535
      baseV[1][0] = 0.0f;
536
      baseV[1][1] = 1.0f;
537
      }
538

    
539
    for(int i=2; i<mDimension; i++)
540
      {
541
      baseV[1][i] = 0.0f;
542
      }
543

    
544
    computeOrthonormalBase();
545
    }
546

    
547
///////////////////////////////////////////////////////////////////////////////////////////////////
548
// helper function in case we are interpolating through more than 2 points
549

    
550
  protected void computeOrthonormalBaseMore(float time,VectorCache vc)
551
    {
552
    for(int i=0; i<mDimension; i++)
553
      {
554
      baseV[0][i] = (3*vc.a[i]*time+2*vc.b[i])*time+vc.c[i];   // first derivative, i.e. velocity vector
555
      old[i]      = baseV[1][i];
556
      baseV[1][i] =  6*vc.a[i]*time+2*vc.b[i];                 // second derivative,i.e. acceleration vector
557
      }
558

    
559
    computeOrthonormalBase();
560
    }
561

    
562
///////////////////////////////////////////////////////////////////////////////////////////////////
563
// When this function gets called, baseV[0] and baseV[1] should have been filled with two mDimension-al
564
// vectors. This function then fills the rest of the baseV array with a mDimension-al Orthonormal base.
565
// (mDimension-2 vectors, pairwise orthogonal to each other and to the original 2). The function always
566
// leaves base[0] alone but generally speaking must adjust base[1] to make it orthogonal to base[0]!
567
// The whole baseV is then used to compute Noise.
568
//
569
// When computing noise of a point travelling along a N-dimensional path, there are three cases:
570
// a) we may be interpolating through 1 point, i.e. standing in place - nothing to do in this case
571
// b) we may be interpolating through 2 points, i.e. travelling along a straight line between them -
572
//    then pass the velocity vector in baseV[0] and anything linearly independent in base[1].
573
//    The output will then be discontinuous in dimensions>2 (sad corollary from the Hairy Ball Theorem)
574
//    but we don't care - we are travelling along a straight line, so velocity (aka baseV[0]!) does
575
//    not change.
576
// c) we may be interpolating through more than 2 points. Then interpolation formulas ensure the path
577
//    will never be a straight line, even locally -> we can pass in baseV[0] and baseV[1] the velocity
578
//    and the acceleration (first and second derivatives of the path) which are then guaranteed to be
579
//    linearly independent. Then we can ensure this is continuous in dimensions <=4. This leaves
580
//    dimension 5 (ATM WAVE is 5-dimensional) discontinuous -> WAVE will suffer from chaotic noise.
581
//
582
// Bear in mind here the 'normal' in 'orthonormal' means 'length equal to the length of the original
583
// velocity vector' (rather than the standard 1)
584

    
585
  protected void computeOrthonormalBase()
586
    {
587
    int last_non_zero=-1;
588
    float tmp;
589

    
590
    for(int i=0; i<mDimension; i++)
591
      if( baseV[0][i] != 0.0f )
592
        last_non_zero=i;
593

    
594
    if( last_non_zero==-1 )                                               ///
595
      {                                                                   //  velocity is the 0 vector -> two
596
      for(int i=0; i<mDimension-1; i++)                                   //  consecutive points we are interpolating
597
        for(int j=0; j<mDimension; j++)                                   //  through are identical -> no noise,
598
          baseV[i+1][j]= 0.0f;                                            //  set the base to 0 vectors.
599
      }                                                                   ///
600
    else
601
      {
602
      for(int i=1; i<mDimension; i++)                                     /// One iteration computes baseV[i][*]
603
        {                                                                 //  (aka b[i]), the i-th orthonormal vector.
604
        buf[i-1]=0.0f;                                                    //
605
                                                                          //  We can use (modified!) Gram-Schmidt.
606
        for(int k=0; k<mDimension; k++)                                   //
607
          {                                                               //
608
          if( i>=2 )                                                      //  b[0] = b[0]
609
            {                                                             //  b[1] = b[1] - (<b[1],b[0]>/<b[0],b[0]>)*b[0]
610
            old[k] = baseV[i][k];                                         //  b[2] = b[2] - (<b[2],b[0]>/<b[0],b[0]>)*b[0] - (<b[2],b[1]>/<b[1],b[1]>)*b[1]
611
            baseV[i][k]= (k==i-(last_non_zero>=i?1:0)) ? 1.0f : 0.0f;     //  b[3] = b[3] - (<b[3],b[0]>/<b[0],b[0]>)*b[0] - (<b[3],b[1]>/<b[1],b[1]>)*b[1] - (<b[3],b[2]>/<b[2],b[2]>)*b[2]
612
            }                                                             //  (...)
613
                                                                          //  then b[i] = b[i] / |b[i]|  ( Here really b[i] = b[i] / (|b[0]|/|b[i]|)
614
          tmp = baseV[i-1][k];                                            //
615
          buf[i-1] += tmp*tmp;                                            //
616
          }                                                               //
617
                                                                          //
618
        for(int j=0; j<i; j++)                                            //
619
          {                                                               //
620
          tmp = 0.0f;                                                     //
621
          for(int k=0;k<mDimension; k++) tmp += baseV[i][k]*baseV[j][k];  //
622
          tmp /= buf[j];                                                  //
623
          for(int k=0;k<mDimension; k++) baseV[i][k] -= tmp*baseV[j][k];  //
624
          }                                                               //
625
                                                                          //
626
        checkAngle(i);                                                    //
627
        }                                                                 /// end compute baseV[i][*]
628

    
629
      buf[mDimension-1]=0.0f;                                             /// Normalize
630
      for(int k=0; k<mDimension; k++)                                     //
631
        {                                                                 //
632
        tmp = baseV[mDimension-1][k];                                     //
633
        buf[mDimension-1] += tmp*tmp;                                     //
634
        }                                                                 //
635
                                                                          //
636
      for(int i=1; i<mDimension; i++)                                     //
637
        {                                                                 //
638
        tmp = (float)Math.sqrt(buf[0]/buf[i]);                            //
639
        for(int k=0;k<mDimension; k++) baseV[i][k] *= tmp;                //
640
        }                                                                 /// End Normalize
641
      }
642
    }
643

    
644
///////////////////////////////////////////////////////////////////////////////////////////////////
645

    
646
  abstract void interpolate(float[] buffer, int offset, float time);
647

    
648
///////////////////////////////////////////////////////////////////////////////////////////////////
649
// PUBLIC API
650
///////////////////////////////////////////////////////////////////////////////////////////////////
651

    
652
/**
653
 * Sets the mode of the interpolation to Loop, Path or Jump.
654
 * <ul>
655
 * <li>Loop is when we go from the first point all the way to the last, and the back to the first through 
656
 * the shortest way.
657
 * <li>Path is when we come back from the last point back to the first the same way we got there.
658
 * <li>Jump is when we go from first to last and then jump straight back to the first.
659
 * </ul>
660
 * 
661
 * @param mode {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
662
 */
663
  public void setMode(int mode)
664
    {
665
    mMode = mode;  
666
    }
667

    
668
///////////////////////////////////////////////////////////////////////////////////////////////////
669
/**
670
 * Returns the number of Points this Dynamic has been fed with.
671
 *   
672
 * @return the number of Points we are currently interpolating through.
673
 */
674
  public synchronized int getNumPoints()
675
    {
676
    return numPoints;  
677
    }
678

    
679
///////////////////////////////////////////////////////////////////////////////////////////////////
680
/**
681
 * Sets how many revolutions we want to do.
682
 * <p>
683
 * Does not have to be an integer. What constitutes 'one revolution' depends on the MODE:
684
 * {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
685
 * Count<=0 means 'go on interpolating indefinitely'.
686
 * 
687
 * @param count the number of times we want to interpolate between our collection of Points.
688
 */
689
  public void setCount(float count)
690
    {
691
    mCount = count;  
692
    }
693

    
694
///////////////////////////////////////////////////////////////////////////////////////////////////
695
/**
696
 * Return the number of revolutions this Dynamic will make.
697
 * What constitutes 'one revolution' depends on the MODE:
698
 * {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
699
 *
700
 * @return the number revolutions this Dynamic will make.
701
 */
702
  public float getCount()
703
    {
704
    return mCount;
705
    }
706

    
707
///////////////////////////////////////////////////////////////////////////////////////////////////
708
/**
709
 * Start running from the beginning again.
710
 *
711
 * If a Dynamic has been used already, and we want to use it again and start interpolating from the
712
 * first Point, first we need to reset it using this method.
713
 */
714
  public void resetToBeginning()
715
    {
716
    mStartTime = -1;
717
    }
718

    
719
///////////////////////////////////////////////////////////////////////////////////////////////////
720
/**
721
 * @param duration Number of milliseconds one revolution will take.
722
 *                 What constitutes 'one revolution' depends on the MODE:
723
 *                 {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
724
 */
725
  public void setDuration(long duration)
726
    {
727
    mDuration = duration;
728
    }
729

    
730
///////////////////////////////////////////////////////////////////////////////////////////////////
731
/**
732
 * @return Number of milliseconds one revolution will take.
733
 */
734
  public long getDuration()
735
    {
736
    return mDuration;
737
    }
738

    
739
///////////////////////////////////////////////////////////////////////////////////////////////////
740
/**
741
 * @param convexity If set to the default (1.0f) then interpolation between 4 points
742
 *                  (1,0) (0,1) (-1,0) (0,-1) will be the natural circle centered at (0,0) with radius 1.
743
 *                  The less it is, the less convex the circle becomes, ultimately when convexity=0.0f
744
 *                  then the interpolation shape will be straight lines connecting the four points.
745
 *                  Further setting this to negative values will make the shape concave.
746
 *                  Valid values: all floats. (although probably only something around (0,2) actually
747
 *                  makes sense)
748
 */
749
  public void setConvexity(float convexity)
750
    {
751
    if( mConvexity!=convexity )
752
      {
753
      mConvexity = convexity;
754
      cacheDirty = true;
755
      }
756
    }
757

    
758
///////////////////////////////////////////////////////////////////////////////////////////////////
759
/**
760
 * @return See {@link Dynamic#setConvexity(float)}
761
 */
762
  public float getConvexity()
763
    {
764
    return mConvexity;
765
    }
766

    
767
///////////////////////////////////////////////////////////////////////////////////////////////////
768
/**
769
 * Sets the access type this Dynamic will be working in.
770
 *
771
 * @param type {@link Dynamic#ACCESS_TYPE_RANDOM} or {@link Dynamic#ACCESS_TYPE_SEQUENTIAL}.
772
 */
773
  public void setAccessType(int type)
774
    {
775
    mAccessType = type;
776
    mLastPos = -1;
777
    }
778

    
779
///////////////////////////////////////////////////////////////////////////////////////////////////
780
/**
781
 * @return See {@link Dynamic#setSpeedMode(int)}
782
 */
783
  public float getSpeedMode()
784
    {
785
    return mSpeedMode;
786
    }
787

    
788
///////////////////////////////////////////////////////////////////////////////////////////////////
789
/**
790
 * Sets the way we compute the interpolation speed.
791
 *
792
 * @param mode {@link Dynamic#SPEED_MODE_SMOOTH} or {@link Dynamic#SPEED_MODE_SEGMENT_CONSTANT} or
793
 *             {@link Dynamic#SPEED_MODE_GLOBALLY_CONSTANT}
794
 */
795
  public void setSpeedMode(int mode)
796
    {
797
    if( mSpeedMode!=mode )
798
      {
799
      if( mSpeedMode==SPEED_MODE_SMOOTH )
800
        {
801
        for(int i=0; i<numPoints; i++)
802
          {
803
          tmpCache1 = vc.elementAt(i);
804
          smoothOutSegment(tmpCache1);
805
          }
806
        }
807

    
808
      mSpeedMode = mode;
809
      }
810
    }
811

    
812
///////////////////////////////////////////////////////////////////////////////////////////////////
813
/**
814
 * Return the Dimension, ie number of floats in a single Point this Dynamic interpolates through.
815
 *
816
 * @return number of floats in a single Point (ie its dimension) contained in the Dynamic.
817
 */
818
  public int getDimension()
819
    {
820
    return mDimension;
821
    }
822

    
823
///////////////////////////////////////////////////////////////////////////////////////////////////
824
/**
825
 * Writes the results of interpolation between the Points at time 'time' to the passed float buffer.
826
 * <p>
827
 * This version differs from the previous in that it returns a boolean value which indicates whether
828
 * the interpolation is finished.
829
 *
830
 * @param buffer Float buffer we will write the results to.
831
 * @param offset Offset in the buffer where to write the result.
832
 * @param time   Time of interpolation. Time=0.0 is the beginning of the first revolution, time=1.0 - the end
833
 *               of the first revolution, time=2.5 - the middle of the third revolution.
834
 *               What constitutes 'one revolution' depends on the MODE:
835
 *               {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
836
 * @param step   Time difference between now and the last time we called this function. Needed to figure
837
 *               out if the previous time we were called the effect wasn't finished yet, but now it is.
838
 * @return true if the interpolation reached its end.
839
 */
840
  public boolean get(float[] buffer, int offset, long time, long step)
841
    {
842
    if( mDuration<=0.0f )
843
      {
844
      interpolate(buffer,offset,mCount-(int)mCount);
845
      return false;
846
      }
847

    
848
    if( mStartTime==-1 )
849
      {
850
      mStartTime = time;
851
      mLastPos   = -1;
852
      }
853

    
854
    long diff = time-mPausedTime;
855

    
856
    if( mStartTime<mPausedTime && mCorrectedTime<mPausedTime && diff>=0 && diff<=step )
857
      {
858
      mCorrectedTime = mPausedTime;
859
      mStartTime += diff;
860
      step -= diff;
861
      }
862

    
863
    time -= mStartTime;
864

    
865
    if( time+step > mDuration*mCount && mCount>0.0f )
866
      {
867
      interpolate(buffer,offset,mCount-(int)mCount);
868
      return true;
869
      }
870

    
871
    double pos;
872

    
873
    if( mAccessType ==ACCESS_TYPE_SEQUENTIAL )
874
      {
875
      pos = mLastPos<0 ? (double)time/mDuration : (double)step/mDuration + mLastPos;
876
      mLastPos = pos;
877
      }
878
    else
879
      {
880
      pos = (double)time/mDuration;
881
      }
882

    
883
    interpolate(buffer,offset, (float)(pos-(int)pos) );
884
    return false;
885
    }
886
  }
(6-6/18)