Project

General

Profile

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

library / src / main / java / org / distorted / library / type / Dynamic.java @ d403b466

1 e0a16874 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2016 Leszek Koltunski                                                               //
3
//                                                                                               //
4 46b572b5 Leszek Koltunski
// This file is part of Distorted.                                                               //
5 e0a16874 Leszek Koltunski
//                                                                                               //
6 46b572b5 Leszek Koltunski
// Distorted is free software: you can redistribute it and/or modify                             //
7 e0a16874 Leszek Koltunski
// 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 46b572b5 Leszek Koltunski
// Distorted is distributed in the hope that it will be useful,                                  //
12 e0a16874 Leszek Koltunski
// 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 46b572b5 Leszek Koltunski
// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
18 e0a16874 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
19
20 a4835695 Leszek Koltunski
package org.distorted.library.type;
21 6a06a912 Leszek Koltunski
22
import java.util.Random;
23 3002bef3 Leszek Koltunski
import java.util.Vector;
24 6a06a912 Leszek Koltunski
25
///////////////////////////////////////////////////////////////////////////////////////////////////
26 ea16dc89 Leszek Koltunski
/** A class to interpolate between a list of Statics.
27 6a06a912 Leszek Koltunski
* <p><ul>
28 c45c2ab1 Leszek Koltunski
* <li>if there is only one Point, just return it.
29 6a06a912 Leszek Koltunski
* <li>if there are two Points, linearly bounce between them
30 c45c2ab1 Leszek Koltunski
* <li>if there are more, interpolate a path between them. Exact way we interpolate depends on the MODE.
31 6a06a912 Leszek Koltunski
* </ul>
32
*/
33
34
// The way Interpolation between more than 2 Points is done:
35
// 
36 f871c455 Leszek Koltunski
// 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 6a06a912 Leszek Koltunski
//
39 f871c455 Leszek Koltunski
// 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 6a06a912 Leszek Koltunski
//
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 f871c455 Leszek Koltunski
// 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 6a06a912 Leszek Koltunski
//
48
// we have the solution:  X(t) = at^3 + bt^2 + ct + d where
49 f871c455 Leszek Koltunski
// 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 6a06a912 Leszek Koltunski
//
54
// and similarly Y(t) and Z(t).
55
56 24b1f190 Leszek Koltunski
public abstract class Dynamic
57 6a06a912 Leszek Koltunski
  {
58 9aabc9eb Leszek Koltunski
  /**
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 d403b466 Leszek Koltunski
  public static final int SPEED_MODE_GLOBALLY_CONSTANT = 2;  // TODO: not supported yet
73 9aabc9eb Leszek Koltunski
74 6a06a912 Leszek Koltunski
  /**
75 c45c2ab1 Leszek Koltunski
   * One revolution takes us from the first point to the last and back to first through the shortest path.
76 6a06a912 Leszek Koltunski
   */
77
  public static final int MODE_LOOP = 0; 
78
  /**
79 c45c2ab1 Leszek Koltunski
   * One revolution takes us from the first point to the last and back to first through the same path.
80 6a06a912 Leszek Koltunski
   */
81
  public static final int MODE_PATH = 1; 
82
  /**
83 c45c2ab1 Leszek Koltunski
   * One revolution takes us from the first point to the last and jumps straight back to the first point.
84 6a06a912 Leszek Koltunski
   */
85
  public static final int MODE_JUMP = 2; 
86 3002bef3 Leszek Koltunski
87 bdb341bc Leszek Koltunski
  /**
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 c45c2ab1 Leszek Koltunski
  public static final int ACCESS_TYPE_RANDOM     = 0;
94 bdb341bc Leszek Koltunski
  /**
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 24d22f93 Leszek Koltunski
   * Dynamic can only be used in one effect at a time.
99 bdb341bc Leszek Koltunski
   */
100 c45c2ab1 Leszek Koltunski
  public static final int ACCESS_TYPE_SEQUENTIAL = 1;
101 bdb341bc Leszek Koltunski
102 310e14fb leszek
  protected int mDimension;
103 6a06a912 Leszek Koltunski
  protected int numPoints;
104 291705f6 Leszek Koltunski
  protected int mSegment;       // between which pair of points are we currently? (in case of PATH this is a bit complicated!)
105 6a06a912 Leszek Koltunski
  protected boolean cacheDirty; // VectorCache not up to date
106
  protected int mMode;          // LOOP, PATH or JUMP
107 8c893ffc Leszek Koltunski
  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 6a06a912 Leszek Koltunski
  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 bdb341bc Leszek Koltunski
  protected double mLastPos;
110 c45c2ab1 Leszek Koltunski
  protected int mAccessType;
111 9aabc9eb Leszek Koltunski
  protected int mSpeedMode;
112 d403b466 Leszek Koltunski
  protected float mTmpTime;
113
  protected int mTmpVec, mTmpSeg;
114 3002bef3 Leszek Koltunski
115
  protected class VectorNoise
116
    {
117
    float[][] n;
118
119 291705f6 Leszek Koltunski
    VectorNoise()
120 3002bef3 Leszek Koltunski
      {
121 291705f6 Leszek Koltunski
      n = new float[mDimension][NUM_NOISE];
122
      }
123 3002bef3 Leszek Koltunski
124 291705f6 Leszek Koltunski
    void computeNoise()
125
      {
126 3002bef3 Leszek Koltunski
      n[0][0] = mRnd.nextFloat();
127
      for(int i=1; i<NUM_NOISE; i++) n[0][i] = n[0][i-1]+mRnd.nextFloat();
128 291705f6 Leszek Koltunski
129 3002bef3 Leszek Koltunski
      float sum = n[0][NUM_NOISE-1] + mRnd.nextFloat();
130
131 291705f6 Leszek Koltunski
      for(int i=0; i<NUM_NOISE; i++)
132 3002bef3 Leszek Koltunski
        {
133 291705f6 Leszek Koltunski
        n[0][i] /=sum;
134
        for(int j=1; j<mDimension; j++) n[j][i] = mRnd.nextFloat()-0.5f;
135 3002bef3 Leszek Koltunski
        }
136
      }
137
    }
138
139
  protected Vector<VectorNoise> vn;
140
  protected float[] mFactor;
141 1e22c248 Leszek Koltunski
  protected float[] mNoise;
142 649544b8 Leszek Koltunski
  protected float[][] baseV;
143
144
  ///////////////////////////////////////////////////////////////////////////////////////////////////
145 9aabc9eb Leszek Koltunski
  // 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.
146
  // (velocity) is the velocity vector.
147 649544b8 Leszek Koltunski
  // (cached) is the original vector from vv (copied here so when interpolating we can see if it is
148
  // still valid and if not - rebuild the Cache
149
150
  protected class VectorCache
151
    {
152
    float[] a;
153
    float[] b;
154
    float[] c;
155
    float[] d;
156 9aabc9eb Leszek Koltunski
    float[] velocity;
157 649544b8 Leszek Koltunski
    float[] cached;
158 9aabc9eb Leszek Koltunski
    float[] path_ratio;
159 649544b8 Leszek Koltunski
160 291705f6 Leszek Koltunski
    VectorCache()
161 649544b8 Leszek Koltunski
      {
162 291705f6 Leszek Koltunski
      a = new float[mDimension];
163
      b = new float[mDimension];
164
      c = new float[mDimension];
165
      d = new float[mDimension];
166 9aabc9eb Leszek Koltunski
167
      velocity   = new float[mDimension];
168
      cached     = new float[mDimension];
169
      path_ratio = new float[NUM_RATIO];
170 649544b8 Leszek Koltunski
      }
171
    }
172
173
  protected Vector<VectorCache> vc;
174 9aabc9eb Leszek Koltunski
  protected VectorCache tmpCache1, tmpCache2;
175 12ecac18 Leszek Koltunski
  protected float mConvexity;
176 3002bef3 Leszek Koltunski
177 9aabc9eb Leszek Koltunski
  private static final int NUM_RATIO = 10; // we attempt to 'smooth out' the speed in each segment -
178
                                           // remember this many 'points' inside the Cache for each segment.
179
180
  protected static final float[] mTmpRatio = new float[NUM_RATIO];
181
182 6a2ebb18 Leszek Koltunski
  private float[] buf;
183
  private float[] old;
184 4f9ec5d6 Leszek Koltunski
  private static final Random mRnd = new Random();
185 6a2ebb18 Leszek Koltunski
  private static final int NUM_NOISE = 5; // used iff mNoise>0.0. Number of intermediary points between each pair of adjacent vectors
186
                                          // where we randomize noise factors to make the way between the two vectors not so smooth.
187 0273ef2a Leszek Koltunski
  private long mStartTime;
188 246d021c Leszek Koltunski
  private long mCorrectedTime;
189 0273ef2a Leszek Koltunski
  private static long mPausedTime;
190 6a2ebb18 Leszek Koltunski
191 6a06a912 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
192
// hide this from Javadoc
193
  
194 649544b8 Leszek Koltunski
  protected Dynamic()
195 6a06a912 Leszek Koltunski
    {
196 310e14fb leszek
197 6a06a912 Leszek Koltunski
    }
198 8c893ffc Leszek Koltunski
199 649544b8 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
200
201
  protected Dynamic(int duration, float count, int dimension)
202
    {
203 291705f6 Leszek Koltunski
    vc         = new Vector<>();
204
    vn         = null;
205
    numPoints  = 0;
206 649544b8 Leszek Koltunski
    cacheDirty = false;
207 291705f6 Leszek Koltunski
    mMode      = MODE_LOOP;
208
    mDuration  = duration;
209
    mCount     = count;
210 649544b8 Leszek Koltunski
    mDimension = dimension;
211 291705f6 Leszek Koltunski
    mSegment   = -1;
212 bdb341bc Leszek Koltunski
    mLastPos   = -1;
213 12ecac18 Leszek Koltunski
    mAccessType= ACCESS_TYPE_RANDOM;
214 9aabc9eb Leszek Koltunski
    mSpeedMode = SPEED_MODE_SMOOTH;
215 12ecac18 Leszek Koltunski
    mConvexity = 1.0f;
216 78ff6ea9 Leszek Koltunski
    mStartTime = -1;
217 246d021c Leszek Koltunski
    mCorrectedTime = 0;
218 142c7236 Leszek Koltunski
219 291705f6 Leszek Koltunski
    baseV      = new float[mDimension][mDimension];
220
    buf        = new float[mDimension];
221
    old        = new float[mDimension];
222 649544b8 Leszek Koltunski
    }
223
224 3ac42a4c Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
225
226
  void initDynamic()
227
    {
228
    mStartTime = -1;
229
    mCorrectedTime = 0;
230
    }
231
232 0273ef2a Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
233
234
  public static void onPause()
235
    {
236
    mPausedTime = System.currentTimeMillis();
237
    }
238
239 d403b466 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
240
241
  protected void computeSegmentAndTime(float time)
242
    {
243
    switch(mMode)
244
      {
245
      case MODE_LOOP: mTmpTime= time*numPoints;
246
                      mTmpSeg = (int)mTmpTime;
247
                      mTmpVec = mTmpSeg;
248
                      break;
249
      case MODE_PATH: mTmpSeg = (int)(2*time*(numPoints-1));
250
251
                      if( time<=0.5f )  // this has to be <= (otherwise when effect ends at t=0.5, then time=1.0
252
                        {               // and end position is slightly not equal to the end point => might not get autodeleted!
253
                        mTmpTime = 2*time*(numPoints-1);
254
                        mTmpVec = mTmpSeg;
255
                        }
256
                      else
257
                        {
258
                        mTmpTime = 2*(1-time)*(numPoints-1);
259
                        mTmpVec  = 2*numPoints-3-mTmpSeg;
260
                        }
261
                      break;
262
      case MODE_JUMP: mTmpTime= time*(numPoints-1);
263
                      mTmpSeg = (int)mTmpTime;
264
                      mTmpVec = mTmpSeg;
265
                      break;
266
      default       : mTmpVec = 0;
267
                      mTmpSeg = 0;
268
      }
269
    }
270
271 9aabc9eb Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
272
273
  private float valueAtPoint(float t, VectorCache cache)
274
    {
275
    float tmp,sum = 0.0f;
276
277
    for(int d=0; d<mDimension; d++)
278
      {
279
      tmp = (3*cache.a[d]*t + 2*cache.b[d])*t + cache.c[d];
280
      sum += tmp*tmp;
281
      }
282
283
    return (float)Math.sqrt(sum);
284
    }
285
286
///////////////////////////////////////////////////////////////////////////////////////////////////
287
288
  protected float smoothSpeed(float time, VectorCache cache)
289
    {
290
    float fndex = time*NUM_RATIO;
291
    int index = (int)fndex;
292
    float prev = index==0 ? 0.0f : cache.path_ratio[index-1];
293
    float next = cache.path_ratio[index];
294
295
    return prev + (next-prev)*(fndex-index);
296
    }
297
298
///////////////////////////////////////////////////////////////////////////////////////////////////
299
// First, compute the approx length of the segment from time=0 to time=(i+1)/NUM_TIME and store this
300
// in cache.path_ratio[i]. Then the last path_ratio is the length from 0 to 1, i.e. the total length
301
// of the segment.
302
// We do this by computing the integral from 0 to 1 of sqrt( (dx/dt)^2 + (dy/dt)^2 ) (i.e. the length
303
// of the segment) using the approx 'trapezoids' integration method.
304
//
305
// Then, for every i, divide path_ratio[i] by the total length to get the percentage of total path
306
// length covered at time i. At this time, path_ratio[3] = 0.45 means 'at time 3/NUM_RATIO, we cover
307
// 0.45 = 45% of the total length of the segment.
308
//
309
// Finally, invert this function (for quicker lookups in smoothSpeed) so that after this step,
310
// path_ratio[3] = 0.45 means 'at 45% of the time, we cover 3/NUM_RATIO distance'.
311
312
  protected void smoothOutSegment(VectorCache cache)
313
    {
314
    float vPrev, sum = 0.0f;
315
    float vNext = valueAtPoint(0.0f,cache);
316
317
    for(int i=0; i<NUM_RATIO; i++)
318
      {
319
      vPrev = vNext;
320
      vNext = valueAtPoint( (float)(i+1)/NUM_RATIO,cache);
321
      sum += (vPrev+vNext);
322
      cache.path_ratio[i] = sum;
323
      }
324
325
    float total = cache.path_ratio[NUM_RATIO-1];
326
327
    for(int i=0; i<NUM_RATIO; i++) cache.path_ratio[i] /= total;
328
329
    int writeIndex = 0;
330
    float prev=0.0f, next, ratio= 1.0f/NUM_RATIO;
331
332
    for(int readIndex=0; readIndex<NUM_RATIO; readIndex++)
333
      {
334
      next = cache.path_ratio[readIndex];
335
336
      while( prev<ratio && ratio<=next )
337
        {
338
        float a = (next-ratio)/(next-prev);
339
        mTmpRatio[writeIndex] = (readIndex+1-a)/NUM_RATIO;
340
        writeIndex++;
341
        ratio = (writeIndex+1.0f)/NUM_RATIO;
342
        }
343
344
      prev = next;
345
      }
346
347
    System.arraycopy(mTmpRatio, 0, cache.path_ratio, 0, NUM_RATIO);
348
    }
349
350 3002bef3 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
351
352
  protected float noise(float time,int vecNum)
353
    {
354
    float lower, upper, len;
355
    float d = time*(NUM_NOISE+1);
356
    int index = (int)d;
357
    if( index>=NUM_NOISE+1 ) index=NUM_NOISE;
358
    VectorNoise tmpN = vn.elementAt(vecNum);
359
360
    float t = d-index;
361
    t = t*t*(3-2*t);
362
363
    switch(index)
364
      {
365 1e22c248 Leszek Koltunski
      case 0        : for(int i=0;i<mDimension-1;i++) mFactor[i] = mNoise[i+1]*tmpN.n[i+1][0]*t;
366
                      return time + mNoise[0]*(d*tmpN.n[0][0]-time);
367
      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);
368 3002bef3 Leszek Koltunski
                      len = ((float)NUM_NOISE)/(NUM_NOISE+1);
369 1e22c248 Leszek Koltunski
                      lower = len + mNoise[0]*(tmpN.n[0][NUM_NOISE-1]-len);
370 3002bef3 Leszek Koltunski
                      return (1.0f-lower)*(d-NUM_NOISE) + lower;
371
      default       : float ya,yb;
372
373
                      for(int i=0;i<mDimension-1;i++)
374
                        {
375
                        yb = tmpN.n[i+1][index  ];
376
                        ya = tmpN.n[i+1][index-1];
377 1e22c248 Leszek Koltunski
                        mFactor[i] = mNoise[i+1]*((yb-ya)*t+ya);
378 3002bef3 Leszek Koltunski
                        }
379
380
                      len = ((float)index)/(NUM_NOISE+1);
381 1e22c248 Leszek Koltunski
                      lower = len + mNoise[0]*(tmpN.n[0][index-1]-len);
382 3002bef3 Leszek Koltunski
                      len = ((float)index+1)/(NUM_NOISE+1);
383 1e22c248 Leszek Koltunski
                      upper = len + mNoise[0]*(tmpN.n[0][index  ]-len);
384 3002bef3 Leszek Koltunski
385
                      return (upper-lower)*(d-index) + lower;
386
      }
387
    }
