Project

General

Profile

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

library / src / main / java / org / distorted / library / type / Dynamic.java @ 9aabc9eb

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2016 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// Distorted 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
// Distorted 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 Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
18
///////////////////////////////////////////////////////////////////////////////////////////////////
19

    
20
package org.distorted.library.type;
21

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

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

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

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

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

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

    
102
  protected int mDimension;
103
  protected int numPoints;
104
  protected int mSegment;       // between which pair of points are we currently? (in case of PATH this is a bit complicated!)
105
  protected boolean cacheDirty; // VectorCache not up to date
106
  protected int mMode;          // LOOP, PATH or JUMP
107
  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
108
  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. 
109
  protected double mLastPos;
110
  protected int mAccessType;
111
  protected int mSpeedMode;
112

    
113
  protected class VectorNoise
114
    {
115
    float[][] n;
116

    
117
    VectorNoise()
118
      {
119
      n = new float[mDimension][NUM_NOISE];
120
      }
121

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

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

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

    
137
  protected Vector<VectorNoise> vn;
138
  protected float[] mFactor;
139
  protected float[] mNoise;
140
  protected float[][] baseV;
141

    
142
  ///////////////////////////////////////////////////////////////////////////////////////////////////
143
  // 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.
144
  // (velocity) is the velocity vector.
145
  // (cached) is the original vector from vv (copied here so when interpolating we can see if it is
146
  // still valid and if not - rebuild the Cache
147

    
148
  protected class VectorCache
149
    {
150
    float[] a;
151
    float[] b;
152
    float[] c;
153
    float[] d;
154
    float[] velocity;
155
    float[] cached;
156
    float[] path_ratio;
157

    
158
    VectorCache()
159
      {
160
      a = new float[mDimension];
161
      b = new float[mDimension];
162
      c = new float[mDimension];
163
      d = new float[mDimension];
164

    
165
      velocity   = new float[mDimension];
166
      cached     = new float[mDimension];
167
      path_ratio = new float[NUM_RATIO];
168
      }
169
    }
170

    
171
  protected Vector<VectorCache> vc;
172
  protected VectorCache tmpCache1, tmpCache2;
173
  protected float mConvexity;
174

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

    
178
  protected static final float[] mTmpRatio = new float[NUM_RATIO];
179

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

    
189
///////////////////////////////////////////////////////////////////////////////////////////////////
190
// hide this from Javadoc
191
  
192
  protected Dynamic()
193
    {
194

    
195
    }
196

    
197
///////////////////////////////////////////////////////////////////////////////////////////////////
198

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

    
217
    baseV      = new float[mDimension][mDimension];
218
    buf        = new float[mDimension];
219
    old        = new float[mDimension];
220
    }
221

    
222
///////////////////////////////////////////////////////////////////////////////////////////////////
223

    
224
  void initDynamic()
225
    {
226
    mStartTime = -1;
227
    mCorrectedTime = 0;
228
    }
229

    
230
///////////////////////////////////////////////////////////////////////////////////////////////////
231

    
232
  public static void onPause()
233
    {
234
    mPausedTime = System.currentTimeMillis();
235
    }
236

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

    
239
  private float valueAtPoint(float t, VectorCache cache)
240
    {
241
    float tmp,sum = 0.0f;
242

    
243
    for(int d=0; d<mDimension; d++)
244
      {
245
      tmp = (3*cache.a[d]*t + 2*cache.b[d])*t + cache.c[d];
246
      sum += tmp*tmp;
247
      }
248

    
249
    return (float)Math.sqrt(sum);
250
    }
251

    
252
///////////////////////////////////////////////////////////////////////////////////////////////////
253

    
254
  protected float smoothSpeed(float time, VectorCache cache)
255
    {
256
    float fndex = time*NUM_RATIO;
257
    int index = (int)fndex;
258
    float prev = index==0 ? 0.0f : cache.path_ratio[index-1];
259
    float next = cache.path_ratio[index];
260

    
261
    return prev + (next-prev)*(fndex-index);
262
    }
