Project

General

Profile

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

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

1 2c8310b1 Leszek Koltunski
////////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2016 Leszek Koltunski  leszek@koltunski.pl                                          //
3 e0a16874 Leszek Koltunski
//                                                                                               //
4 46b572b5 Leszek Koltunski
// This file is part of Distorted.                                                               //
5 e0a16874 Leszek Koltunski
//                                                                                               //
6 2c8310b1 Leszek Koltunski
// 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 e0a16874 Leszek Koltunski
//                                                                                               //
11 2c8310b1 Leszek Koltunski
// This library 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 2c8310b1 Leszek Koltunski
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU                             //
14
// Lesser General Public License for more details.                                               //
15 e0a16874 Leszek Koltunski
//                                                                                               //
16 2c8310b1 Leszek Koltunski
// 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 e0a16874 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
20
21 a4835695 Leszek Koltunski
package org.distorted.library.type;
22 6a06a912 Leszek Koltunski
23
import java.util.Random;
24 3002bef3 Leszek Koltunski
import java.util.Vector;
25 6a06a912 Leszek Koltunski
26
///////////////////////////////////////////////////////////////////////////////////////////////////
27 ea16dc89 Leszek Koltunski
/** A class to interpolate between a list of Statics.
28 6a06a912 Leszek Koltunski
* <p><ul>
29 c45c2ab1 Leszek Koltunski
* <li>if there is only one Point, just return it.
30 6a06a912 Leszek Koltunski
* <li>if there are two Points, linearly bounce between them
31 c45c2ab1 Leszek Koltunski
* <li>if there are more, interpolate a path between them. Exact way we interpolate depends on the MODE.
32 6a06a912 Leszek Koltunski
* </ul>
33
*/
34
35
// The way Interpolation between more than 2 Points is done:
36
// 
37 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
38
// be flying at Point P[i]
39 6a06a912 Leszek Koltunski
//
40 f871c455 Leszek Koltunski
// 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 6a06a912 Leszek Koltunski
//
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 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)
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 6a06a912 Leszek Koltunski
//
49
// we have the solution:  X(t) = at^3 + bt^2 + ct + d where
50 f871c455 Leszek Koltunski
// 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 6a06a912 Leszek Koltunski
//
55
// and similarly Y(t) and Z(t).
56
57 24b1f190 Leszek Koltunski
public abstract class Dynamic
58 6a06a912 Leszek Koltunski
  {
59 9aabc9eb Leszek Koltunski
  /**
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 d403b466 Leszek Koltunski
  public static final int SPEED_MODE_GLOBALLY_CONSTANT = 2;  // TODO: not supported yet
74 9aabc9eb Leszek Koltunski
75 6a06a912 Leszek Koltunski
  /**
76 c45c2ab1 Leszek Koltunski
   * One revolution takes us from the first point to the last and back to first through the shortest path.
77 6a06a912 Leszek Koltunski
   */
78
  public static final int MODE_LOOP = 0; 
79
  /**
80 c45c2ab1 Leszek Koltunski
   * One revolution takes us from the first point to the last and back to first through the same path.
81 6a06a912 Leszek Koltunski
   */
82
  public static final int MODE_PATH = 1; 
83
  /**
84 c45c2ab1 Leszek Koltunski
   * One revolution takes us from the first point to the last and jumps straight back to the first point.
85 6a06a912 Leszek Koltunski
   */
86
  public static final int MODE_JUMP = 2; 
87 3002bef3 Leszek Koltunski
88 bdb341bc Leszek Koltunski
  /**
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 c45c2ab1 Leszek Koltunski
  public static final int ACCESS_TYPE_RANDOM     = 0;
95 bdb341bc Leszek Koltunski
  /**
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 24d22f93 Leszek Koltunski
   * Dynamic can only be used in one effect at a time.
100 bdb341bc Leszek Koltunski
   */
101 c45c2ab1 Leszek Koltunski
  public static final int ACCESS_TYPE_SEQUENTIAL = 1;
102 bdb341bc Leszek Koltunski
103 310e14fb leszek
  protected int mDimension;
104 6a06a912 Leszek Koltunski
  protected int numPoints;
105 291705f6 Leszek Koltunski
  protected int mSegment;       // between which pair of points are we currently? (in case of PATH this is a bit complicated!)
106 6a06a912 Leszek Koltunski
  protected boolean cacheDirty; // VectorCache not up to date
107
  protected int mMode;          // LOOP, PATH or JUMP
108 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
109 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. 
110 bdb341bc Leszek Koltunski
  protected double mLastPos;
111 c45c2ab1 Leszek Koltunski
  protected int mAccessType;
112 9aabc9eb Leszek Koltunski
  protected int mSpeedMode;
113 d403b466 Leszek Koltunski
  protected float mTmpTime;
114
  protected int mTmpVec, mTmpSeg;
115 3002bef3 Leszek Koltunski
116
  protected class VectorNoise
117
    {
118
    float[][] n;
119
120 291705f6 Leszek Koltunski
    VectorNoise()
121 3002bef3 Leszek Koltunski
      {
122 291705f6 Leszek Koltunski
      n = new float[mDimension][NUM_NOISE];
123
      }
124 3002bef3 Leszek Koltunski
125 291705f6 Leszek Koltunski
    void computeNoise()
126
      {
127 3002bef3 Leszek Koltunski
      n[0][0] = mRnd.nextFloat();
128
      for(int i=1; i<NUM_NOISE; i++) n[0][i] = n[0][i-1]+mRnd.nextFloat();
129 291705f6 Leszek Koltunski
130 3002bef3 Leszek Koltunski
      float sum = n[0][NUM_NOISE-1] + mRnd.nextFloat();
131
132 291705f6 Leszek Koltunski
      for(int i=0; i<NUM_NOISE; i++)
133 3002bef3 Leszek Koltunski
        {
134 291705f6 Leszek Koltunski
        n[0][i] /=sum;
135
        for(int j=1; j<mDimension; j++) n[j][i] = mRnd.nextFloat()-0.5f;
136 3002bef3 Leszek Koltunski
        }
137
      }
138
    }
139
140
  protected Vector<VectorNoise> vn;
141
  protected float[] mFactor;
142 1e22c248 Leszek Koltunski
  protected float[] mNoise;
143 649544b8 Leszek Koltunski
  protected float[][] baseV;
144
145
  ///////////////////////////////////////////////////////////////////////////////////////////////////
146 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.
147
  // (velocity) is the velocity vector.
148 649544b8 Leszek Koltunski
  // (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 9aabc9eb Leszek Koltunski
    float[] velocity;
158 649544b8 Leszek Koltunski
    float[] cached;
159 9aabc9eb Leszek Koltunski
    float[] path_ratio;
160 649544b8 Leszek Koltunski
161 291705f6 Leszek Koltunski
    VectorCache()
162 649544b8 Leszek Koltunski
      {
163 291705f6 Leszek Koltunski
      a = new float[mDimension];
164
      b = new float[mDimension];
165
      c = new float[mDimension];
166
      d = new float[mDimension];
167 9aabc9eb Leszek Koltunski
168
      velocity   = new float[mDimension];
169
      cached     = new float[mDimension];
170
      path_ratio = new float[NUM_RATIO];
171 649544b8 Leszek Koltunski
      }
172
    }
