Project

General

Profile

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

library / src / main / java / org / distorted / library / DistortedEffects.java @ ec231614

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 android.content.res.Resources;
23
import android.opengl.GLES30;
24
import android.opengl.Matrix;
25

    
26
import org.distorted.library.message.EffectListener;
27
import org.distorted.library.program.DistortedProgram;
28
import org.distorted.library.program.FragmentCompilationException;
29
import org.distorted.library.program.FragmentUniformsException;
30
import org.distorted.library.program.LinkingException;
31
import org.distorted.library.program.VertexCompilationException;
32
import org.distorted.library.program.VertexUniformsException;
33
import org.distorted.library.type.Data1D;
34
import org.distorted.library.type.Data2D;
35
import org.distorted.library.type.Data3D;
36
import org.distorted.library.type.Data4D;
37
import org.distorted.library.type.Data5D;
38
import org.distorted.library.type.Static3D;
39

    
40
import java.io.InputStream;
41
import java.nio.ByteBuffer;
42
import java.nio.ByteOrder;
43
import java.nio.FloatBuffer;
44

    
45
///////////////////////////////////////////////////////////////////////////////////////////////////
46
/**
47
 * Class containing Matrix,Vertex and Fragment effect queues. Postprocessing queue is held in a separate
48
 * class.
49
 * <p>
50
 * The queues hold actual effects to be applied to a given (DistortedTexture,MeshObject) combo.
51
 */