263

    
264
///////////////////////////////////////////////////////////////////////////////////////////////////
265
// First, compute the approx length of the segment from time=0 to time=(i+1)/NUM_TIME and store this
266
// in cache.path_ratio[i]. Then the last path_ratio is the length from 0 to 1, i.e. the total length
267
// of the segment.
268
// We do this by computing the integral from 0 to 1 of sqrt( (dx/dt)^2 + (dy/dt)^2 ) (i.e. the length
269
// of the segment) using the approx 'trapezoids' integration method.
270
//
271
// Then, for every i, divide path_ratio[i] by the total length to get the percentage of total path
272
// length covered at time i. At this time, path_ratio[3] = 0.45 means 'at time 3/NUM_RATIO, we cover
273
// 0.45 = 45% of the total length of the segment.
274
//
275
// Finally, invert this function (for quicker lookups in smoothSpeed) so that after this step,
276
// path_ratio[3] = 0.45 means 'at 45% of the time, we cover 3/NUM_RATIO distance'.
277

    
278
  protected void smoothOutSegment(VectorCache cache)
279
    {
280
    float vPrev, sum = 0.0f;
281
    float vNext = valueAtPoint(0.0f,cache);
282

    
283
    for(int i=0; i<NUM_RATIO; i++)
284
      {
285
      vPrev = vNext;
286
      vNext = valueAtPoint( (float)(i+1)/NUM_RATIO,cache);
287
      sum += (vPrev+vNext);
288
      cache.path_ratio[i] = sum;
289
      }
290

    
291
    float total = cache.path_ratio[NUM_RATIO-1];
292

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

    
295
    int writeIndex = 0;
296
    float prev=0.0f, next, ratio= 1.0f/NUM_RATIO;
297

    
298
    for(int readIndex=0; readIndex<NUM_RATIO; readIndex++)
299
      {
300
      next = cache.path_ratio[readIndex];
301

    
302
      while( prev<ratio && ratio<=next )
303
        {
304
        float a = (next-ratio)/(next-prev);
305
        mTmpRatio[writeIndex] = (readIndex+1-a)/NUM_RATIO;
306
        writeIndex++;
307
        ratio = (writeIndex+1.0f)/NUM_RATIO;
308
        }
309

    
310
      prev = next;
311
      }
312

    
313
    System.arraycopy(mTmpRatio, 0, cache.path_ratio, 0, NUM_RATIO);
314
    }
315

    
316
///////////////////////////////////////////////////////////////////////////////////////////////////
317

    
318
  protected float noise(float time,int vecNum)
319
    {
320
    float lower, upper, len;
321
    float d = time*(NUM_NOISE+1);
322
    int index = (int)d;
323
    if( index>=NUM_NOISE+1 ) index=NUM_NOISE;
324
    VectorNoise tmpN = vn.elementAt(vecNum);
325

    
326
    float t = d-index;
327
    t = t*t*(3-2*t);
328

    
329
    switch(index)
330
      {
331
      case 0        : for(int i=0;i<mDimension-1;i++) mFactor[i] = mNoise[i+1]*tmpN.n[i+1][0]*t;
332
                      return time + mNoise[0]*(d*tmpN.n[0][0]-time);
333
      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);
334
                      len = ((float)NUM_NOISE)/(NUM_NOISE+1);
335
                      lower = len + mNoise[0]*(tmpN.n[0][NUM_NOISE-1]-len);
336
                      return (1.0f-lower)*(d-NUM_NOISE) + lower;
337
      default       : float ya,yb;
338

    
339
                      for(int i=0;i<mDimension-1;i++)
340
                        {
341
                        yb = tmpN.n[i+1][index  ];
342
                        ya = tmpN.n[i+1][index-1];
343
                        mFactor[i] = mNoise[i+1]*((yb-ya)*t+ya);
344
                        }
345

    
346
                      len = ((float)index)/(NUM_NOISE+1);
347
                      lower = len + mNoise[0]*(tmpN.n[0][index-1]-len);
348
                      len = ((float)index+1)/(NUM_NOISE+1);
349
                      upper = len + mNoise[0]*(tmpN.n[0][index  ]-len);
350

    
351
                      return (upper-lower)*(d-index) + lower;
352
      }