173
174
  protected Vector<VectorCache> vc;
175 9aabc9eb Leszek Koltunski
  protected VectorCache tmpCache1, tmpCache2;
176 12ecac18 Leszek Koltunski
  protected float mConvexity;
177 3002bef3 Leszek Koltunski
178 9aabc9eb Leszek Koltunski
  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 6a2ebb18 Leszek Koltunski
  private float[] buf;
184
  private float[] old;
185 4f9ec5d6 Leszek Koltunski
  private static final Random mRnd = new Random();
186 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
187
                                          // where we randomize noise factors to make the way between the two vectors not so smooth.
188 0273ef2a Leszek Koltunski
  private long mStartTime;
189 246d021c Leszek Koltunski
  private long mCorrectedTime;
190 0273ef2a Leszek Koltunski
  private static long mPausedTime;
191 6a2ebb18 Leszek Koltunski
192 6a06a912 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
193
// hide this from Javadoc
194
  
195 649544b8 Leszek Koltunski
  protected Dynamic()
196 6a06a912 Leszek Koltunski
    {
197 310e14fb leszek
198 6a06a912 Leszek Koltunski
    }
199 8c893ffc Leszek Koltunski
200 649544b8 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
201
202
  protected Dynamic(int duration, float count, int dimension)
203
    {
204 291705f6 Leszek Koltunski
    vc         = new Vector<>();
205
    vn         = null;
206
    numPoints  = 0;
207 649544b8 Leszek Koltunski
    cacheDirty = false;
208 291705f6 Leszek Koltunski
    mMode      = MODE_LOOP;
209
    mDuration  = duration;
210
    mCount     = count;
211 649544b8 Leszek Koltunski
    mDimension = dimension;
212 291705f6 Leszek Koltunski
    mSegment   = -1;
213 bdb341bc Leszek Koltunski
    mLastPos   = -1;
214 12ecac18 Leszek Koltunski
    mAccessType= ACCESS_TYPE_RANDOM;
215 9aabc9eb Leszek Koltunski
    mSpeedMode = SPEED_MODE_SMOOTH;
216 12ecac18 Leszek Koltunski
    mConvexity = 1.0f;
217 78ff6ea9 Leszek Koltunski
    mStartTime = -1;
218 246d021c Leszek Koltunski
    mCorrectedTime = 0;
219 142c7236 Leszek Koltunski
220 291705f6 Leszek Koltunski
    baseV      = new float[mDimension][mDimension];
221
    buf        = new float[mDimension];
222
    old        = new float[mDimension];
223 649544b8 Leszek Koltunski
    }