52
public class DistortedEffects
53
  {
54
  private static final int POSITION_DATA_SIZE= 3; // Main Program: size of the position data in elements
55
  private static final int NORMAL_DATA_SIZE  = 3; // Main Program: size of the normal data in elements
56
  private static final int TEX_DATA_SIZE     = 2; // Main Program: size of the texture coordinate data in elements.
57

    
58
  /// MAIN PROGRAM ///
59
  private static DistortedProgram mMainProgram;
60
  private static int mMainTextureH;
61
  private static boolean[] mEffectEnabled = new boolean[EffectNames.size()];
62

    
63
  static
64
    {
65
    int len = EffectNames.size();
66

    
67
    for(int i=0; i<len; i++)
68
      {
69
      mEffectEnabled[i] = false;
70
      }
71
    }
72

    
73
  /// BLIT PROGRAM ///
74
  private static DistortedProgram mBlitProgram;
75
  private static int mBlitTextureH;
76
  private static int mBlitDepthH;
77
  private static final FloatBuffer mQuadPositions;
78

    
79
  static
80
    {
81
    float[] positionData= { -0.5f, -0.5f,  -0.5f, 0.5f,  0.5f,-0.5f,  0.5f, 0.5f };
82
    mQuadPositions = ByteBuffer.allocateDirect(32).order(ByteOrder.nativeOrder()).asFloatBuffer();
83
    mQuadPositions.put(positionData).position(0);
84
    }
85

    
86
  /// DEBUG ONLY /////
87
  private static DistortedProgram mDebugProgram;
88

    
89
  private static int mDebugObjDH;
90
  private static int mDebugMVPMatrixH;
91
  /// END DEBUG //////
92

    
93
  private static float[] mMVPMatrix = new float[16];
94
  private static float[] mTmpMatrix = new float[16];
95

    
96
  private static long mNextID =0;
97
  private long mID;
98

    
99
  private EffectQueueMatrix      mM;
100
  private EffectQueueFragment    mF;
101
  private EffectQueueVertex      mV;
102

    
103
  private boolean matrixCloned, vertexCloned, fragmentCloned;
104

    
105
///////////////////////////////////////////////////////////////////////////////////////////////////
106

    
107
  static void createProgram(Resources resources)
108
  throws FragmentCompilationException,VertexCompilationException,VertexUniformsException,FragmentUniformsException,LinkingException
109
    {
110
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
111
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
112

    
113
    String mainVertHeader= Distorted.GLSL_VERSION;
114
    String mainFragHeader= Distorted.GLSL_VERSION;
115

    
116
    EffectNames name;
117
    EffectTypes type;
118
    boolean foundF = false;
119
    boolean foundV = false;
120

    
121
    for(int i=0; i<mEffectEnabled.length; i++)
122
      {
123
      if( mEffectEnabled[i] )
124
        {
125
        name = EffectNames.getName(i);
126
        type = EffectNames.getType(i);
127

    
128
        if( type == EffectTypes.VERTEX )
129
          {
130
          mainVertHeader += ("#define "+name.name()+" "+name.ordinal()+"\n");
131
          foundV = true;
132
          }
133
        else if( type == EffectTypes.FRAGMENT )
134
          {
135
          mainFragHeader += ("#define "+name.name()+" "+name.ordinal()+"\n");
136
          foundF = true;
137
          }
138
        }
139
      }
140

    
141
    mainVertHeader += ("#define NUM_VERTEX "   + ( foundV ? getMaxVertex()   : 0 ) + "\n");
142
    mainFragHeader += ("#define NUM_FRAGMENT " + ( foundF ? getMaxFragment() : 0 ) + "\n");
143

    
144
    //android.util.Log.e("Effects", "vertHeader= "+mainVertHeader);
145
    //android.util.Log.e("Effects", "fragHeader= "+mainFragHeader);
146

    
147
    mMainProgram = new DistortedProgram(mainVertStream,mainFragStream, mainVertHeader, mainFragHeader, Distorted.GLSL);
148

    
149
    int mainProgramH = mMainProgram.getProgramHandle();
150
    EffectQueueFragment.getUniforms(mainProgramH);
151
    EffectQueueVertex.getUniforms(mainProgramH);
152
    EffectQueueMatrix.getUniforms(mainProgramH);
153
    mMainTextureH= GLES30.glGetUniformLocation( mainProgramH, "u_Texture");
154

    
155
    // BLIT PROGRAM ////////////////////////////////////
156
    final InputStream blitVertStream = resources.openRawResource(R.raw.blit_vertex_shader);
157
    final InputStream blitFragStream = resources.openRawResource(R.raw.blit_fragment_shader);
158

    
159
    String blitVertHeader= (Distorted.GLSL_VERSION + "#define NUM_VERTEX 0\n"  );
160
    String blitFragHeader= (Distorted.GLSL_VERSION + "#define NUM_FRAGMENT 0\n");
161

    
162
    try
163
      {
164
      mBlitProgram = new DistortedProgram(blitVertStream,blitFragStream,blitVertHeader,blitFragHeader, Distorted.GLSL);
165
      }
166
    catch(Exception e)
167
      {
168
      android.util.Log.e("EFFECTS", "exception trying to compile BLIT program: "+e.getMessage());
169
      throw new RuntimeException(e.getMessage());
170
      }
171

    
172
    int blitProgramH = mBlitProgram.getProgramHandle();
173
    mBlitTextureH  = GLES30.glGetUniformLocation( blitProgramH, "u_Texture");
174
    mBlitDepthH    = GLES30.glGetUniformLocation( blitProgramH, "u_Depth");
175

    
176
    // DEBUG ONLY //////////////////////////////////////
177
    final InputStream debugVertexStream   = resources.openRawResource(R.raw.test_vertex_shader);
178
    final InputStream debugFragmentStream = resources.openRawResource(R.raw.test_fragment_shader);
179

    
180
    try
181
      {
182
      mDebugProgram = new DistortedProgram(debugVertexStream,debugFragmentStream, Distorted.GLSL_VERSION, Distorted.GLSL_VERSION, Distorted.GLSL);
183
      }
184
    catch(Exception e)
185
      {
186
      android.util.Log.e("EFFECTS", "exception trying to compile DEBUG program: "+e.getMessage());
187
      throw new RuntimeException(e.getMessage());
188
      }
189

    
190
    int debugProgramH = mDebugProgram.getProgramHandle();
191
    mDebugObjDH = GLES30.glGetUniformLocation( debugProgramH, "u_objD");
192
    mDebugMVPMatrixH = GLES30.glGetUniformLocation( debugProgramH, "u_MVPMatrix");
193
    // END DEBUG  //////////////////////////////////////
194
    }
195

    
196
///////////////////////////////////////////////////////////////////////////////////////////////////
197

    
198
  private void initializeEffectLists(DistortedEffects d, int flags)
199
    {
200
    if( (flags & Distorted.CLONE_MATRIX) != 0 )
201
      {
202
      mM = d.mM;
203
      matrixCloned = true;
204
      }
205
    else
206
      {
207
      mM = new EffectQueueMatrix(mID);
208
      matrixCloned = false;
209
      }
210
    
211
    if( (flags & Distorted.CLONE_VERTEX) != 0 )
212
      {
213
      mV = d.mV;
214
      vertexCloned = true;
215
      }
216
    else
217
      {
218
      mV = new EffectQueueVertex(mID);
219
      vertexCloned = false;
220
      }
221
    
222
    if( (flags & Distorted.CLONE_FRAGMENT) != 0 )
223
      {
224
      mF = d.mF;
225
      fragmentCloned = true;
226
      }
227
    else
228
      {
229
      mF = new EffectQueueFragment(mID);
230
      fragmentCloned = false;
231
      }
232
    }
233

    
234
///////////////////////////////////////////////////////////////////////////////////////////////////
235
// DEBUG ONLY
236

    
237
  @SuppressWarnings("unused")
238
  private void displayBoundingRect(float halfX, float halfY, float halfZ, DistortedOutputSurface surface, float[] mvp, float[] vertices, long currTime)
239
    {
240
    int len  = vertices.length/3;
241
    int minx = Integer.MAX_VALUE;
242
    int maxx = Integer.MIN_VALUE;
243
    int miny = Integer.MAX_VALUE;
244
    int maxy = Integer.MIN_VALUE;
245
    int wx,wy;
246

    
247
    float x,y,z, X,Y,W, ndcX,ndcY;
248

    
249
    for(int i=0; i<len; i++)
250
      {
251
      x = 2*halfX*vertices[3*i  ];
252
      y = 2*halfY*vertices[3*i+1];
253
      z = 2*halfZ*vertices[3*i+2];
254

    
255
      X = mvp[ 0]*x + mvp[ 4]*y + mvp[ 8]*z + mvp[12];
256
      Y = mvp[ 1]*x + mvp[ 5]*y + mvp[ 9]*z + mvp[13];
257
      W = mvp[ 3]*x + mvp[ 7]*y + mvp[11]*z + mvp[15];
258

    
259
      ndcX = X/W;
260
      ndcY = Y/W;
261

    
262
      wx = (int)(surface.mWidth *(ndcX+1)/2);
263
      wy = (int)(surface.mHeight*(ndcY+1)/2);
264

    
265
      if( wx<minx ) minx = wx;
266
      if( wx>maxx ) maxx = wx;
267
      if( wy<miny ) miny = wy;
268
      if( wy>maxy ) maxy = wy;
269
      }
270

    
271
    mDebugProgram.useProgram();
272
    surface.setAsOutput(currTime);
273

    
274
    Matrix.setIdentityM( mTmpMatrix, 0);
275
    Matrix.translateM  ( mTmpMatrix, 0, minx-surface.mWidth/2, maxy-surface.mHeight/2, -surface.mDistance);
276
    Matrix.scaleM      ( mTmpMatrix, 0, (float)(maxx-minx)/(2*halfX), (float)(maxy-miny)/(2*halfY), 1.0f);
277
    Matrix.translateM  ( mTmpMatrix, 0, halfX,-halfY, 0);
278
    Matrix.multiplyMM  ( mMVPMatrix, 0, surface.mProjectionMatrix, 0, mTmpMatrix, 0);
279

    
280
    GLES30.glUniform2f(mDebugObjDH, 2*halfX, 2*halfY);
281
    GLES30.glUniformMatrix4fv(mDebugMVPMatrixH, 1, false, mMVPMatrix , 0);
282

    
283
    GLES30.glVertexAttribPointer(mDebugProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
284
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
285
    }
286

    
287
///////////////////////////////////////////////////////////////////////////////////////////////////
288

    
289
  void drawPriv(float halfW, float halfH, MeshObject mesh, DistortedOutputSurface surface, long currTime)
290
    {
291
    mM.compute(currTime);
292
    mV.compute(currTime);
293
    mF.compute(currTime);
294

    
295
    float halfZ = halfW*mesh.zFactor;
296
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight);
297

    
298
    mMainProgram.useProgram();
299
    GLES30.glUniform1i(mMainTextureH, 0);
300
    surface.setAsOutput(currTime);
301
    mM.send(surface,halfW,halfH,halfZ);
302
    mV.send(halfW,halfH,halfZ);
303
    mF.send(halfW,halfH);
304
    GLES30.glVertexAttribPointer(mMainProgram.mAttribute[0], POSITION_DATA_SIZE, GLES30.GL_FLOAT, false, 0, mesh.mMeshPositions);
305
    GLES30.glVertexAttribPointer(mMainProgram.mAttribute[1], NORMAL_DATA_SIZE  , GLES30.GL_FLOAT, false, 0, mesh.mMeshNormals);
306
    GLES30.glVertexAttribPointer(mMainProgram.mAttribute[2], TEX_DATA_SIZE     , GLES30.GL_FLOAT, false, 0, mesh.mMeshTexture);
307
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.dataLength);
308

    
309
    /// DEBUG ONLY //////
310
    // displayBoundingRect(halfInputW, halfInputH, halfZ, df, mM.getMVP(), mesh.getBoundingVertices() );
311
    /// END DEBUG ///////
312
    }