353
    }
354

    
355
///////////////////////////////////////////////////////////////////////////////////////////////////
356
// debugging only
357

    
358
  private void printBase(String str)
359
    {
360
    String s;
361
    float t;
362

    
363
    for(int i=0; i<mDimension; i++)
364
      {
365
      s = "";
366

    
367
      for(int j=0; j<mDimension; j++)
368
        {
369
        t = ((int)(1000*baseV[i][j]))/(1000.0f);
370
        s+=(" "+t);
371
        }
372
      android.util.Log.e("dynamic", str+" base "+i+" : " + s);
373
      }
374
    }
375

    
376
///////////////////////////////////////////////////////////////////////////////////////////////////
377
// debugging only
378

    
379
  @SuppressWarnings("unused")
380
  private void checkBase()
381
    {
382
    float tmp, cosA;
383
    float[] len= new float[mDimension];
384
    boolean error=false;
385

    
386
    for(int i=0; i<mDimension; i++)
387
      {
388
      len[i] = 0.0f;
389

    
390
      for(int k=0; k<mDimension; k++)
391
        {
392
        len[i] += baseV[i][k]*baseV[i][k];
393
        }
394

    
395
      if( len[i] == 0.0f || len[0]/len[i] < 0.95f || len[0]/len[i]>1.05f )
396
        {
397
        android.util.Log.e("dynamic", "length of vector "+i+" : "+Math.sqrt(len[i]));
398
        error = true;
399
        }
400
      }
401

    
402
    for(int i=0; i<mDimension; i++)
403
      for(int j=i+1; j<mDimension; j++)
404
        {
405
        tmp = 0.0f;
406

    
407
        for(int k=0; k<mDimension; k++)
408
          {
409
          tmp += baseV[i][k]*baseV[j][k];
410
          }
411

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

    
414
        if( cosA > 0.05f || cosA < -0.05f )
415
          {
416
          android.util.Log.e("dynamic", "cos angle between vectors "+i+" and "+j+" : "+cosA);
417
          error = true;
418
          }
419
        }
420

    
421
    if( error ) printBase("");
422
    }
423

    
424
///////////////////////////////////////////////////////////////////////////////////////////////////
425

    
426
  int getNext(int curr, float time)
427
    {
428
    switch(mMode)
429
      {
430
      case MODE_LOOP: return curr==numPoints-1 ? 0:curr+1;
431
      case MODE_PATH: return time<0.5f ? (curr+1) : (curr==0 ? 1 : curr-1);
432
      case MODE_JUMP: return curr==numPoints-1 ? 1:curr+1;
433
      default       : return 0;
434
      }
435
    }
436

    
437
///////////////////////////////////////////////////////////////////////////////////////////////////
438

    
439
  private void checkAngle(int index)
440
    {
441
    float cosA = 0.0f;
442

    
443
    for(int k=0;k<mDimension; k++)
444
      cosA += baseV[index][k]*old[k];
445

    
446
    if( cosA<0.0f )
447
      {
448
      for(int j=0; j<mDimension; j++)
449
        baseV[index][j] = -baseV[index][j];
450
      }
451
    }
452

    
453
///////////////////////////////////////////////////////////////////////////////////////////////////
454
// helper function in case we are interpolating through exactly 2 points
455

    
456
  protected void computeOrthonormalBase2(Static curr, Static next)