388
389 649544b8 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
390
// debugging only
391
392
  private void printBase(String str)
393
    {
394
    String s;
395
    float t;
396
397
    for(int i=0; i<mDimension; i++)
398
      {
399
      s = "";
400
401
      for(int j=0; j<mDimension; j++)
402
        {
403
        t = ((int)(1000*baseV[i][j]))/(1000.0f);
404
        s+=(" "+t);
405
        }
406
      android.util.Log.e("dynamic", str+" base "+i+" : " + s);
407
      }
408
    }
409
410
///////////////////////////////////////////////////////////////////////////////////////////////////
411
// debugging only
412
413 24d22f93 Leszek Koltunski
  @SuppressWarnings("unused")
414 649544b8 Leszek Koltunski
  private void checkBase()
415
    {
416 6a2ebb18 Leszek Koltunski
    float tmp, cosA;
417
    float[] len= new float[mDimension];
418
    boolean error=false;
419
420
    for(int i=0; i<mDimension; i++)
421
      {
422
      len[i] = 0.0f;
423
424
      for(int k=0; k<mDimension; k++)
425
        {
426
        len[i] += baseV[i][k]*baseV[i][k];
427
        }
428
429
      if( len[i] == 0.0f || len[0]/len[i] < 0.95f || len[0]/len[i]>1.05f )
430
        {
431
        android.util.Log.e("dynamic", "length of vector "+i+" : "+Math.sqrt(len[i]));
432
        error = true;
433
        }
434
      }
435 649544b8 Leszek Koltunski
436
    for(int i=0; i<mDimension; i++)
437
      for(int j=i+1; j<mDimension; j++)
438
        {
439
        tmp = 0.0f;
440
441
        for(int k=0; k<mDimension; k++)
442
          {
443
          tmp += baseV[i][k]*baseV[j][k];
444
          }
445
446 6a2ebb18 Leszek Koltunski
        cosA = ( (len[i]==0.0f || len[j]==0.0f) ? 0.0f : tmp/(float)Math.sqrt(len[i]*len[j]));
447 649544b8 Leszek Koltunski
448 6a2ebb18 Leszek Koltunski
        if( cosA > 0.05f || cosA < -0.05f )
449
          {
450
          android.util.Log.e("dynamic", "cos angle between vectors "+i+" and "+j+" : "+cosA);
451
          error = true;
452
          }
453 649544b8 Leszek Koltunski
        }
454
455 6a2ebb18 Leszek Koltunski
    if( error ) printBase("");
456 649544b8 Leszek Koltunski
    }