313

    
314
///////////////////////////////////////////////////////////////////////////////////////////////////
315
   
316
  static void blitPriv(DistortedOutputSurface projection)
317
    {
318
    mBlitProgram.useProgram();
319

    
320
    GLES30.glViewport(0, 0, projection.mWidth, projection.mHeight);
321
    GLES30.glUniform1i(mBlitTextureH, 0);
322
    GLES30.glUniform1f( mBlitDepthH , 1.0f-projection.mNear);
323
    GLES30.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
324
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
325
    }
326
    
327
///////////////////////////////////////////////////////////////////////////////////////////////////
328
   
329
  private void releasePriv()
330
    {
331
    if( !matrixCloned     ) mM.abortAll(false);
332
    if( !vertexCloned     ) mV.abortAll(false);
333
    if( !fragmentCloned   ) mF.abortAll(false);
334

    
335
    mM = null;
336
    mV = null;
337
    mF = null;
338
    }
339

    
340
///////////////////////////////////////////////////////////////////////////////////////////////////
341

    
342
  static void onDestroy()
343
    {
344
    mNextID = 0;
345

    
346
    int len = EffectNames.size();
347

    
348
    for(int i=0; i<len; i++)
349
      {
350
      mEffectEnabled[i] = false;
351
      }
352
    }
353

    
354
///////////////////////////////////////////////////////////////////////////////////////////////////
355
// PUBLIC API
356
///////////////////////////////////////////////////////////////////////////////////////////////////
357
/**
358
 * Create empty effect queue.
359
 */
360
  public DistortedEffects()
361
    {
362
    mID = ++mNextID;
363
    initializeEffectLists(this,0);
364
    }
365

    
366
///////////////////////////////////////////////////////////////////////////////////////////////////
367
/**
368
 * Copy constructor.
369
 * <p>
370
 * Whatever we do not clone gets created just like in the default constructor.
371
 *
372
 * @param dc    Source object to create our object from
373
 * @param flags A bitmask of values specifying what to copy.
374
 *              For example, CLONE_VERTEX | CLONE_MATRIX.
375
 */
376
  public DistortedEffects(DistortedEffects dc, int flags)
377
    {
378
    mID = ++mNextID;
379
    initializeEffectLists(dc,flags);
380
    }
381

    
382
///////////////////////////////////////////////////////////////////////////////////////////////////
383
/**
384
 * Releases all resources. After this call, the queue should not be used anymore.
385
 */
386
  @SuppressWarnings("unused")
387
  public synchronized void delete()
388
    {
389
    releasePriv();
390
    }
391

    
392
///////////////////////////////////////////////////////////////////////////////////////////////////
393
/**
394
 * Returns unique ID of this instance.
395
 *
396
 * @return ID of the object.
397
 */
398
  public long getID()
399
      {
400
      return mID;
401
      }
402

    
403
///////////////////////////////////////////////////////////////////////////////////////////////////
404
/**
405
 * Adds the calling class to the list of Listeners that get notified each time some event happens 
406
 * to one of the Effects in those queues. Nothing will happen if 'el' is already in the list.
407
 * 
408
 * @param el A class implementing the EffectListener interface that wants to get notifications.
409
 */
410
  @SuppressWarnings("unused")
411
  public void registerForMessages(EffectListener el)
412
    {
413
    mV.registerForMessages(el);
414
    mF.registerForMessages(el);
415
    mM.registerForMessages(el);
416
    }
417

    
418
///////////////////////////////////////////////////////////////////////////////////////////////////
419
/**
420
 * Removes the calling class from the list of Listeners.
421
 * 
422
 * @param el A class implementing the EffectListener interface that no longer wants to get notifications.
423
 */