457
    {
458
    switch(mDimension)
459
      {
460
      case 1: Static1D curr1 = (Static1D)curr;
461
              Static1D next1 = (Static1D)next;
462
              baseV[0][0] = (next1.x-curr1.x);
463
              break;
464
      case 2: Static2D curr2 = (Static2D)curr;
465
              Static2D next2 = (Static2D)next;
466
              baseV[0][0] = (next2.x-curr2.x);
467
              baseV[0][1] = (next2.y-curr2.y);
468
              break;
469
      case 3: Static3D curr3 = (Static3D)curr;
470
              Static3D next3 = (Static3D)next;
471
              baseV[0][0] = (next3.x-curr3.x);
472
              baseV[0][1] = (next3.y-curr3.y);
473
              baseV[0][2] = (next3.z-curr3.z);
474
              break;
475
      case 4: Static4D curr4 = (Static4D)curr;
476
              Static4D next4 = (Static4D)next;
477
              baseV[0][0] = (next4.x-curr4.x);
478
              baseV[0][1] = (next4.y-curr4.y);
479
              baseV[0][2] = (next4.z-curr4.z);
480
              baseV[0][3] = (next4.w-curr4.w);
481
              break;
482
      case 5: Static5D curr5 = (Static5D)curr;
483
              Static5D next5 = (Static5D)next;
484
              baseV[0][0] = (next5.x-curr5.x);
485
              baseV[0][1] = (next5.y-curr5.y);
486
              baseV[0][2] = (next5.z-curr5.z);
487
              baseV[0][3] = (next5.w-curr5.w);
488
              baseV[0][4] = (next5.v-curr5.v);
489
              break;
490
      default: throw new RuntimeException("Unsupported dimension");
491
      }
492

    
493
    if( baseV[0][0] == 0.0f )
494
      {
495
      baseV[1][0] = 1.0f;
496
      baseV[1][1] = 0.0f;
497
      }
498
    else
499
      {
500
      baseV[1][0] = 0.0f;
501
      baseV[1][1] = 1.0f;
502
      }
503

    
504
    for(int i=2; i<mDimension; i++)
505
      {
506
      baseV[1][i] = 0.0f;
507
      }
508

    
509
    computeOrthonormalBase();
510
    }
511

    
512
///////////////////////////////////////////////////////////////////////////////////////////////////
513
// helper function in case we are interpolating through more than 2 points
514

    
515
  protected void computeOrthonormalBaseMore(float time,VectorCache vc)
516
    {
517
    for(int i=0; i<mDimension; i++)
518
      {
519
      baseV[0][i] = (3*vc.a[i]*time+2*vc.b[i])*time+vc.c[i];   // first derivative, i.e. velocity vector
520
      old[i]      = baseV[1][i];
521
      baseV[1][i] =  6*vc.a[i]*time+2*vc.b[i];                 // second derivative,i.e. acceleration vector
522
      }
523

    
524
    computeOrthonormalBase();
525
    }
526

    
527
///////////////////////////////////////////////////////////////////////////////////////////////////
528
// When this function gets called, baseV[0] and baseV[1] should have been filled with two mDimension-al
529
// vectors. This function then fills the rest of the baseV array with a mDimension-al Orthonormal base.
530
// (mDimension-2 vectors, pairwise orthogonal to each other and to the original 2). The function always
531
// leaves base[0] alone but generally speaking must adjust base[1] to make it orthogonal to base[0]!
532
// The whole baseV is then used to compute Noise.
533
//
534
// When computing noise of a point travelling along a N-dimensional path, there are three cases:
535
// a) we may be interpolating through 1 point, i.e. standing in place - nothing to do in this case
536
// b) we may be interpolating through 2 points, i.e. travelling along a straight line between them -
537
//    then pass the velocity vector in baseV[0] and anything linearly independent in base[1].
538
//    The output will then be discontinuous in dimensions>2 (sad corollary from the Hairy Ball Theorem)
539
//    but we don't care - we are travelling along a straight line, so velocity (aka baseV[0]!) does
540
//    not change.
541
// c) we may be interpolating through more than 2 points. Then interpolation formulas ensure the path
542
//    will never be a straight line, even locally -> we can pass in baseV[0] and baseV[1] the velocity
543
//    and the acceleration (first and second derivatives of the path) which are then guaranteed to be
544
//    linearly independent. Then we can ensure this is continuous in dimensions <=4. This leaves
545
//    dimension 5 (ATM WAVE is 5-dimensional) discontinuous -> WAVE will suffer from chaotic noise.
546
//
547
// Bear in mind here the 'normal' in 'orthonormal' means 'length equal to the length of the original
548
// velocity vector' (rather than the standard 1)
549

    
550
  protected void computeOrthonormalBase()