457
458 9dacabea Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
459
460
  int getNext(int curr, float time)
461
    {
462
    switch(mMode)
463
      {
464
      case MODE_LOOP: return curr==numPoints-1 ? 0:curr+1;
465
      case MODE_PATH: return time<0.5f ? (curr+1) : (curr==0 ? 1 : curr-1);
466
      case MODE_JUMP: return curr==numPoints-1 ? 1:curr+1;
467
      default       : return 0;
468
      }
469
    }
470
471 c6dec65b Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
472
473
  private void checkAngle(int index)
474
    {
475
    float cosA = 0.0f;
476
477
    for(int k=0;k<mDimension; k++)
478
      cosA += baseV[index][k]*old[k];
479
480
    if( cosA<0.0f )
481
      {
482
      for(int j=0; j<mDimension; j++)
483
        baseV[index][j] = -baseV[index][j];
484
      }
485
    }
486
487 649544b8 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
488
// helper function in case we are interpolating through exactly 2 points
489
490 a20f274f Leszek Koltunski
  protected void computeOrthonormalBase2(Static curr, Static next)
491 649544b8 Leszek Koltunski
    {
492
    switch(mDimension)
493
      {
494 a20f274f Leszek Koltunski
      case 1: Static1D curr1 = (Static1D)curr;
495
              Static1D next1 = (Static1D)next;
496
              baseV[0][0] = (next1.x-curr1.x);
497 649544b8 Leszek Koltunski
              break;
498
      case 2: Static2D curr2 = (Static2D)curr;
499
              Static2D next2 = (Static2D)next;
500
              baseV[0][0] = (next2.x-curr2.x);
501
              baseV[0][1] = (next2.y-curr2.y);
502
              break;
503
      case 3: Static3D curr3 = (Static3D)curr;
504
              Static3D next3 = (Static3D)next;
505
              baseV[0][0] = (next3.x-curr3.x);
506
              baseV[0][1] = (next3.y-curr3.y);
507
              baseV[0][2] = (next3.z-curr3.z);
508
              break;
509
      case 4: Static4D curr4 = (Static4D)curr;
510
              Static4D next4 = (Static4D)next;
511
              baseV[0][0] = (next4.x-curr4.x);
512
              baseV[0][1] = (next4.y-curr4.y);
513
              baseV[0][2] = (next4.z-curr4.z);
514
              baseV[0][3] = (next4.w-curr4.w);
515
              break;
516
      case 5: Static5D curr5 = (Static5D)curr;
517
              Static5D next5 = (Static5D)next;
518
              baseV[0][0] = (next5.x-curr5.x);
519
              baseV[0][1] = (next5.y-curr5.y);
520
              baseV[0][2] = (next5.z-curr5.z);
521
              baseV[0][3] = (next5.w-curr5.w);
522
              baseV[0][4] = (next5.v-curr5.v);
523
              break;
524
      default: throw new RuntimeException("Unsupported dimension");
525
      }
526
527
    if( baseV[0][0] == 0.0f )
528
      {
529
      baseV[1][0] = 1.0f;
530
      baseV[1][1] = 0.0f;
531
      }
532
    else
533
      {
534
      baseV[1][0] = 0.0f;
535
      baseV[1][1] = 1.0f;
536
      }
537
538
    for(int i=2; i<mDimension; i++)
539
      {
540
      baseV[1][i] = 0.0f;
541
      }
542
543
    computeOrthonormalBase();
544
    }