424
  @SuppressWarnings("unused")
425
  public void deregisterForMessages(EffectListener el)
426
    {
427
    mV.deregisterForMessages(el);
428
    mF.deregisterForMessages(el);
429
    mM.deregisterForMessages(el);
430
    }
431

    
432
///////////////////////////////////////////////////////////////////////////////////////////////////
433
/**
434
 * Aborts all Effects.
435
 * @return Number of effects aborted.
436
 */
437
  public int abortAllEffects()
438
    {
439
    return mM.abortAll(true) + mV.abortAll(true) + mF.abortAll(true);
440
    }
441

    
442
///////////////////////////////////////////////////////////////////////////////////////////////////
443
/**
444
 * Aborts all Effects of a given type, for example all MATRIX Effects.
445
 * 
446
 * @param type one of the constants defined in {@link EffectTypes}
447
 * @return Number of effects aborted.
448
 */
449
  public int abortEffects(EffectTypes type)
450
    {
451
    switch(type)
452
      {
453
      case MATRIX     : return mM.abortAll(true);
454
      case VERTEX     : return mV.abortAll(true);
455
      case FRAGMENT   : return mF.abortAll(true);
456
      default         : return 0;
457
      }
458
    }
459
    
460
///////////////////////////////////////////////////////////////////////////////////////////////////
461
/**
462
 * Aborts a single Effect.
463
 * 
464
 * @param id ID of the Effect we want to abort.
465
 * @return number of Effects aborted. Always either 0 or 1.
466
 */
467
  public int abortEffect(long id)
468
    {
469
    int type = (int)(id&EffectTypes.MASK);
470

    
471
    if( type==EffectTypes.MATRIX.type      ) return mM.removeByID(id>>EffectTypes.LENGTH);
472
    if( type==EffectTypes.VERTEX.type      ) return mV.removeByID(id>>EffectTypes.LENGTH);
473
    if( type==EffectTypes.FRAGMENT.type    ) return mF.removeByID(id>>EffectTypes.LENGTH);
474

    
475
    return 0;
476
    }
477

    
478
///////////////////////////////////////////////////////////////////////////////////////////////////
479
/**
480
 * Abort all Effects of a given name, for example all rotations.
481
 * 
482
 * @param name one of the constants defined in {@link EffectNames}
483
 * @return number of Effects aborted.
484
 */
485
  public int abortEffects(EffectNames name)
486
    {
487
    switch(name.getType())
488
      {
489
      case MATRIX     : return mM.removeByType(name);
490
      case VERTEX     : return mV.removeByType(name);
491
      case FRAGMENT   : return mF.removeByType(name);
492
      default         : return 0;
493
      }
494
    }
495
    
496
///////////////////////////////////////////////////////////////////////////////////////////////////
497
/**
498
 * Print some info about a given Effect to Android's standard out. Used for debugging only.
499
 * 
500
 * @param id Effect ID we want to print info about
501
 * @return <code>true</code> if a single Effect of type effectType has been found.
502
 */
503
  @SuppressWarnings("unused")
504
  public boolean printEffect(long id)
505
    {
506
    int type = (int)(id&EffectTypes.MASK);
507

    
508
    if( type==EffectTypes.MATRIX.type  )  return mM.printByID(id>>EffectTypes.LENGTH);
509
    if( type==EffectTypes.VERTEX.type  )  return mV.printByID(id>>EffectTypes.LENGTH);
510
    if( type==EffectTypes.FRAGMENT.type)  return mF.printByID(id>>EffectTypes.LENGTH);
511

    
512
    return false;
513
    }
514

    
515
///////////////////////////////////////////////////////////////////////////////////////////////////
516
/**
517
 * Enables a given Effect.
518
 * <p>
519
 * By default, all effects are disabled. One has to explicitly enable each effect one intends to use.
520
 * This needs to be called BEFORE shaders get compiled, i.e. before the call to Distorted.onCreate().
521
 * The point: by enabling only the effects we need, we can optimize the shaders.
522
 *
523
 * @param name Name of the Effect to enable.
524
 */
525
  public static void enableEffect(EffectNames name)
526
    {
527
    mEffectEnabled[name.ordinal()] = true;
528
    }
529

    
530
///////////////////////////////////////////////////////////////////////////////////////////////////
531
/**
532
 * Returns the maximum number of Matrix effects.
533
 *
534
 * @return The maximum number of Matrix effects
535
 */
536
  @SuppressWarnings("unused")
537
  public static int getMaxMatrix()
538
    {
539
    return EffectQueue.getMax(EffectTypes.MATRIX.ordinal());
540
    }
541

    
542
///////////////////////////////////////////////////////////////////////////////////////////////////
543
/**
544
 * Returns the maximum number of Vertex effects.
545
 *
546
 * @return The maximum number of Vertex effects
547
 */
548
  @SuppressWarnings("unused")
549
  public static int getMaxVertex()
550
    {
551
    return EffectQueue.getMax(EffectTypes.VERTEX.ordinal());
552
    }
553

    
554
///////////////////////////////////////////////////////////////////////////////////////////////////
555
/**
556
 * Returns the maximum number of Fragment effects.
557
 *
558
 * @return The maximum number of Fragment effects
559
 */
560
  @SuppressWarnings("unused")
561
  public static int getMaxFragment()
562
    {
563
    return EffectQueue.getMax(EffectTypes.FRAGMENT.ordinal());
564
    }
