Project

General

Profile

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

library / src / main / java / org / distorted / library / type / DynamicQuat.java @ c59fc52d

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2016 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// Distorted is free software: you can redistribute it and/or modify                             //
7
// it under the terms of the GNU General Public License as published by                          //
8
// the Free Software Foundation, either version 2 of the License, or                             //
9
// (at your option) any later version.                                                           //
10
//                                                                                               //
11
// Distorted is distributed in the hope that it will be useful,                                  //
12
// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
13
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
14
// GNU General Public License for more details.                                                  //
15
//                                                                                               //
16
// You should have received a copy of the GNU General Public License                             //
17
// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
18
///////////////////////////////////////////////////////////////////////////////////////////////////
19

    
20
package org.distorted.library.type;
21

    
22
import java.util.Vector;
23

    
24
///////////////////////////////////////////////////////////////////////////////////////////////////
25
/** 
26
* A 4-dimensional implementation of the Dynamic class to interpolate between a list
27
* of Static4Ds.
28
* Here, the Points are assumed to be Quaternions - thus we do the Spherical Linear Interpolation, aka
29
* SLERP. Noise not supported (yet?).
30
*
31
* Only unit quaternions represent valid rotations in 3D - and interpolating through rotations is the
32
* most common use case for this class. No effort is done to normalize the Points though.
33
*/
34

    
35
public class DynamicQuat extends Dynamic implements Data4D
36
  {
37
 
38
///////////////////////////////////////////////////////////////////////////////////////////////////
39
// Here we implement our own Cache as we need something slightly different.
40
// omega, sinOmega, cosOmega - angle between pair of quaternions, its sinus and cosinus.
41
//  
42
// (vx,vy,vz,vw) is the original vector from vv (copied here so when interpolating we can see if it is 
43
// still valid and if not - rebuild the Cache.
44
  
45
  private class VectorCacheQuat
46
    {
47
    float omega, sinOmega,cosOmega;
48
    float vx,vy,vz,vw;
49
    }
50
  
51
  private Vector<VectorCacheQuat> vc;
52
  private VectorCacheQuat tmp1, tmp2;
53

    
54
  private Vector<Static4D> vv;
55
  private Static4D curr, next;
56
 
57
///////////////////////////////////////////////////////////////////////////////////////////////////
58
// Abramowitz / Stegun
59

    
60
  private static float arcCos(float x)
61
    {
62
    if( x<0 )
63
      return 3.14159265358979f - (float)Math.sqrt(1+x)*(1.5707288f + 0.2121144f*x + 0.074261f*x*x + 0.0187293f*x*x*x);
64
     
65
    return (float)Math.sqrt(1-x)*(1.5707288f - 0.2121144f*x + 0.074261f*x*x - 0.0187293f*x*x*x);
66
    }
67

    
68
///////////////////////////////////////////////////////////////////////////////////////////////////
69

    
70
  private void recomputeCache()
71
    {  
72
    if( numPoints>=2 )
73
      {
74
      int i, n;  
75
      Static4D cu,ne;
76
      VectorCacheQuat vq;
77

    
78
      for(i=0; i<numPoints; i++)
79
        {
80
        n = i<numPoints-1 ? i+1:0;  
81
      
82
        vq= vc.elementAt(i);
83
        cu= vv.elementAt(i);
84
        ne= vv.elementAt(n);
85
      
86
        vq.vx = cu.x;
87
        vq.vy = cu.y;
88
        vq.vz = cu.z;
89
        vq.vw = cu.w;
90
    	
91
        vq.cosOmega = cu.x*ne.x + cu.y*ne.y + cu.z*ne.z + cu.w*ne.w;
92
        vq.sinOmega = (float)Math.sqrt(1-vq.cosOmega*vq.cosOmega);
93
        vq.omega    = arcCos(vq.cosOmega);
94
        }
95
      }
96
   
97
    cacheDirty = false;
98
    }
99

    
100
///////////////////////////////////////////////////////////////////////////////////////////////////
101
// PUBLIC API
102
///////////////////////////////////////////////////////////////////////////////////////////////////
103
/**
104
 * Default constructor.
105
 */
106
  public DynamicQuat()
107
    {
108
    this(0,0.5f);
109
    }
110

    
111
///////////////////////////////////////////////////////////////////////////////////////////////////
112
/**
113
 * Constructor setting the speed of interpolation and the number of revolutions.
114
 *
115
 * What constitutes 'one revolution' depends on the MODE:
116
 * {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
117
 *
118
 * @param duration number of milliseconds it takes to do one revolution.
119
 * @param count    number of revolutions we will do. Count<=0 means 'infinite'.
120
 */
121
  public DynamicQuat(int duration, float count)
122
    {
123
    vv         = new Vector<>();
124
    vc         = new Vector<>();
125
    numPoints  = 0;
126
    cacheDirty = false;
127
    mMode      = MODE_LOOP;
128
    mDuration  = duration;
129
    mCount     = count;
130
    mLastPos   = -1;
131
    mAccessType = ACCESS_TYPE_RANDOM;
132
    mDimension = 4;
133
    }
134

    
135
///////////////////////////////////////////////////////////////////////////////////////////////////
136
/**
137
 * Returns the location'th Static4D.
138
 *   
139
 * @param location the index of the Point we are interested in.
140
 * @return The Static4D, if 0<=location&lt;getNumPoints(), or null otherwise.
141
 */  
142
  public synchronized Static4D getPoint(int location)
143
    {
144
    return (location>=0 && location<numPoints) ? vv.elementAt(location) : null;  
145
    }
146
  
147
///////////////////////////////////////////////////////////////////////////////////////////////////
148
/**
149
 * Resets the location'th Point.
150
 *
151
 * @param location the index of the Point we are setting.
152
 * @param x New value of its first float.
153
 */
154
  public synchronized void setPoint(int location, float x, float y, float z, float w)
155
    {
156
    if( location>=0 && location<numPoints )
157
      {
158
      curr = vv.elementAt(location);
159
   
160
      if( curr!=null )
161
        {
162
        curr.set(x,y,z,w);
163
        cacheDirty=true;
164
        }
165
      }
166
    }
167

    
168
///////////////////////////////////////////////////////////////////////////////////////////////////
169
/**
170
 * Adds a new Static4D to the end of our list of Points to interpolate through.
171
 * <p>   
172
 * Only a reference to the Point gets added to the List; this means that one can add a Point 
173
 * here, and later on {@link Static4D#set(float,float,float,float)} it to some new value and
174
 * the change will be seamlessly reflected in the interpolated path.  
175
 * <p>
176
 * A Point can be added multiple times.
177
 *   
178
 * @param v The Point to add.
179
 */    
180
  public synchronized void add(Static4D v)
181
    {
182
    if( v!=null )
183
      {
184
      vv.add(v);
185
      
186
      switch(numPoints)
187
         {
188
         case 0: 
189
         case 1: vc.add(new VectorCacheQuat());
190
                 vc.add(new VectorCacheQuat());
191
        	     break;
192
         default:vc.add(new VectorCacheQuat());
193
         }
194

    
195
       numPoints++;
196
       cacheDirty = true;
197
       }
198
    }
199

    
200
///////////////////////////////////////////////////////////////////////////////////////////////////
201
/**
202
 * Adds a new Static4D to the location'th place in our List of Points to interpolate through.
203
 *   
204
 * @param location Index in our List to add the new Point at.
205
 * @param v The Static4D to add.
206
 */  
207
  public synchronized void add(int location, Static4D v)
208
    {
209
    if( v!=null )
210
      {
211
      vv.add(location, v);
212
      
213
      switch(numPoints)
214
        {
215
        case 0: 
216
        case 1: vc.add(new VectorCacheQuat());
217
                vc.add(new VectorCacheQuat());
218
                break;
219
        default:vc.add(location,new VectorCacheQuat());
220
        }
221

    
222
      numPoints++;
223
      cacheDirty = true;
224
      }
225
    }
226
  
227
///////////////////////////////////////////////////////////////////////////////////////////////////
228
/**
229
 * Removes all occurrences of Point v from the List of Points to interpolate through.  
230
 * 
231
 * @param v The Point to remove.
232
 * @return <code>true</code> if we have removed at least one Point.
233
 */
234
  public synchronized boolean remove(Static4D v)
235
    {
236
    int n = vv.indexOf(v);
237
    boolean found = false;
238
   
239
    while( n>=0 ) 
240
      {
241
      vv.remove(n);
242
     
243
      switch(numPoints)
244
        {
245
        case 0:
246
        case 1: break;
247
        case 2: vc.removeAllElements();
248
                break;
249
        default:vc.remove(n);
250
        }
251

    
252
      numPoints--;
253
      found = true;
254
      n = vv.indexOf(v);
255
      }
256
   
257
    if( found ) 
258
      {
259
      cacheDirty=true;
260
      }
261
   
262
    return found;
263
    }
264

    
265
///////////////////////////////////////////////////////////////////////////////////////////////////
266
/**
267
 * Removes a location'th Point from the List of Points we interpolate through.
268
 * 
269
 * @param location index of the Point we want to remove. 
270
 * @return <code>true</code> if location is valid, i.e. if 0<=location&lt;getNumPoints().
271
 */
272
  public synchronized boolean remove(int location)
273
    {
274
    if( location>=0 && location<numPoints ) 
275
      {
276
      vv.removeElementAt(location);
277
      
278
      switch(numPoints)
279
        {
280
        case 0: 
281
        case 1: break;
282
        case 2: vc.removeAllElements();
283
                break;
284
        default:vc.removeElementAt(location);
285
        }
286

    
287
      numPoints--;
288
      cacheDirty = true; 
289
      return true;
290
      }
291

    
292
    return false;
293
    }
294
  
295
///////////////////////////////////////////////////////////////////////////////////////////////////
296
/**
297
 * Removes all Points.
298
 */
299
  public synchronized void removeAll()
300
    {
301
    numPoints = 0;
302
    vv.removeAllElements();
303
    vc.removeAllElements();
304
    cacheDirty = false;
305
    }
306
  
307
///////////////////////////////////////////////////////////////////////////////////////////////////
308
/**
309
 * Writes the results of interpolation between the Points at time 'time' to the passed float buffer.
310
 * Interpolation is done using the spherical linear algorithm, aka SLERP.
311
 * <p>
312
 * Since this is a 4-dimensional Dynamic, the resulting interpolated Static4D gets written
313
 * to four locations in the buffer: buffer[offset], buffer[offset+1], buffer[offset+2] and buffer[offset+3]. 
314
 * 
315
 * @param buffer Float buffer we will write the resulting Static4D to.
316
 * @param offset Offset in the buffer where to write the result.
317
 * @param time   Time of interpolation. Time=0.0 is the beginning of the first revolution, time=1.0 - the end
318
 *               of the first revolution, time=2.5 - the middle of the third revolution.
319
 *               What constitutes 'one revolution' depends on the MODE:
320
 *               {@link Dynamic#MODE_LOOP}, {@link Dynamic#MODE_PATH} or {@link Dynamic#MODE_JUMP}.
321
 **/
322
  synchronized void interpolate(float[] buffer, int offset, float time)
323
    {  
324
    switch(numPoints)
325
      {
326
      case 0: buffer[offset  ] = 0.0f;
327
              buffer[offset+1] = 0.0f;
328
              buffer[offset+2] = 0.0f;
329
              buffer[offset+3] = 0.0f;
330
              break;
331
      case 1: curr = vv.elementAt(0);
332
              buffer[offset  ] = curr.x; 
333
              buffer[offset+1] = curr.y;
334
              buffer[offset+2] = curr.z;
335
              buffer[offset+3] = curr.w;
336
              break;
337
      default:float t = time;
338
              int vecCurr, segment;
339
              float scale0, scale1;
340

    
341
              switch(mMode)
342
                {
343
                case MODE_LOOP: time = time*numPoints;
344
                                segment = (int)time;
345
                                vecCurr = segment;
346
                                break;
347
                case MODE_PATH: if( t>0.5f ) t = 1.0f-t;
348
                                time = 2*t*(numPoints-1);
349
                                segment = (int)(2*t*(numPoints-1));
350
                                vecCurr = segment;
351
                                break;
352
                case MODE_JUMP: time = time*(numPoints-1);
353
                                segment = (int)time;
354
                                vecCurr = segment;
355
                                break;
356
                default       : vecCurr = 0;
357
                                segment = 0;
358
                }
359

    
360
              if( vecCurr>=0 && vecCurr<numPoints )
361
                {
362
                int vecNext = getNext(vecCurr,t);
363

    
364
                curr = vv.elementAt(vecCurr);
365
                tmp1 = vc.elementAt(vecCurr);
366
                next = vv.elementAt(vecNext);
367

    
368
                if( cacheDirty ) recomputeCache();  // recompute cache if we have added or remove vectors since last computation
369
                else if( mSegment!= segment )       // ...or if we have just passed a vector and the vector we are currently flying to has changed
370
                  {
371
                  tmp2 = vc.elementAt(vecNext);
372

    
373
                  if( tmp2.vx!=next.x || tmp2.vy!=next.y || tmp2.vz!=next.z || tmp2.vw!=next.w ) recomputeCache();
374
                  }
375

    
376
                mSegment = segment;
377

    
378
                time = time-vecCurr;
379

    
380
                if( tmp1.sinOmega==0 )
381
                  {
382
                  scale0 = 1f;
383
                  scale1 = 0f;
384
                  }
385
                else if( tmp1.cosOmega < 0.99 )
386
                  {
387
                  scale0 = (float)Math.sin( (1f-time)*tmp1.omega ) / tmp1.sinOmega;
388
                  scale1 = (float)Math.sin(     time *tmp1.omega ) / tmp1.sinOmega;
389
                  }
390
                else
391
                  {
392
                  scale0 = 1f-time;
393
                  scale1 = time;
394
                  }
395

    
396
                buffer[offset  ] = scale0*curr.x + scale1*next.x;
397
                buffer[offset+1] = scale0*curr.y + scale1*next.y;
398
                buffer[offset+2] = scale0*curr.z + scale1*next.z;
399
                buffer[offset+3] = scale0*curr.w + scale1*next.w;
400

    
401
                break;
402
                }
403
      }
404
    }  
405

    
406
  }
(12-12/18)