545
546
///////////////////////////////////////////////////////////////////////////////////////////////////
547
// helper function in case we are interpolating through more than 2 points
548
549
  protected void computeOrthonormalBaseMore(float time,VectorCache vc)
550
    {
551
    for(int i=0; i<mDimension; i++)
552
      {
553 6a2ebb18 Leszek Koltunski
      baseV[0][i] = (3*vc.a[i]*time+2*vc.b[i])*time+vc.c[i];   // first derivative, i.e. velocity vector
554
      old[i]      = baseV[1][i];
555
      baseV[1][i] =  6*vc.a[i]*time+2*vc.b[i];                 // second derivative,i.e. acceleration vector
556 649544b8 Leszek Koltunski
      }
557
558
    computeOrthonormalBase();
559
    }
560
561
///////////////////////////////////////////////////////////////////////////////////////////////////
562
// When this function gets called, baseV[0] and baseV[1] should have been filled with two mDimension-al
563
// vectors. This function then fills the rest of the baseV array with a mDimension-al Orthonormal base.
564
// (mDimension-2 vectors, pairwise orthogonal to each other and to the original 2). The function always
565
// leaves base[0] alone but generally speaking must adjust base[1] to make it orthogonal to base[0]!
566
// The whole baseV is then used to compute Noise.
567
//
568
// When computing noise of a point travelling along a N-dimensional path, there are three cases:
569
// a) we may be interpolating through 1 point, i.e. standing in place - nothing to do in this case
570
// b) we may be interpolating through 2 points, i.e. travelling along a straight line between them -
571
//    then pass the velocity vector in baseV[0] and anything linearly independent in base[1].
572
//    The output will then be discontinuous in dimensions>2 (sad corollary from the Hairy Ball Theorem)
573
//    but we don't care - we are travelling along a straight line, so velocity (aka baseV[0]!) does
574
//    not change.
575
// c) we may be interpolating through more than 2 points. Then interpolation formulas ensure the path
576
//    will never be a straight line, even locally -> we can pass in baseV[0] and baseV[1] the velocity
577
//    and the acceleration (first and second derivatives of the path) which are then guaranteed to be
578
//    linearly independent. Then we can ensure this is continuous in dimensions <=4. This leaves
579
//    dimension 5 (ATM WAVE is 5-dimensional) discontinuous -> WAVE will suffer from chaotic noise.
580
//
581
// Bear in mind here the 'normal' in 'orthonormal' means 'length equal to the length of the original
582
// velocity vector' (rather than the standard 1)
583
584
  protected void computeOrthonormalBase()