565

    
566
///////////////////////////////////////////////////////////////////////////////////////////////////
567
/**
568
 * Sets the maximum number of Matrix effects that can be stored in a single EffectQueue at one time.
569
 * This can fail if:
570
 * <ul>
571
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
572
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
573
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link Distorted#onCreate}. After this
574
 *     time only decreasing the value of 'max' is permitted.
575
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
576
 * </ul>
577
 *
578
 * @param max new maximum number of simultaneous Matrix Effects. Has to be a non-negative number not greater
579
 *            than Byte.MAX_VALUE
580
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
581
 */
582
  @SuppressWarnings("unused")
583
  public static boolean setMaxMatrix(int max)
584
    {
585
    return EffectQueue.setMax(EffectTypes.MATRIX.ordinal(),max);
586
    }
587

    
588
///////////////////////////////////////////////////////////////////////////////////////////////////
589
/**
590
 * Sets the maximum number of Vertex effects that can be stored in a single EffectQueue at one time.
591
 * This can fail if:
592
 * <ul>
593
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
594
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
595
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link Distorted#onCreate}. After this
596
 *     time only decreasing the value of 'max' is permitted.
597
* <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
598
 * </ul>
599
 *
600
 * @param max new maximum number of simultaneous Vertex Effects. Has to be a non-negative number not greater
601
 *            than Byte.MAX_VALUE
602
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
603
 */
604
  @SuppressWarnings("unused")
605
  public static boolean setMaxVertex(int max)
606
    {
607
    return EffectQueue.setMax(EffectTypes.VERTEX.ordinal(),max);
608
    }
609

    
610
///////////////////////////////////////////////////////////////////////////////////////////////////
611
/**
612
 * Sets the maximum number of Fragment effects that can be stored in a single EffectQueue at one time.
613
 * This can fail if:
614
 * <ul>
615
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
616
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
617
 *     before the Fragment Shader gets compiled, i.e. before the call to {@link Distorted#onCreate}. After this
618
 *     time only decreasing the value of 'max' is permitted.
619
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
620
 * </ul>
621
 *
622
 * @param max new maximum number of simultaneous Fragment Effects. Has to be a non-negative number not greater
623
 *            than Byte.MAX_VALUE
624
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
625
 */
626
  @SuppressWarnings("unused")
627
  public static boolean setMaxFragment(int max)
628
    {
629
    return EffectQueue.setMax(EffectTypes.FRAGMENT.ordinal(),max);
630
    }
631

    
632
///////////////////////////////////////////////////////////////////////////////////////////////////   
633
///////////////////////////////////////////////////////////////////////////////////////////////////
634
// Individual effect functions.
635
///////////////////////////////////////////////////////////////////////////////////////////////////
636
// Matrix-based effects
637
///////////////////////////////////////////////////////////////////////////////////////////////////
638
/**
639
 * Moves the Object by a (possibly changing in time) vector.
640
 * 
641
 * @param vector 3-dimensional Data which at any given time will return a Static3D representing
642
 *               the current coordinates of the vector we want to move the Object with.
643
 *               Units: to make it independent of the dimensions of the surface we are rendering to,
644
 *               the vector's unit is the size of the surface in each direction; i.e. a move(0.3,0.7,0.0)
645
 *               will move our object 30% of the width of the surface to the right and 70% of its height
646
 *               down.
647
 * @return       ID of the effect added, or -1 if we failed to add one.
648
 */
649
  public long move(Data3D vector)
650
    {   
651
    return mM.add(EffectNames.MOVE,vector);
652
    }
653

    
654
///////////////////////////////////////////////////////////////////////////////////////////////////
655
/**
656
 * Scales the Object by (possibly changing in time) 3D scale factors.
657
 * 
658
 * @param scale 3-dimensional Data which at any given time returns a Static3D
659
 *              representing the current x- , y- and z- scale factors.
660
 *              Example: a scale(2,1,-0.5) makes the object 2 times wider, keeps the height
661
 *              unchanged, and makes it twice thinner in Z-axis shifting the originally further
662
 *              wall in front of the originally closer to the camera one.
663
 * @return      ID of the effect added, or -1 if we failed to add one.
664
 */
665
  public long scale(Data3D scale)
666
    {   
667
    return mM.add(EffectNames.SCALE,scale);
668
    }
669

    
670
///////////////////////////////////////////////////////////////////////////////////////////////////
671
/**
672
 * Scales the Object by one uniform, constant factor in all 3 dimensions. Convenience function.
673
 *
674
 * @param scale The factor to scale all 3 dimensions with.
675
 * @return      ID of the effect added, or -1 if we failed to add one.
676
 */
677
  public long scale(float scale)
678
    {
679
    return mM.add(EffectNames.SCALE, new Static3D(scale,scale,scale));
680
    }
681

    
682
///////////////////////////////////////////////////////////////////////////////////////////////////
683
/**
684
 * Rotates the Object by 'angle' degrees around the center.
685
 * Static axis of rotation is given by the 2nd parameter.
686
 *
687
 * @param angle  Angle that we want to rotate the Object to. Unit: degrees
688
 * @param axis   Axis of rotation
689
 * @param center Coordinates of the Point we are rotating around.
690
 * @return       ID of the effect added, or -1 if we failed to add one.
691
 */
692
  public long rotate(Data1D angle, Static3D axis, Data3D center )
693
    {   
694
    return mM.add(EffectNames.ROTATE, angle, axis, center);
695
    }
696

    
697
///////////////////////////////////////////////////////////////////////////////////////////////////
698
/**
699
 * Rotates the Object by 'angle' degrees around the center.
700
 * Here both angle and axis can dynamically change.
701
 *
702
 * @param angleaxis Combined 4-tuple representing the (angle,axisX,axisY,axisZ).
703
 * @param center    Coordinates of the Point we are rotating around.
704
 * @return          ID of the effect added, or -1 if we failed to add one.
705
 */
706
  public long rotate(Data4D angleaxis, Data3D center)