551
    {
552
    int last_non_zero=-1;
553
    float tmp;
554

    
555
    for(int i=0; i<mDimension; i++)
556
      if( baseV[0][i] != 0.0f )
557
        last_non_zero=i;
558

    
559
    if( last_non_zero==-1 )                                               ///
560
      {                                                                   //  velocity is the 0 vector -> two
561
      for(int i=0; i<mDimension-1; i++)                                   //  consecutive points we are interpolating
562
        for(int j=0; j<mDimension; j++)                                   //  through are identical -> no noise,
563
          baseV[i+1][j]= 0.0f;                                            //  set the base to 0 vectors.
564
      }                                                                   ///
565
    else
566
      {
567
      for(int i=1; i<mDimension; i++)                                     /// One iteration computes baseV[i][*]
568
        {                                                                 //  (aka b[i]), the i-th orthonormal vector.
569
        buf[i-1]=0.0f;                                                    //
570
                                                                          //  We can use (modified!) Gram-Schmidt.
571
        for(int k=0; k<mDimension; k++)                                   //
572
          {                                                               //
573
          if( i>=2 )                                                      //  b[0] = b[0]
574
            {                                                             //  b[1] = b[1] - (<b[1],b[0]>/<b[0],b[0]>)*b[0]
575
            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]
576
            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]
577
            }                                                             //  (...)
578
                                                                          //  then b[i] = b[i] / |b[i]|  ( Here really b[i] = b[i] / (|b[0]|/|b[i]|)
579
          tmp = baseV[i-1][k];                                            //
580
          buf[i-1] += tmp*tmp;                                            //
581
          }                                                               //
582
                                                                          //
583
        for(int j=0; j<i; j++)                                            //
584
          {                                                               //
585
          tmp = 0.0f;                                                     //
586
          for(int k=0;k<mDimension; k++) tmp += baseV[i][k]*baseV[j][k];  //
587
          tmp /= buf[j];                                                  //
588
          for(int k=0;k<mDimension; k++) baseV[i][k] -= tmp*baseV[j][k];  //
589
          }                                                               //
590
                                                                          //
591
        checkAngle(i);                                                    //
592
        }                                                                 /// end compute baseV[i][*]
593

    
594
      buf[mDimension-1]=0.0f;                                             /// Normalize
595
      for(int k=0; k<mDimension; k++)                                     //
596
        {                                                                 //
597
        tmp = baseV[mDimension-1][k];                                     //
598
        buf[mDimension-1] += tmp*tmp;                                     //
599
        }                                                                 //
600
                                                                          //
601
      for(int i=1; i<mDimension; i++)                                     //
602
        {                                                                 //
603
        tmp = (float)Math.sqrt(buf[0]/buf[i]);                            //
604
        for(int k=0;k<mDimension; k++) baseV[i][k] *= tmp;                //
605
        }                                                                 /// End Normalize
606
      }
607
    }
608

    
609
///////////////////////////////////////////////////////////////////////////////////////////////////
610

    
611
  abstract void interpolate(float[] buffer, int offset, float time);
612

    
613
///////////////////////////////////////////////////////////////////////////////////////////////////
614
// PUBLIC API
615
///////////////////////////////////////////////////////////////////////////////////////////////////
616

    
617
/**
618
 * Sets the mode of the interpolation to Loop, Path or Jump.
619
 * <ul>
620
 * <li>Loop is when we go from the first point all the way to the last, and the back to the first through 
621
 * the shortest way.
622
 * <li>Path is when we come back from the last point back to the first the same way we got there.
623
 * <li>Jump is when we go from first to last and then jump straight back to the first.
624
 * </ul>
625
 * 
626
 * @param mode {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
627
 */