585
    {
586
    int last_non_zero=-1;
587 6a2ebb18 Leszek Koltunski
    float tmp;
588 649544b8 Leszek Koltunski
589 6a2ebb18 Leszek Koltunski
    for(int i=0; i<mDimension; i++)
590
      if( baseV[0][i] != 0.0f )
591 649544b8 Leszek Koltunski
        last_non_zero=i;
592 6a2ebb18 Leszek Koltunski
593 a36b0cbb Leszek Koltunski
    if( last_non_zero==-1 )                                               ///
594 6a2ebb18 Leszek Koltunski
      {                                                                   //  velocity is the 0 vector -> two
595
      for(int i=0; i<mDimension-1; i++)                                   //  consecutive points we are interpolating
596
        for(int j=0; j<mDimension; j++)                                   //  through are identical -> no noise,
597
          baseV[i+1][j]= 0.0f;                                            //  set the base to 0 vectors.
598
      }                                                                   ///
599 649544b8 Leszek Koltunski
    else
600
      {
601 6a2ebb18 Leszek Koltunski
      for(int i=1; i<mDimension; i++)                                     /// One iteration computes baseV[i][*]
602
        {                                                                 //  (aka b[i]), the i-th orthonormal vector.
603
        buf[i-1]=0.0f;                                                    //
604
                                                                          //  We can use (modified!) Gram-Schmidt.
605
        for(int k=0; k<mDimension; k++)                                   //
606
          {                                                               //
607
          if( i>=2 )                                                      //  b[0] = b[0]
608
            {                                                             //  b[1] = b[1] - (<b[1],b[0]>/<b[0],b[0]>)*b[0]
609
            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]
610
            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]
611
            }                                                             //  (...)
612
                                                                          //  then b[i] = b[i] / |b[i]|  ( Here really b[i] = b[i] / (|b[0]|/|b[i]|)
613
          tmp = baseV[i-1][k];                                            //
614
          buf[i-1] += tmp*tmp;                                            //
615
          }                                                               //
616
                                                                          //
617
        for(int j=0; j<i; j++)                                            //
618
          {                                                               //
619
          tmp = 0.0f;                                                     //
620
          for(int k=0;k<mDimension; k++) tmp += baseV[i][k]*baseV[j][k];  //
621
          tmp /= buf[j];                                                  //
622
          for(int k=0;k<mDimension; k++) baseV[i][k] -= tmp*baseV[j][k];  //
623
          }                                                               //
624
                                                                          //
625
        checkAngle(i);                                                    //
626
        }                                                                 /// end compute baseV[i][*]