707
    {
708
    return mM.add(EffectNames.ROTATE, angleaxis, center);
709
    }
710

    
711
///////////////////////////////////////////////////////////////////////////////////////////////////
712
/**
713
 * Rotates the Object by quaternion.
714
 *
715
 * @param quaternion The quaternion describing the rotation.
716
 * @param center     Coordinates of the Point we are rotating around.
717
 * @return           ID of the effect added, or -1 if we failed to add one.
718
 */
719
  public long quaternion(Data4D quaternion, Data3D center )
720
    {
721
    return mM.add(EffectNames.QUATERNION,quaternion,center);
722
    }
723

    
724
///////////////////////////////////////////////////////////////////////////////////////////////////
725
/**
726
 * Shears the Object.
727
 *
728
 * @param shear   The 3-tuple of shear factors. The first controls level
729
 *                of shearing in the X-axis, second - Y-axis and the third -
730
 *                Z-axis. Each is the tangent of the shear angle, i.e 0 -
731
 *                no shear, 1 - shear by 45 degrees (tan(45deg)=1) etc.
732
 * @param center  Center of shearing, i.e. the point which stays unmoved.
733
 * @return        ID of the effect added, or -1 if we failed to add one.
734
 */
735
  public long shear(Data3D shear, Data3D center)
736
    {
737
    return mM.add(EffectNames.SHEAR, shear, center);
738
    }
739

    
740
///////////////////////////////////////////////////////////////////////////////////////////////////
741
// Fragment-based effects  
742
///////////////////////////////////////////////////////////////////////////////////////////////////
743
/**
744
 * Makes a certain sub-region of the Object smoothly change all three of its RGB components.
745
 *        
746
 * @param blend  1-dimensional Data that returns the level of blend a given pixel will be
747
 *               mixed with the next parameter 'color': pixel = (1-level)*pixel + level*color.
748
 *               Valid range: <0,1>
749
 * @param color  Color to mix. (1,0,0) is RED.
750
 * @param region Region this Effect is limited to.
751
 * @param smooth If true, the level of 'blend' will smoothly fade out towards the edges of the region.
752
 * @return       ID of the effect added, or -1 if we failed to add one.
753
 */
754
  public long chroma(Data1D blend, Data3D color, Data4D region, boolean smooth)
755
    {
756
    return mF.add( smooth? EffectNames.SMOOTH_CHROMA:EffectNames.CHROMA, blend, color, region);
757
    }
758

    
759
///////////////////////////////////////////////////////////////////////////////////////////////////
760
/**
761
 * Makes the whole Object smoothly change all three of its RGB components.
762
 *
763
 * @param blend  1-dimensional Data that returns the level of blend a given pixel will be
764
 *               mixed with the next parameter 'color': pixel = (1-level)*pixel + level*color.
765
 *               Valid range: <0,1>
766
 * @param color  Color to mix. (1,0,0) is RED.
767
 * @return       ID of the effect added, or -1 if we failed to add one.
768
 */
769
  public long chroma(Data1D blend, Data3D color)
770
    {
771
    return mF.add(EffectNames.CHROMA, blend, color);
772
    }
773

    
774
///////////////////////////////////////////////////////////////////////////////////////////////////
775
/**
776
 * Makes a certain sub-region of the Object smoothly change its transparency level.
777
 *        
778
 * @param alpha  1-dimensional Data that returns the level of transparency we want to have at any given
779
 *               moment: pixel.a *= alpha.
780
 *               Valid range: <0,1>
781
 * @param region Region this Effect is limited to. 
782
 * @param smooth If true, the level of 'alpha' will smoothly fade out towards the edges of the region.
783
 * @return       ID of the effect added, or -1 if we failed to add one. 
784
 */
785
  public long alpha(Data1D alpha, Data4D region, boolean smooth)
786
    {
787
    return mF.add( smooth? EffectNames.SMOOTH_ALPHA:EffectNames.ALPHA, alpha, region);
788
    }
789

    
790
///////////////////////////////////////////////////////////////////////////////////////////////////
791
/**
792
 * Makes the whole Object smoothly change its transparency level.
793
 *
794
 * @param alpha  1-dimensional Data that returns the level of transparency we want to have at any
795
 *               given moment: pixel.a *= alpha.
796
 *               Valid range: <0,1>
797
 * @return       ID of the effect added, or -1 if we failed to add one.
798
 */
799
  public long alpha(Data1D alpha)
800
    {
801
    return mF.add(EffectNames.ALPHA, alpha);
802
    }
803

    
804
///////////////////////////////////////////////////////////////////////////////////////////////////
805
/**
806
 * Makes a certain sub-region of the Object smoothly change its brightness level.
807
 *        
808
 * @param brightness 1-dimensional Data that returns the level of brightness we want to have
809
 *                   at any given moment. Valid range: <0,infinity)
810
 * @param region     Region this Effect is limited to.
811
 * @param smooth     If true, the level of 'brightness' will smoothly fade out towards the edges of the region.
812
 * @return           ID of the effect added, or -1 if we failed to add one.
813
 */
814
  public long brightness(Data1D brightness, Data4D region, boolean smooth)
815
    {
816
    return mF.add( smooth ? EffectNames.SMOOTH_BRIGHTNESS: EffectNames.BRIGHTNESS, brightness, region);
817
    }
818

    
819
///////////////////////////////////////////////////////////////////////////////////////////////////
820
/**
821
 * Makes the whole Object smoothly change its brightness level.
822
 *
823
 * @param brightness 1-dimensional Data that returns the level of brightness we want to have
824
 *                   at any given moment. Valid range: <0,infinity)
825
 * @return           ID of the effect added, or -1 if we failed to add one.
826
 */
827
  public long brightness(Data1D brightness)