224
225 3ac42a4c Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
226
227
  void initDynamic()
228
    {
229
    mStartTime = -1;
230
    mCorrectedTime = 0;
231
    }
232
233 0273ef2a Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
234
235
  public static void onPause()
236
    {
237
    mPausedTime = System.currentTimeMillis();
238
    }
239
240 d403b466 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 9aabc9eb Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 3002bef3 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 1e22c248 Leszek Koltunski
      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 3002bef3 Leszek Koltunski
                      len = ((float)NUM_NOISE)/(NUM_NOISE+1);
370 1e22c248 Leszek Koltunski
                      lower = len + mNoise[0]*(tmpN.n[0][NUM_NOISE-1]-len);
371 3002bef3 Leszek Koltunski
                      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 1e22c248 Leszek Koltunski
                        mFactor[i] = mNoise[i+1]*((yb-ya)*t+ya);
379 3002bef3 Leszek Koltunski
                        }
380
381
                      len = ((float)index)/(NUM_NOISE+1);
382 1e22c248 Leszek Koltunski
                      lower = len + mNoise[0]*(tmpN.n[0][index-1]-len);
383 3002bef3 Leszek Koltunski
                      len = ((float)index+1)/(NUM_NOISE+1);
384 1e22c248 Leszek Koltunski
                      upper = len + mNoise[0]*(tmpN.n[0][index  ]-len);
385 3002bef3 Leszek Koltunski
386
                      return (upper-lower)*(d-index) + lower;
387
      }
388
    }
389
390 649544b8 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 24d22f93 Leszek Koltunski
  @SuppressWarnings("unused")
415 649544b8 Leszek Koltunski
  private void checkBase()
416
    {
417 6a2ebb18 Leszek Koltunski
    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 649544b8 Leszek Koltunski
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 6a2ebb18 Leszek Koltunski
        cosA = ( (len[i]==0.0f || len[j]==0.0f) ? 0.0f : tmp/(float)Math.sqrt(len[i]*len[j]));
448 649544b8 Leszek Koltunski
449 6a2ebb18 Leszek Koltunski
        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 649544b8 Leszek Koltunski
        }
455
456 6a2ebb18 Leszek Koltunski
    if( error ) printBase("");
457 649544b8 Leszek Koltunski
    }
458
459 9dacabea Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 c6dec65b Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 649544b8 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
489
// helper function in case we are interpolating through exactly 2 points
490
491 a20f274f Leszek Koltunski
  protected void computeOrthonormalBase2(Static curr, Static next)