627
628
      buf[mDimension-1]=0.0f;                                             /// Normalize
629
      for(int k=0; k<mDimension; k++)                                     //
630
        {                                                                 //
631
        tmp = baseV[mDimension-1][k];                                     //
632
        buf[mDimension-1] += tmp*tmp;                                     //
633
        }                                                                 //
634
                                                                          //
635
      for(int i=1; i<mDimension; i++)                                     //
636
        {                                                                 //
637
        tmp = (float)Math.sqrt(buf[0]/buf[i]);                            //
638
        for(int k=0;k<mDimension; k++) baseV[i][k] *= tmp;                //
639
        }                                                                 /// End Normalize
640 649544b8 Leszek Koltunski
      }
641 6a06a912 Leszek Koltunski
    }
642 3002bef3 Leszek Koltunski
643 6a06a912 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
644 3002bef3 Leszek Koltunski
645 6a06a912 Leszek Koltunski
  abstract void interpolate(float[] buffer, int offset, float time);
646
647
///////////////////////////////////////////////////////////////////////////////////////////////////
648
// PUBLIC API
649
///////////////////////////////////////////////////////////////////////////////////////////////////
650 8c893ffc Leszek Koltunski
651 6a06a912 Leszek Koltunski
/**
652
 * Sets the mode of the interpolation to Loop, Path or Jump.
653
 * <ul>
654
 * <li>Loop is when we go from the first point all the way to the last, and the back to the first through 
655
 * the shortest way.
656
 * <li>Path is when we come back from the last point back to the first the same way we got there.
657 c45c2ab1 Leszek Koltunski
 * <li>Jump is when we go from first to last and then jump straight back to the first.
658 6a06a912 Leszek Koltunski
 * </ul>
659
 * 
660 568b29d8 Leszek Koltunski
 * @param mode {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
661 6a06a912 Leszek Koltunski
 */