828
    {
829
    return mF.add(EffectNames.BRIGHTNESS, brightness);
830
    }
831

    
832
///////////////////////////////////////////////////////////////////////////////////////////////////
833
/**
834
 * Makes a certain sub-region of the Object smoothly change its contrast level.
835
 *        
836
 * @param contrast 1-dimensional Data that returns the level of contrast we want to have
837
 *                 at any given moment. Valid range: <0,infinity)
838
 * @param region   Region this Effect is limited to.
839
 * @param smooth   If true, the level of 'contrast' will smoothly fade out towards the edges of the region.
840
 * @return         ID of the effect added, or -1 if we failed to add one.
841
 */
842
  public long contrast(Data1D contrast, Data4D region, boolean smooth)
843
    {
844
    return mF.add( smooth ? EffectNames.SMOOTH_CONTRAST:EffectNames.CONTRAST, contrast, region);
845
    }
846

    
847
///////////////////////////////////////////////////////////////////////////////////////////////////
848
/**
849
 * Makes the whole Object smoothly change its contrast level.
850
 *
851
 * @param contrast 1-dimensional Data that returns the level of contrast we want to have
852
 *                 at any given moment. Valid range: <0,infinity)
853
 * @return         ID of the effect added, or -1 if we failed to add one.
854
 */
855
  public long contrast(Data1D contrast)
856
    {
857
    return mF.add(EffectNames.CONTRAST, contrast);
858
    }
859

    
860
///////////////////////////////////////////////////////////////////////////////////////////////////
861
/**
862
 * Makes a certain sub-region of the Object smoothly change its saturation level.
863
 *        
864
 * @param saturation 1-dimensional Data that returns the level of saturation we want to have
865
 *                   at any given moment. Valid range: <0,infinity)
866
 * @param region     Region this Effect is limited to.
867
 * @param smooth     If true, the level of 'saturation' will smoothly fade out towards the edges of the region.
868
 * @return           ID of the effect added, or -1 if we failed to add one.
869
 */
870
  public long saturation(Data1D saturation, Data4D region, boolean smooth)
871
    {
872
    return mF.add( smooth ? EffectNames.SMOOTH_SATURATION:EffectNames.SATURATION, saturation, region);
873
    }
874

    
875
///////////////////////////////////////////////////////////////////////////////////////////////////
876
/**
877
 * Makes the whole Object smoothly change its saturation level.
878
 *
879
 * @param saturation 1-dimensional Data that returns the level of saturation we want to have
880
 *                   at any given moment. Valid range: <0,infinity)
881
 * @return           ID of the effect added, or -1 if we failed to add one.
882
 */
883
  public long saturation(Data1D saturation)
884
    {
885
    return mF.add(EffectNames.SATURATION, saturation);
886
    }
887

    
888
///////////////////////////////////////////////////////////////////////////////////////////////////
889
// Vertex-based effects  
890
///////////////////////////////////////////////////////////////////////////////////////////////////
891
/**
892
 * Distort a (possibly changing in time) part of the Object by a (possibly changing in time) vector of force.
893
 *
894
 * @param vector 3-dimensional Vector which represents the force the Center of the Effect is
895
 *               currently being dragged with.
896
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
897
 * @param region Region that masks the Effect.
898
 * @return       ID of the effect added, or -1 if we failed to add one.
899
 */
900
  public long distort(Data3D vector, Data3D center, Data4D region)
901
    {  
902
    return mV.add(EffectNames.DISTORT, vector, center, region);
903
    }
904

    
905
///////////////////////////////////////////////////////////////////////////////////////////////////
906
/**
907
 * Distort the whole Object by a (possibly changing in time) vector of force.
908
 *
909
 * @param vector 3-dimensional Vector which represents the force the Center of the Effect is
910
 *               currently being dragged with.
911
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
912
 * @return       ID of the effect added, or -1 if we failed to add one.
913
 */
914
  public long distort(Data3D vector, Data3D center)
915
    {
916
    return mV.add(EffectNames.DISTORT, vector, center, null);
917
    }
918

    
919
///////////////////////////////////////////////////////////////////////////////////////////////////
920
/**
921
 * Deform the shape of the whole Object with a (possibly changing in time) vector of force applied to
922
 * a (possibly changing in time) point on the Object.
923
 *
924
 * @param vector Vector of force that deforms the shape of the whole Object.
925
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
926
 * @param region Region that masks the Effect.
927
 * @return       ID of the effect added, or -1 if we failed to add one.
928
 */
929
  public long deform(Data3D vector, Data3D center, Data4D region)
930
    {
931
    return mV.add(EffectNames.DEFORM, vector, center, region);
932
    }
933

    
934
///////////////////////////////////////////////////////////////////////////////////////////////////
935
/**
936
 * Deform the shape of the whole Object with a (possibly changing in time) vector of force applied to
937
 * a (possibly changing in time) point on the Object.
938
 *     
939
 * @param vector Vector of force that deforms the shape of the whole Object.
940
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
941
 * @return       ID of the effect added, or -1 if we failed to add one.
942
 */
943
  public long deform(Data3D vector, Data3D center)
944
    {  
945
    return mV.add(EffectNames.DEFORM, vector, center, null);
946
    }
947

    
948
///////////////////////////////////////////////////////////////////////////////////////////////////  
949
/**
950
 * Pull all points around the center of the Effect towards the center (if degree>=1) or push them
951
 * away from the center (degree<=1)
952
 *
953
 * @param sink   The current degree of the Effect.
954
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
955
 * @param region Region that masks the Effect.
956
 * @return       ID of the effect added, or -1 if we failed to add one.
957
 */
958
  public long sink(Data1D sink, Data3D center, Data4D region)