628
  public void setMode(int mode)
629
    {
630
    mMode = mode;  
631
    }
632

    
633
///////////////////////////////////////////////////////////////////////////////////////////////////
634
/**
635
 * Returns the number of Points this Dynamic has been fed with.
636
 *   
637
 * @return the number of Points we are currently interpolating through.
638
 */
639
  public synchronized int getNumPoints()
640
    {
641
    return numPoints;  
642
    }
643

    
644
///////////////////////////////////////////////////////////////////////////////////////////////////
645
/**
646
 * Sets how many revolutions we want to do.
647
 * <p>
648
 * Does not have to be an integer. What constitutes 'one revolution' depends on the MODE:
649
 * {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
650
 * Count<=0 means 'go on interpolating indefinitely'.
651
 * 
652
 * @param count the number of times we want to interpolate between our collection of Points.
653
 */
654
  public void setCount(float count)
655
    {
656
    mCount = count;  
657
    }
658

    
659
///////////////////////////////////////////////////////////////////////////////////////////////////
660
/**
661
 * Return the number of revolutions this Dynamic will make.
662
 * What constitutes 'one revolution' depends on the MODE:
663
 * {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
664
 *
665
 * @return the number revolutions this Dynamic will make.
666
 */
667
  public float getCount()
668
    {
669
    return mCount;
670
    }
671

    
672
///////////////////////////////////////////////////////////////////////////////////////////////////
673
/**
674
 * Start running from the beginning again.
675
 *
676
 * If a Dynamic has been used already, and we want to use it again and start interpolating from the
677
 * first Point, first we need to reset it using this method.
678
 */
679
  public void resetToBeginning()
680
    {
681
    mStartTime = -1;
682
    }
683

    
684
///////////////////////////////////////////////////////////////////////////////////////////////////
685
/**
686
 * @param duration Number of milliseconds one revolution will take.
687
 *                 What constitutes 'one revolution' depends on the MODE:
688
 *                 {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
689
 */
690
  public void setDuration(long duration)
691
    {
692
    mDuration = duration;
693
    }
694

    
695
///////////////////////////////////////////////////////////////////////////////////////////////////
696
/**
697
 * @return Number of milliseconds one revolution will take.
698
 */
699
  public long getDuration()
700
    {
701
    return mDuration;
702
    }
703

    
704
///////////////////////////////////////////////////////////////////////////////////////////////////
705
/**
706
 * @param convexity If set to the default (1.0f) then interpolation between 4 points
707
 *                  (1,0) (0,1) (-1,0) (0,-1) will be the natural circle centered at (0,0) with radius 1.
708
 *                  The less it is, the less convex the circle becomes, ultimately when convexity=0.0f
709
 *                  then the interpolation shape will be straight lines connecting the four points.
710
 *                  Further setting this to negative values will make the shape concave.
711
 *                  Valid values: all floats. (although probably only something around (0,2) actually
712
 *                  makes sense)
713
 */
714
  public void setConvexity(float convexity)
715
    {
716
    if( mConvexity!=convexity )
717
      {
718
      mConvexity = convexity;
719
      cacheDirty = true;
720
      }
721
    }
722

    
723
///////////////////////////////////////////////////////////////////////////////////////////////////
724
/**
725
 * @return See {@link Dynamic#setConvexity(float)}
726
 */
727
  public float getConvexity()
728
    {
729
    return mConvexity;
730
    }
731

    
732
///////////////////////////////////////////////////////////////////////////////////////////////////
733
/**
734
 * Sets the access type this Dynamic will be working in.
735
 *
736
 * @param type {@link Dynamic#ACCESS_TYPE_RANDOM} or {@link Dynamic#ACCESS_TYPE_SEQUENTIAL}.
737
 */
738
  public void setAccessType(int type)