662
  public void setMode(int mode)
663
    {
664
    mMode = mode;  
665
    }
666
667
///////////////////////////////////////////////////////////////////////////////////////////////////
668
/**
669 c45c2ab1 Leszek Koltunski
 * Returns the number of Points this Dynamic has been fed with.
670 6a06a912 Leszek Koltunski
 *   
671 c45c2ab1 Leszek Koltunski
 * @return the number of Points we are currently interpolating through.
672 6a06a912 Leszek Koltunski
 */
673
  public synchronized int getNumPoints()
674
    {
675
    return numPoints;  
676
    }
677
678
///////////////////////////////////////////////////////////////////////////////////////////////////
679
/**
680 c45c2ab1 Leszek Koltunski
 * Sets how many revolutions we want to do.
681 6a06a912 Leszek Koltunski
 * <p>
682 c45c2ab1 Leszek Koltunski
 * Does not have to be an integer. What constitutes 'one revolution' depends on the MODE:
683
 * {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
684 6a06a912 Leszek Koltunski
 * Count<=0 means 'go on interpolating indefinitely'.
685
 * 
686 c45c2ab1 Leszek Koltunski
 * @param count the number of times we want to interpolate between our collection of Points.
687 6a06a912 Leszek Koltunski
 */
688
  public void setCount(float count)
689
    {
690
    mCount = count;  
691
    }
692
693
///////////////////////////////////////////////////////////////////////////////////////////////////
694
/**
695 c45c2ab1 Leszek Koltunski
 * Return the number of revolutions this Dynamic will make.
696
 * What constitutes 'one revolution' depends on the MODE:
697
 * {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
698 b920c848 Leszek Koltunski
 *
699 c45c2ab1 Leszek Koltunski
 * @return the number revolutions this Dynamic will make.
700 b920c848 Leszek Koltunski
 */
701
  public float getCount()
702
    {
703
    return mCount;
704
    }
705
706
///////////////////////////////////////////////////////////////////////////////////////////////////
707
/**
708
 * Start running from the beginning again.
709 c45c2ab1 Leszek Koltunski
 *
710
 * If a Dynamic has been used already, and we want to use it again and start interpolating from the
711
 * first Point, first we need to reset it using this method.
712 6a06a912 Leszek Koltunski
 */
713 b920c848 Leszek Koltunski
  public void resetToBeginning()
714 6a06a912 Leszek Koltunski
    {
715 24b1f190 Leszek Koltunski
    mStartTime = -1;
716 b920c848 Leszek Koltunski
    }
717
718
///////////////////////////////////////////////////////////////////////////////////////////////////
719
/**
720 c45c2ab1 Leszek Koltunski
 * @param duration Number of milliseconds one revolution will take.
721
 *                 What constitutes 'one revolution' depends on the MODE:
722
 *                 {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
723 b920c848 Leszek Koltunski
 */
724
  public void setDuration(long duration)
725
    {
726
    mDuration = duration;
727
    }
728
729
///////////////////////////////////////////////////////////////////////////////////////////////////
730
/**
731 c45c2ab1 Leszek Koltunski
 * @return Number of milliseconds one revolution will take.
732 b920c848 Leszek Koltunski
 */
733
  public long getDuration()
734
    {
735
    return mDuration;
736 6a06a912 Leszek Koltunski
    }
737
738 12ecac18 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
739
/**
740
 * @param convexity If set to the default (1.0f) then interpolation between 4 points
741
 *                  (1,0) (0,1) (-1,0) (0,-1) will be the natural circle centered at (0,0) with radius 1.
742
 *                  The less it is, the less convex the circle becomes, ultimately when convexity=0.0f
743
 *                  then the interpolation shape will be straight lines connecting the four points.
744
 *                  Further setting this to negative values will make the shape concave.
745
 *                  Valid values: all floats. (although probably only something around (0,2) actually
746
 *                  makes sense)
747
 */
748
  public void setConvexity(float convexity)
749
    {
750
    if( mConvexity!=convexity )
751
      {
752
      mConvexity = convexity;
753
      cacheDirty = true;
754
      }
755
    }
756
757
///////////////////////////////////////////////////////////////////////////////////////////////////
758
/**
759
 * @return See {@link Dynamic#setConvexity(float)}
760
 */
761
  public float getConvexity()
762
    {
763
    return mConvexity;
764
    }
765
766 bdb341bc Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
767
/**
768 c45c2ab1 Leszek Koltunski
 * Sets the access type this Dynamic will be working in.
769 bdb341bc Leszek Koltunski
 *
770 c45c2ab1 Leszek Koltunski
 * @param type {@link Dynamic#ACCESS_TYPE_RANDOM} or {@link Dynamic#ACCESS_TYPE_SEQUENTIAL}.
771 bdb341bc Leszek Koltunski
 */