959
    {
960
    return mV.add(EffectNames.SINK, sink, center, region);
961
    }
962

    
963
///////////////////////////////////////////////////////////////////////////////////////////////////
964
/**
965
 * Pull all points around the center of the Effect towards the center (if degree>=1) or push them
966
 * away from the center (degree<=1)
967
 *
968
 * @param sink   The current degree of the Effect.
969
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
970
 * @return       ID of the effect added, or -1 if we failed to add one.
971
 */
972
  public long sink(Data1D sink, Data3D center)
973
    {
974
    return mV.add(EffectNames.SINK, sink, center);
975
    }
976

    
977
///////////////////////////////////////////////////////////////////////////////////////////////////
978
/**
979
 * Pull all points around the center of the Effect towards a line passing through the center
980
 * (that's if degree>=1) or push them away from the line (degree<=1)
981
 *
982
 * @param pinch  The current degree of the Effect + angle the line forms with X-axis
983
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
984
 * @param region Region that masks the Effect.
985
 * @return       ID of the effect added, or -1 if we failed to add one.
986
 */
987
  public long pinch(Data2D pinch, Data3D center, Data4D region)
988
    {
989
    return mV.add(EffectNames.PINCH, pinch, center, region);
990
    }
991

    
992
///////////////////////////////////////////////////////////////////////////////////////////////////
993
/**
994
 * Pull all points around the center of the Effect towards a line passing through the center
995
 * (that's if degree>=1) or push them away from the line (degree<=1)
996
 *
997
 * @param pinch  The current degree of the Effect + angle the line forms with X-axis
998
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
999
 * @return       ID of the effect added, or -1 if we failed to add one.
1000
 */
1001
  public long pinch(Data2D pinch, Data3D center)
1002
    {
1003
    return mV.add(EffectNames.PINCH, pinch, center);
1004
    }
1005

    
1006
///////////////////////////////////////////////////////////////////////////////////////////////////  
1007
/**
1008
 * Rotate part of the Object around the Center of the Effect by a certain angle.
1009
 *
1010
 * @param swirl  The angle of Swirl (in degrees). Positive values swirl clockwise.
1011
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
1012
 * @param region Region that masks the Effect.
1013
 * @return       ID of the effect added, or -1 if we failed to add one.
1014
 */
1015
  public long swirl(Data1D swirl, Data3D center, Data4D region)
1016
    {    
1017
    return mV.add(EffectNames.SWIRL, swirl, center, region);
1018
    }
1019

    
1020
///////////////////////////////////////////////////////////////////////////////////////////////////
1021
/**
1022
 * Rotate the whole Object around the Center of the Effect by a certain angle.
1023
 *
1024
 * @param swirl  The angle of Swirl (in degrees). Positive values swirl clockwise.
1025
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
1026
 * @return       ID of the effect added, or -1 if we failed to add one.
1027
 */
1028
  public long swirl(Data1D swirl, Data3D center)
1029
    {
1030
    return mV.add(EffectNames.SWIRL, swirl, center);
1031
    }
1032

    
1033
///////////////////////////////////////////////////////////////////////////////////////////////////
1034
/**
1035
 * Directional, sinusoidal wave effect.
1036
 *
1037
 * @param wave   A 5-dimensional data structure describing the wave: first member is the amplitude,
1038
 *               second is the wave length, third is the phase (i.e. when phase = PI/2, the sine
1039
 *               wave at the center does not start from sin(0), but from sin(PI/2) ) and the next two
1040
 *               describe the 'direction' of the wave.
1041
 *               <p>
1042
 *               Wave direction is defined to be a 3D vector of length 1. To define such vectors, we
1043
 *               need 2 floats: thus the third member is the angle Alpha (in degrees) which the vector
1044
 *               forms with the XY-plane, and the fourth is the angle Beta (again in degrees) which
1045
 *               the projection of the vector to the XY-plane forms with the Y-axis (counterclockwise).
1046
 *               <p>
1047
 *               <p>
1048
 *               Example1: if Alpha = 90, Beta = 90, (then V=(0,0,1) ) and the wave acts 'vertically'
1049
 *               in the X-direction, i.e. cross-sections of the resulting surface with the XZ-plane
1050
 *               will be sine shapes.
1051
 *               <p>
1052
 *               Example2: if Alpha = 90, Beta = 0, the again V=(0,0,1) and the wave is 'vertical',
1053
 *               but this time it waves in the Y-direction, i.e. cross sections of the surface and the
1054
 *               YZ-plane with be sine shapes.
1055
 *               <p>
1056
 *               Example3: if Alpha = 0 and Beta = 45, then V=(sqrt(2)/2, -sqrt(2)/2, 0) and the wave
1057
 *               is entirely 'horizontal' and moves point (x,y,0) in direction V by whatever is the
1058
 *               value if sin at this point.
1059
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
1060
 * @return       ID of the effect added, or -1 if we failed to add one.
1061
 */
1062
  public long wave(Data5D wave, Data3D center)
1063
    {
1064
    return mV.add(EffectNames.WAVE, wave, center, null);
1065
    }
1066

    
1067
///////////////////////////////////////////////////////////////////////////////////////////////////
1068
/**
1069
 * Directional, sinusoidal wave effect.
1070
 *
1071
 * @param wave   see {@link DistortedEffects#wave(Data5D,Data3D)}
1072
 * @param center 3-dimensional Data that, at any given time, returns the Center of the Effect.
1073
 * @param region Region that masks the Effect.
1074
 * @return       ID of the effect added, or -1 if we failed to add one.
1075
 */
1076
  public long wave(Data5D wave, Data3D center, Data4D region)
1077
    {
1078
    return mV.add(EffectNames.WAVE, wave, center, region);
1079
    }
1080
  }
(2-2/24)