739
    {
740
    mAccessType = type;
741
    mLastPos = -1;
742
    }
743

    
744
///////////////////////////////////////////////////////////////////////////////////////////////////
745
/**
746
 * @return See {@link Dynamic#setSpeedMode(int)}
747
 */
748
  public float getSpeedMode()
749
    {
750
    return mSpeedMode;
751
    }
752

    
753
///////////////////////////////////////////////////////////////////////////////////////////////////
754
/**
755
 * Sets the way we compute the interpolation speed.
756
 *
757
 * @param mode {@link Dynamic#SPEED_MODE_SMOOTH} or {@link Dynamic#SPEED_MODE_SEGMENT_CONSTANT} or
758
 *             {@link Dynamic#SPEED_MODE_GLOBALLY_CONSTANT}
759
 */
760
  public void setSpeedMode(int mode)
761
    {
762
    if( mSpeedMode!=mode )
763
      {
764
      if( mSpeedMode==SPEED_MODE_SMOOTH )
765
        {
766
        for(int i=0; i<numPoints; i++)
767
          {
768
          tmpCache1 = vc.elementAt(i);
769
          smoothOutSegment(tmpCache1);
770
          }
771
        }
772

    
773
      mSpeedMode = mode;
774
      }
775
    }
776

    
777
///////////////////////////////////////////////////////////////////////////////////////////////////
778
/**
779
 * Return the Dimension, ie number of floats in a single Point this Dynamic interpolates through.
780
 *
781
 * @return number of floats in a single Point (ie its dimension) contained in the Dynamic.
782
 */
783
  public int getDimension()
784
    {
785
    return mDimension;
786
    }
787

    
788
///////////////////////////////////////////////////////////////////////////////////////////////////
789
/**
790
 * Writes the results of interpolation between the Points at time 'time' to the passed float buffer.
791
 * <p>
792
 * This version differs from the previous in that it returns a boolean value which indicates whether
793
 * the interpolation is finished.
794
 *
795
 * @param buffer Float buffer we will write the results to.
796
 * @param offset Offset in the buffer where to write the result.
797
 * @param time   Time of interpolation. Time=0.0 is the beginning of the first revolution, time=1.0 - the end
798
 *               of the first revolution, time=2.5 - the middle of the third revolution.
799
 *               What constitutes 'one revolution' depends on the MODE:
800
 *               {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
801
 * @param step   Time difference between now and the last time we called this function. Needed to figure
802
 *               out if the previous time we were called the effect wasn't finished yet, but now it is.
803
 * @return true if the interpolation reached its end.
804
 */
805
  public boolean get(float[] buffer, int offset, long time, long step)
806
    {
807
    if( mDuration<=0.0f )
808
      {
809
      interpolate(buffer,offset,mCount-(int)mCount);
810
      return false;
811
      }
812

    
813
    if( mStartTime==-1 )
814
      {
815
      mStartTime = time;
816
      mLastPos   = -1;
817
      }
818

    
819
    long diff = time-mPausedTime;
820

    
821
    if( mStartTime<mPausedTime && mCorrectedTime<mPausedTime && diff>=0 && diff<=step )
822
      {
823
      mCorrectedTime = mPausedTime;
824
      mStartTime += diff;
825
      step -= diff;
826
      }
827

    
828
    time -= mStartTime;
829

    
830
    if( time+step > mDuration*mCount && mCount>0.0f )
831
      {
832
      interpolate(buffer,offset,mCount-(int)mCount);
833
      return true;
834
      }
835

    
836
    double pos;
837

    
838
    if( mAccessType ==ACCESS_TYPE_SEQUENTIAL )
839
      {
840
      pos = mLastPos<0 ? (double)time/mDuration : (double)step/mDuration + mLastPos;
841
      mLastPos = pos;
842
      }
843
    else
844
      {
845
      pos = (double)time/mDuration;
846
      }
847

    
848
    interpolate(buffer,offset, (float)(pos-(int)pos) );
849
    return false;
850
    }
851
  }
(6-6/18)