772 c45c2ab1 Leszek Koltunski
  public void setAccessType(int type)
773 bdb341bc Leszek Koltunski
    {
774 c45c2ab1 Leszek Koltunski
    mAccessType = type;
775 bdb341bc Leszek Koltunski
    mLastPos = -1;
776
    }
777
778 9aabc9eb Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
779
/**
780
 * @return See {@link Dynamic#setSpeedMode(int)}
781
 */
782
  public float getSpeedMode()
783
    {
784
    return mSpeedMode;
785
    }
786
787
///////////////////////////////////////////////////////////////////////////////////////////////////
788
/**
789
 * Sets the way we compute the interpolation speed.
790
 *
791
 * @param mode {@link Dynamic#SPEED_MODE_SMOOTH} or {@link Dynamic#SPEED_MODE_SEGMENT_CONSTANT} or
792
 *             {@link Dynamic#SPEED_MODE_GLOBALLY_CONSTANT}
793
 */
794
  public void setSpeedMode(int mode)
795
    {
796
    if( mSpeedMode!=mode )
797
      {
798
      if( mSpeedMode==SPEED_MODE_SMOOTH )
799
        {
800
        for(int i=0; i<numPoints; i++)
801
          {
802
          tmpCache1 = vc.elementAt(i);
803
          smoothOutSegment(tmpCache1);
804
          }
805
        }
806
807
      mSpeedMode = mode;
808
      }
809
    }
810
811 6d62a900 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
812
/**
813
 * Return the Dimension, ie number of floats in a single Point this Dynamic interpolates through.
814 c45c2ab1 Leszek Koltunski
 *
815
 * @return number of floats in a single Point (ie its dimension) contained in the Dynamic.
816 6d62a900 Leszek Koltunski
 */
817
  public int getDimension()
818
    {
819
    return mDimension;
820
    }
821
822 bdb341bc Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
823
/**
824
 * Writes the results of interpolation between the Points at time 'time' to the passed float buffer.
825
 * <p>
826
 * This version differs from the previous in that it returns a boolean value which indicates whether
827
 * the interpolation is finished.
828
 *
829 24d22f93 Leszek Koltunski
 * @param buffer Float buffer we will write the results to.
830 bdb341bc Leszek Koltunski
 * @param offset Offset in the buffer where to write the result.
831 c45c2ab1 Leszek Koltunski
 * @param time   Time of interpolation. Time=0.0 is the beginning of the first revolution, time=1.0 - the end
832
 *               of the first revolution, time=2.5 - the middle of the third revolution.
833
 *               What constitutes 'one revolution' depends on the MODE:
834
 *               {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
835 012901f5 Leszek Koltunski
 * @param step   Time difference between now and the last time we called this function. Needed to figure
836
 *               out if the previous time we were called the effect wasn't finished yet, but now it is.
837 bdb341bc Leszek Koltunski
 * @return true if the interpolation reached its end.
838
 */
839 a1d92a36 leszek
  public boolean get(float[] buffer, int offset, long time, long step)
840 bdb341bc Leszek Koltunski
    {
841
    if( mDuration<=0.0f )
842
      {
843
      interpolate(buffer,offset,mCount-(int)mCount);
844
      return false;
845
      }
846 b920c848 Leszek Koltunski
847 78ff6ea9 Leszek Koltunski
    if( mStartTime==-1 )
848 b920c848 Leszek Koltunski
      {
849 0273ef2a Leszek Koltunski
      mStartTime = time;
850 b920c848 Leszek Koltunski
      mLastPos   = -1;
851
      }
852
853 0273ef2a Leszek Koltunski
    long diff = time-mPausedTime;
854
855 246d021c Leszek Koltunski
    if( mStartTime<mPausedTime && mCorrectedTime<mPausedTime && diff>=0 && diff<=step )
856 0273ef2a Leszek Koltunski
      {
857 246d021c Leszek Koltunski
      mCorrectedTime = mPausedTime;
858 0273ef2a Leszek Koltunski
      mStartTime += diff;
859
      step -= diff;
860
      }
861
862
    time -= mStartTime;
863 b920c848 Leszek Koltunski
864 48d0867a leszek
    if( time+step > mDuration*mCount && mCount>0.0f )
865
      {
866
      interpolate(buffer,offset,mCount-(int)mCount);
867
      return true;
868
      }
869 bdb341bc Leszek Koltunski
870
    double pos;
871
872 c45c2ab1 Leszek Koltunski
    if( mAccessType ==ACCESS_TYPE_SEQUENTIAL )
873 bdb341bc Leszek Koltunski
      {
874
      pos = mLastPos<0 ? (double)time/mDuration : (double)step/mDuration + mLastPos;
875
      mLastPos = pos;
876
      }
877
    else
878
      {
879
      pos = (double)time/mDuration;
880
      }
881
882 48d0867a leszek
    interpolate(buffer,offset, (float)(pos-(int)pos) );
883 bdb341bc Leszek Koltunski
    return false;
884
    }
885 6a06a912 Leszek Koltunski
  }