492 649544b8 Leszek Koltunski
    {
493
    switch(mDimension)
494
      {
495 a20f274f Leszek Koltunski
      case 1: Static1D curr1 = (Static1D)curr;
496
              Static1D next1 = (Static1D)next;
497
              baseV[0][0] = (next1.x-curr1.x);
498 649544b8 Leszek Koltunski
              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 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
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 649544b8 Leszek Koltunski
      }
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 6a2ebb18 Leszek Koltunski
    float tmp;
589 649544b8 Leszek Koltunski
590 6a2ebb18 Leszek Koltunski
    for(int i=0; i<mDimension; i++)
591
      if( baseV[0][i] != 0.0f )
592 649544b8 Leszek Koltunski
        last_non_zero=i;
593 6a2ebb18 Leszek Koltunski
594 a36b0cbb Leszek Koltunski
    if( last_non_zero==-1 )                                               ///
595 6a2ebb18 Leszek Koltunski
      {                                                                   //  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 649544b8 Leszek Koltunski
    else
601
      {
602 6a2ebb18 Leszek Koltunski
      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 649544b8 Leszek Koltunski
      }
642 6a06a912 Leszek Koltunski
    }
643 3002bef3 Leszek Koltunski
644 6a06a912 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
645 3002bef3 Leszek Koltunski
646 6a06a912 Leszek Koltunski
  abstract void interpolate(float[] buffer, int offset, float time);
647
648
///////////////////////////////////////////////////////////////////////////////////////////////////
649
// PUBLIC API
650
///////////////////////////////////////////////////////////////////////////////////////////////////
651 8c893ffc Leszek Koltunski
652 6a06a912 Leszek Koltunski
/**
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 c45c2ab1 Leszek Koltunski
 * <li>Jump is when we go from first to last and then jump straight back to the first.
659 6a06a912 Leszek Koltunski
 * </ul>
660
 * 
661 568b29d8 Leszek Koltunski
 * @param mode {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
662 6a06a912 Leszek Koltunski
 */
663
  public void setMode(int mode)
664
    {
665
    mMode = mode;  
666
    }
667
668
///////////////////////////////////////////////////////////////////////////////////////////////////
669
/**
670 c45c2ab1 Leszek Koltunski
 * Returns the number of Points this Dynamic has been fed with.
671 6a06a912 Leszek Koltunski
 *   
672 c45c2ab1 Leszek Koltunski
 * @return the number of Points we are currently interpolating through.
673 6a06a912 Leszek Koltunski
 */
674
  public synchronized int getNumPoints()
675
    {
676
    return numPoints;  
677
    }
678
679
///////////////////////////////////////////////////////////////////////////////////////////////////
680
/**
681 c45c2ab1 Leszek Koltunski
 * Sets how many revolutions we want to do.
682 6a06a912 Leszek Koltunski
 * <p>
683 c45c2ab1 Leszek Koltunski
 * 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 6a06a912 Leszek Koltunski
 * Count<=0 means 'go on interpolating indefinitely'.
686
 * 
687 c45c2ab1 Leszek Koltunski
 * @param count the number of times we want to interpolate between our collection of Points.
688 6a06a912 Leszek Koltunski
 */
689
  public void setCount(float count)
690
    {
691
    mCount = count;  
692
    }
693
694
///////////////////////////////////////////////////////////////////////////////////////////////////
695
/**
696 c45c2ab1 Leszek Koltunski
 * 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 b920c848 Leszek Koltunski
 *
700 c45c2ab1 Leszek Koltunski
 * @return the number revolutions this Dynamic will make.
701 b920c848 Leszek Koltunski
 */
702
  public float getCount()
703
    {
704
    return mCount;
705
    }
706
707
///////////////////////////////////////////////////////////////////////////////////////////////////
708
/**
709
 * Start running from the beginning again.
710 c45c2ab1 Leszek Koltunski
 *
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 6a06a912 Leszek Koltunski
 */
714 b920c848 Leszek Koltunski
  public void resetToBeginning()
715 6a06a912 Leszek Koltunski
    {
716 24b1f190 Leszek Koltunski
    mStartTime = -1;
717 b920c848 Leszek Koltunski
    }
718
719
///////////////////////////////////////////////////////////////////////////////////////////////////
720
/**
721 c45c2ab1 Leszek Koltunski
 * @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 b920c848 Leszek Koltunski
 */
725
  public void setDuration(long duration)
726
    {
727
    mDuration = duration;
728
    }
729
730
///////////////////////////////////////////////////////////////////////////////////////////////////
731
/**
732 c45c2ab1 Leszek Koltunski
 * @return Number of milliseconds one revolution will take.
733 b920c848 Leszek Koltunski
 */
734
  public long getDuration()
735
    {
736
    return mDuration;
737 6a06a912 Leszek Koltunski
    }
738
739 12ecac18 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 bdb341bc Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
768
/**
769 c45c2ab1 Leszek Koltunski
 * Sets the access type this Dynamic will be working in.
770 bdb341bc Leszek Koltunski
 *
771 c45c2ab1 Leszek Koltunski
 * @param type {@link Dynamic#ACCESS_TYPE_RANDOM} or {@link Dynamic#ACCESS_TYPE_SEQUENTIAL}.
772 bdb341bc Leszek Koltunski
 */
773 c45c2ab1 Leszek Koltunski
  public void setAccessType(int type)
774 bdb341bc Leszek Koltunski
    {
775 c45c2ab1 Leszek Koltunski
    mAccessType = type;
776 bdb341bc Leszek Koltunski
    mLastPos = -1;
777
    }
778
779 9aabc9eb Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 6d62a900 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
813
/**
814
 * Return the Dimension, ie number of floats in a single Point this Dynamic interpolates through.
815 c45c2ab1 Leszek Koltunski
 *
816
 * @return number of floats in a single Point (ie its dimension) contained in the Dynamic.
817 6d62a900 Leszek Koltunski
 */
818
  public int getDimension()
819
    {
820
    return mDimension;
821
    }
822
823 bdb341bc Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
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 24d22f93 Leszek Koltunski
 * @param buffer Float buffer we will write the results to.
831 bdb341bc Leszek Koltunski
 * @param offset Offset in the buffer where to write the result.
832 c45c2ab1 Leszek Koltunski
 * @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 012901f5 Leszek Koltunski
 * @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 bdb341bc Leszek Koltunski
 * @return true if the interpolation reached its end.
839
 */
840 a1d92a36 leszek
  public boolean get(float[] buffer, int offset, long time, long step)
841 bdb341bc Leszek Koltunski
    {
842
    if( mDuration<=0.0f )
843
      {
844
      interpolate(buffer,offset,mCount-(int)mCount);
845
      return false;
846
      }
847 b920c848 Leszek Koltunski
848 78ff6ea9 Leszek Koltunski
    if( mStartTime==-1 )
849 b920c848 Leszek Koltunski
      {
850 0273ef2a Leszek Koltunski
      mStartTime = time;
851 b920c848 Leszek Koltunski
      mLastPos   = -1;
852
      }
853
854 0273ef2a Leszek Koltunski
    long diff = time-mPausedTime;
855
856 246d021c Leszek Koltunski
    if( mStartTime<mPausedTime && mCorrectedTime<mPausedTime && diff>=0 && diff<=step )
857 0273ef2a Leszek Koltunski
      {
858 246d021c Leszek Koltunski
      mCorrectedTime = mPausedTime;
859 0273ef2a Leszek Koltunski
      mStartTime += diff;
860
      step -= diff;
861
      }
862
863
    time -= mStartTime;
864 b920c848 Leszek Koltunski
865 48d0867a leszek
    if( time+step > mDuration*mCount && mCount>0.0f )
866
      {
867
      interpolate(buffer,offset,mCount-(int)mCount);
868
      return true;
869
      }
870 bdb341bc Leszek Koltunski
871
    double pos;
872
873 c45c2ab1 Leszek Koltunski
    if( mAccessType ==ACCESS_TYPE_SEQUENTIAL )
874 bdb341bc Leszek Koltunski
      {
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 48d0867a leszek
    interpolate(buffer,offset, (float)(pos-(int)pos) );
884 bdb341bc Leszek Koltunski
    return false;
885
    }
886 6a06a912 Leszek Koltunski
  }