Project

General

Profile

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

library / src / main / java / org / distorted / library / Interpolator2D.java @ d333eb6b

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;
21

    
22
import java.util.Vector;
23

    
24
///////////////////////////////////////////////////////////////////////////////////////////////////
25
/** 
26
* A 2-dimensional implementation of the Interpolator class to interpolate between a list 
27
* of Float2Ds.
28
*/
29

    
30
public class Interpolator2D extends Interpolator 
31
  {
32

    
33
///////////////////////////////////////////////////////////////////////////////////////////////////
34
// the coefficients of the X(t), Y(t) polynomials: X(t) = ax*T^3 + bx*T^2 + cx*t + dx  etc.
35
// (x,y) is the vector tangent to the path.
36
// (vx,vy) is the original vector from vv (copied here so when interpolating we can see if it is 
37
// still valid and if not - rebuild the Cache
38
  
39
  private class VectorCache
40
    {
41
    float ax, bx, cx, dx;
42
    float ay, by, cy, dy;
43
   
44
    float x,y;
45
    float vx,vy;
46
    }
47
  
48
  private class VectorNoise
49
    {    
50
    float[] nx;
51
    float[] ny;
52
   
53
    public VectorNoise()
54
      {
55
      nx = new float[NUM_NOISE]; 
56
      nx[0] = mRnd.nextFloat();
57
      for(int i=1; i<NUM_NOISE; i++) nx[i] = nx[i-1]+mRnd.nextFloat();
58
      float sum = nx[NUM_NOISE-1] + mRnd.nextFloat();
59
      for(int i=0; i<NUM_NOISE; i++) nx[i] /=sum;
60
     
61
      ny = new float[NUM_NOISE];
62
      for(int i=0; i<NUM_NOISE; i++) ny[i] = mRnd.nextFloat()-0.5f;
63
      }
64
    }
65
    
66
  private Vector<VectorCache> vc;
67
  private VectorCache tmp1, tmp2;
68
   
69
  private Vector<Float2D> vv;
70
  private Float2D prev, curr, next;
71
 
72
  private Vector<VectorNoise> vn;
73
  private VectorNoise tmpN;
74
  
75
  private float mFactor;
76
 
77
///////////////////////////////////////////////////////////////////////////////////////////////////
78

    
79
  synchronized void createNoise()
80
    {
81
    if( vn==null )
82
      {
83
      vn = new Vector<VectorNoise>();
84
      for(int i=0; i<numPoints; i++) vn.add(new VectorNoise());
85
      }
86
    }
87
 
88
///////////////////////////////////////////////////////////////////////////////////////////////////
89
// no array bounds checking!
90
  
91
  private void vec(int c)
92
    {
93
    int p = c>0 ? c-1: numPoints-1;
94
    int n = c<numPoints-1 ? c+1: 0;
95
    
96
    prev = vv.elementAt(p);
97
    curr = vv.elementAt(c);
98
    next = vv.elementAt(n);
99

    
100
    tmp1 = vc.elementAt(c);
101
    
102
    float px = curr.x - prev.x;
103
    float py = curr.y - prev.y;
104
    float nx = next.x - curr.x;
105
    float ny = next.y - curr.y;
106
     
107
    float d = nx*nx+ny*ny;
108
    
109
    if( d>0 )
110
      {
111
      float q = (float)Math.sqrt((px*px+py*py)/d);
112
      
113
      if( q>1 )
114
        {
115
        tmp1.x = nx+px/q;
116
        tmp1.y = ny+py/q;
117
        }
118
      else
119
        {
120
        tmp1.x = px+nx*q;
121
        tmp1.y = py+ny*q;
122
        }
123
      }
124
    else
125
      {
126
      tmp1.x = 0.0f;
127
      tmp1.y = 0.0f;
128
      }
129
    }
130
   
131
///////////////////////////////////////////////////////////////////////////////////////////////////
132
  
133
  private void recomputeCache()
134
    {  
135
    if( numPoints==1 )
136
      {
137
      tmp1= vc.elementAt(0);
138
      curr= vv.elementAt(0);
139
              
140
      tmp1.ax = tmp1.ay = 0.0f;
141
      tmp1.bx = tmp1.by = 0.0f;
142
      tmp1.cx = curr.x;
143
      tmp1.cy = curr.y;
144
      tmp1.dx = tmp1.dy = 0.0f;
145
      }
146
    else if( numPoints==2 )
147
      {
148
      tmp1= vc.elementAt(0);
149
      tmp2= vc.elementAt(1);
150
      curr= vv.elementAt(0);
151
      next= vv.elementAt(1);
152
          
153
      tmp1.ax = tmp1.ay = 0.0f;
154
      tmp1.bx = tmp1.by = 0.0f;
155
      tmp1.cx = next.x - curr.x;
156
      tmp1.cy = next.y - curr.y;
157
      tmp1.dx = curr.x;
158
      tmp1.dy = curr.y;
159
      
160
      tmp2.ax = tmp2.ay = 0.0f;
161
      tmp2.bx = tmp2.by = 0.0f;
162
      tmp2.cx = curr.x - next.x;
163
      tmp2.cy = curr.y - next.y;
164
      tmp2.dx = next.x;
165
      tmp2.dy = next.y;
166
      }
167
    else
168
      {
169
      int i, n;  
170
         
171
      for(i=0; i<numPoints; i++) vec(i);
172
   
173
      for(i=0; i<numPoints; i++)
174
        {
175
        n = i<numPoints-1 ? i+1:0;  
176
      
177
        tmp1= vc.elementAt(i);
178
        tmp2= vc.elementAt(n);
179
        curr= vv.elementAt(i);
180
        next= vv.elementAt(n);
181
      
182
        tmp1.vx = curr.x;
183
        tmp1.vy = curr.y;
184
        
185
        tmp1.ax =  2*curr.x +   tmp1.x - 2*next.x + tmp2.x;
186
        tmp1.bx = -3*curr.x - 2*tmp1.x + 3*next.x - tmp2.x;
187
        tmp1.cx = tmp1.x;
188
        tmp1.dx = curr.x;
189
      
190
        tmp1.ay =  2*curr.y +   tmp1.y - 2*next.y + tmp2.y;
191
        tmp1.by = -3*curr.y - 2*tmp1.y + 3*next.y - tmp2.y;
192
        tmp1.cy = tmp1.y;
193
        tmp1.dy = curr.y;
194
        }
195
      }
196
    
197
    cacheDirty = false;
198
    }
199
 
200
///////////////////////////////////////////////////////////////////////////////////////////////////
201

    
202
  private float noise(float time,int vecNum)
203
    {
204
    float lower, upper, len;  
205
    float d = time*(NUM_NOISE+1);
206
    int index = (int)d;
207
    if( index>=NUM_NOISE+1 ) index=NUM_NOISE;
208
    tmpN = vn.elementAt(vecNum);
209
   
210
    float x = d-index;
211
    x = x*x*(3-2*x);
212
   
213
    switch(index)
214
      {
215
      case 0        : mFactor = mNoise*tmpN.ny[0]*x;  
216
                      return time + mNoise*(d*tmpN.nx[0]-time);                
217
      case NUM_NOISE: mFactor= mNoise*tmpN.ny[NUM_NOISE-1]*(1-x);
218
                      len = ((float)NUM_NOISE)/(NUM_NOISE+1);
219
                      lower = len + mNoise*(tmpN.nx[NUM_NOISE-1]-len);  
220
                      return (1.0f-lower)*(d-NUM_NOISE) + lower;
221
      default       : float yb = tmpN.ny[index  ];
222
                      float ya = tmpN.ny[index-1];
223
                      mFactor  = mNoise*((yb-ya)*x+ya);
224
   
225
                      len = ((float)index)/(NUM_NOISE+1);
226
                      lower = len + mNoise*(tmpN.nx[index-1]-len);   
227
                      len = ((float)index+1)/(NUM_NOISE+1); 
228
                      upper = len + mNoise*(tmpN.nx[index  ]-len);
229
            
230
                      return (upper-lower)*(d-index) + lower; 
231
      }
232
    }
233
  
234
///////////////////////////////////////////////////////////////////////////////////////////////////
235
// PUBLIC API 
236
///////////////////////////////////////////////////////////////////////////////////////////////////
237
/**
238
 * Default constructor.
239
 */
240
  public Interpolator2D()
241
    {
242
    vv = new Vector<Float2D>();
243
    vc = new Vector<VectorCache>();
244
    vn = null;
245
    numPoints = 0;
246
    cacheDirty = false;
247
    mMode = MODE_LOOP;
248
    mDuration = 0;
249
    mCount = 0.5f;
250
    mNoise = 0.0f;
251
    }
252
  
253
///////////////////////////////////////////////////////////////////////////////////////////////////
254
/**
255
 * Returns the location'th Float2D. 
256
 *   
257
 * @param location the index of the Point we are interested in.
258
 * @return The Float2D, if 0<=location&lt;getNumPoints(), or null otherwise. 
259
 */  
260
  public synchronized Float2D getPoint(int location)
261
    {
262
    return (location>=0 && location<numPoints) ? vv.elementAt(location) : null;  
263
    }
264
  
265
///////////////////////////////////////////////////////////////////////////////////////////////////
266
/**
267
 * Resets the location'th Point.
268
 * 
269
 * @param location the index of the Point we are setting.
270
 * @param x New value of its first float.
271
 */
272
  public synchronized void setPoint(int location, float x, float y)
273
    {
274
    if( location>=0 && location<numPoints )
275
      {
276
      curr = vv.elementAt(location);
277
   
278
      if( curr!=null )
279
        {
280
        curr.set(x,y);
281
        cacheDirty=true;
282
        }
283
      }
284
    }
285
    
286
///////////////////////////////////////////////////////////////////////////////////////////////////
287
/**
288
 * Adds a new Float2D to the end of our list of Points to interpolate through.
289
 * <p>   
290
 * Only a reference to the Point gets added to the List; this means that one can add a Point 
291
 * here, and later on {@link Float2D#set(float,float)} it to some new value and the change 
292
 * will be seamlessly reflected in the interpolated path.  
293
 * <p>
294
 * A Point can be added multiple times.
295
 *   
296
 * @param v The Point to add.
297
 */  
298
  public synchronized void add(Float2D v)
299
    {
300
    if( v!=null )
301
      {
302
      vv.add(v);
303
     
304
      if( vn!=null ) vn.add(new VectorNoise());
305
       
306
      switch(numPoints)
307
        {
308
        case 0:
309
        case 1: break;
310
        case 2: vc.add(new VectorCache());
311
                vc.add(new VectorCache());
312
                vc.add(new VectorCache());
313
                break;
314
        default:vc.add(new VectorCache());
315
        }
316
     
317
      numPoints++;
318
      cacheDirty = true;
319
      }
320
    }
321

    
322
///////////////////////////////////////////////////////////////////////////////////////////////////
323
/**
324
 * Adds a new Float2D to the location'th place in our List of Points to interpolate through.  
325
 *   
326
 * @param location Index in our List to add the new Point at.
327
 * @param v The Point to add.
328
 */  
329
  public synchronized void add(int location, Float2D v)
330
    {
331
    if( v!=null )
332
      {
333
      vv.add(location, v);
334
      
335
      if( vn!=null ) vn.add(new VectorNoise());
336
      
337
      switch(numPoints)
338
        {
339
        case 0:
340
        case 1: break;
341
        case 2: vc.add(new VectorCache());
342
                vc.add(new VectorCache());
343
                vc.add(new VectorCache());
344
                break;
345
        default:vc.add(location,new VectorCache());
346
        }
347
      
348
      numPoints++;
349
      cacheDirty = true;
350
      }
351
    }
352
  
353
///////////////////////////////////////////////////////////////////////////////////////////////////
354
/**
355
 * Removes all occurrences of Point v from the List of Points to interpolate through.  
356
 * 
357
 * @param v The Point to remove.
358
 * @return <code>true</code> if we have removed at least one Point.
359
 */
360
  public synchronized boolean remove(Float2D v)
361
    {
362
    int n = vv.indexOf(v);
363
    boolean found = false;
364
   
365
    while( n>=0 ) 
366
      {
367
      vv.remove(n);
368
     
369
      if( vn!=null ) vn.remove(0);
370
     
371
      switch(numPoints)
372
        {
373
        case 0:
374
        case 1: 
375
        case 2: break;
376
        case 3: vc.removeAllElements();
377
                break;
378
        default:vc.remove(n);
379
        }
380
     
381
      numPoints--;
382
      found = true;
383
      n = vv.indexOf(v);
384
      }
385
   
386
    if( found ) 
387
      {
388
      cacheDirty=true;
389
      }
390
   
391
    return found;
392
    }
393

    
394
///////////////////////////////////////////////////////////////////////////////////////////////////
395
/**
396
 * Removes a location'th Point from the List of Points we interpolate through.
397
 * 
398
 * @param location index of the Point we want to remove. 
399
 * @return <code>true</code> if location is valid, i.e. if 0<=location&lt;getNumPoints().
400
 */
401
  public synchronized boolean remove(int location)
402
    {
403
    if( location>=0 && location<numPoints ) 
404
      {
405
      vv.removeElementAt(location);
406
      
407
      if( vn!=null ) vn.remove(0);
408
      
409
      switch(numPoints)
410
        {
411
        case 0:
412
        case 1: 
413
        case 2: break;
414
        case 3: vc.removeAllElements();
415
                break;
416
        default:vc.removeElementAt(location);
417
        }
418

    
419
      numPoints--;
420
      cacheDirty = true; 
421
      return true;
422
      }
423

    
424
   return false;
425
   }
426
  
427
///////////////////////////////////////////////////////////////////////////////////////////////////
428
/**
429
 * Removes all Points.
430
 */
431
  public synchronized void removeAll()
432
    {
433
    numPoints = 0;
434
    vv.removeAllElements();
435
    vc.removeAllElements();
436
    cacheDirty = false;
437
   
438
    if( vn!=null ) vn.removeAllElements();
439
    }
440

    
441
///////////////////////////////////////////////////////////////////////////////////////////////////
442
/**
443
 * Writes the results of interpolation between the Points at time 'time' to the passed float buffer.
444
 * <p>
445
 * Since this is a 2-dimensional Interpolator, the resulting interpolated Float2D gets written
446
 * to two locations in the buffer: buffer[offset] and buffer[offset+1]. 
447
 * 
448
 * @param buffer Float buffer we will write the resulting Float2D to.
449
 * @param offset Offset in the buffer where to write the result.
450
 * @param time Time of interpolation. Time=0.0 would return the first Point, Time=0.5 - the last,
451
 *             time=1.0 - the first again, and time 0.1 would be 1/5 of the way between the first and the last Points.
452
 */  
453
  public synchronized void interpolate(float[] buffer, int offset, float time)
454
    {
455
    switch(numPoints)
456
      {
457
      case 0: buffer[offset  ] = 0.0f;
458
              buffer[offset+1] = 0.0f;
459
              break;
460
      case 1: curr = vv.elementAt(0);
461
              buffer[offset  ] = curr.x;
462
              buffer[offset+1] = curr.y;
463
              break;
464
      case 2: curr = vv.elementAt(0);
465
              next = vv.elementAt(1);
466
               
467
              if( mMode==MODE_LOOP || mMode==MODE_PATH ) time = (time>0.5f ? 2-2*time : 2*time);
468
             
469
              if( vn!=null )
470
                {
471
                time = noise(time,0);
472
              
473
                float dx2 = next.x-curr.x;
474
                float dy2 = next.y-curr.y;
475
   
476
                buffer[offset  ] = dx2*time + curr.x +dy2*mFactor;
477
                buffer[offset+1] = dy2*time + curr.y -dx2*mFactor;
478
                }
479
              else
480
                {
481
                buffer[offset  ] = (next.x-curr.x)*time + curr.x;
482
                buffer[offset+1] = (next.y-curr.y)*time + curr.y;
483
                }
484
              
485
              break;
486
      default:float t = time;
487
        
488
              switch(mMode)
489
                {
490
                case MODE_LOOP: time = time*numPoints;
491
                                break;
492
                case MODE_PATH: time = (time<=0.5f) ? 2*time*(numPoints-1) : 2*(1-time)*(numPoints-1);
493
                                break;
494
                case MODE_JUMP: time = time*(numPoints-1);
495
                                break;
496
                }
497
            
498
              int vecCurr = (int)time;
499
              time = time-vecCurr;
500
      
501
              if( vecCurr>=0 && vecCurr<numPoints )
502
                { 
503
                if( cacheDirty ) recomputeCache();    // recompute cache if we have added or remove vectors since last computation
504
                else if( mVecCurr!= vecCurr )         // ...or if we have just passed a vector and the vector we are currently flying to has changed
505
                  {
506
                  int vecNext;   
507
                  mVecCurr = vecCurr;
508
                                
509
                  switch(mMode)
510
                    {
511
                    case MODE_LOOP: vecNext = vecCurr==numPoints-1 ? 0:vecCurr+1; 
512
                                    break;
513
                    case MODE_PATH: if( t<0.5f ) vecNext = vecCurr==numPoints-1 ? numPoints-2: vecCurr+1;  
514
                                    else         vecNext = vecCurr==0 ? 1 : vecCurr-1;  
515
                                    break;
516
                    case MODE_JUMP: vecNext = vecCurr==numPoints-1 ? 1:vecCurr+1;
517
                                    break;
518
                    default       : vecNext = 0;                
519
                    }
520
              
521
                  next = vv.elementAt(vecNext);
522
                  tmp2 = vc.elementAt(vecNext);
523
              
524
                  if( tmp2.vx!=next.x || tmp2.vy!=next.y ) recomputeCache();
525
                  }
526
              
527
                if( vn!=null )
528
                  {
529
                  time = noise(time,vecCurr);
530
                  tmp1 = vc.elementAt(vecCurr);
531
               
532
                  float dx2 = (3*tmp1.ax*time+2*tmp1.bx)*time + tmp1.cx;
533
                  float dy2 = (3*tmp1.ay*time+2*tmp1.by)*time + tmp1.cy;
534
                 
535
                  buffer[offset  ]= ((tmp1.ax*time+tmp1.bx)*time+tmp1.cx)*time+tmp1.dx +dy2*mFactor;
536
                  buffer[offset+1]= ((tmp1.ay*time+tmp1.by)*time+tmp1.cy)*time+tmp1.dy -dx2*mFactor;
537
                  } 
538
                else
539
                  {
540
                  tmp1 = vc.elementAt(vecCurr);
541
                  buffer[offset  ]= ((tmp1.ax*time+tmp1.bx)*time+tmp1.cx)*time+tmp1.dx;
542
                  buffer[offset+1]= ((tmp1.ay*time+tmp1.by)*time+tmp1.cy)*time+tmp1.dy;
543
                  }
544
                
545
                break;
546
                }
547
      }
548
    }  
549
  }
550
///////////////////////////////////////////////////////////////////////////////////////////////////
551
//
(27-27/30)