Project

General

Profile

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

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

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
  /// MAIN PROGRAM ///
55
  private static DistortedProgram mMainProgram;
56
  private static int mMainTextureH;
57
  private static boolean[] mEffectEnabled = new boolean[EffectNames.size()];
58

    
59
  static
60
    {
61
    int len = EffectNames.size();
62

    
63
    for(int i=0; i<len; i++)
64
      {
65
      mEffectEnabled[i] = false;
66
      }
67
    }
68

    
69
  /// BLIT PROGRAM ///
70
  private static DistortedProgram mBlitProgram;
71
  private static int mBlitTextureH;
72
  private static int mBlitDepthH;
73
  private static final FloatBuffer mQuadPositions;
74

    
75
  static
76
    {
77
    float[] positionData= { -0.5f, -0.5f,  -0.5f, 0.5f,  0.5f,-0.5f,  0.5f, 0.5f };
78
    mQuadPositions = ByteBuffer.allocateDirect(32).order(ByteOrder.nativeOrder()).asFloatBuffer();
79
    mQuadPositions.put(positionData).position(0);
80
    }
81

    
82
  /// DEBUG ONLY /////
83
  private static DistortedProgram mDebugProgram;
84

    
85
  private static int mDebugObjDH;
86
  private static int mDebugMVPMatrixH;
87
  /// END DEBUG //////
88

    
89
  private static float[] mMVPMatrix = new float[16];
90
  private static float[] mTmpMatrix = new float[16];
91

    
92
  private static long mNextID =0;
93
  private long mID;
94

    
95
  private EffectQueueMatrix      mM;
96
  private EffectQueueFragment    mF;
97
  private EffectQueueVertex      mV;
98

    
99
  private boolean matrixCloned, vertexCloned, fragmentCloned;
100

    
101
///////////////////////////////////////////////////////////////////////////////////////////////////
102

    
103
  static void createProgram(Resources resources)
104
  throws FragmentCompilationException,VertexCompilationException,VertexUniformsException,FragmentUniformsException,LinkingException
105
    {
106
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
107
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
108

    
109
    String mainVertHeader= Distorted.GLSL_VERSION;
110
    String mainFragHeader= Distorted.GLSL_VERSION;
111

    
112
    EffectNames name;
113
    EffectTypes type;
114
    boolean foundF = false;
115
    boolean foundV = false;
116

    
117
    for(int i=0; i<mEffectEnabled.length; i++)
118
      {
119
      if( mEffectEnabled[i] )
120
        {
121
        name = EffectNames.getName(i);
122
        type = EffectNames.getType(i);
123

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

    
137
    mainVertHeader += ("#define NUM_VERTEX "   + ( foundV ? getMaxVertex()   : 0 ) + "\n");
138
    mainFragHeader += ("#define NUM_FRAGMENT " + ( foundF ? getMaxFragment() : 0 ) + "\n");
139

    
140
    //android.util.Log.e("Effects", "vertHeader= "+mainVertHeader);
141
    //android.util.Log.e("Effects", "fragHeader= "+mainFragHeader);
142

    
143
    mMainProgram = new DistortedProgram(mainVertStream,mainFragStream, mainVertHeader, mainFragHeader, Distorted.GLSL);
144

    
145
    int mainProgramH = mMainProgram.getProgramHandle();
146
    EffectQueueFragment.getUniforms(mainProgramH);
147
    EffectQueueVertex.getUniforms(mainProgramH);
148
    EffectQueueMatrix.getUniforms(mainProgramH);
149
    mMainTextureH= GLES30.glGetUniformLocation( mainProgramH, "u_Texture");
150

    
151
    // BLIT PROGRAM ////////////////////////////////////
152
    final InputStream blitVertStream = resources.openRawResource(R.raw.blit_vertex_shader);
153
    final InputStream blitFragStream = resources.openRawResource(R.raw.blit_fragment_shader);
154

    
155
    String blitVertHeader= (Distorted.GLSL_VERSION + "#define NUM_VERTEX 0\n"  );
156
    String blitFragHeader= (Distorted.GLSL_VERSION + "#define NUM_FRAGMENT 0\n");
157

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

    
168
    int blitProgramH = mBlitProgram.getProgramHandle();
169
    mBlitTextureH  = GLES30.glGetUniformLocation( blitProgramH, "u_Texture");
170
    mBlitDepthH    = GLES30.glGetUniformLocation( blitProgramH, "u_Depth");
171

    
172
    // DEBUG ONLY //////////////////////////////////////
173
    final InputStream debugVertexStream   = resources.openRawResource(R.raw.test_vertex_shader);
174
    final InputStream debugFragmentStream = resources.openRawResource(R.raw.test_fragment_shader);
175

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

    
186
    int debugProgramH = mDebugProgram.getProgramHandle();
187
    mDebugObjDH = GLES30.glGetUniformLocation( debugProgramH, "u_objD");
188
    mDebugMVPMatrixH = GLES30.glGetUniformLocation( debugProgramH, "u_MVPMatrix");
189
    // END DEBUG  //////////////////////////////////////
190
    }
191

    
192
///////////////////////////////////////////////////////////////////////////////////////////////////
193

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

    
230
///////////////////////////////////////////////////////////////////////////////////////////////////
231
// DEBUG ONLY
232

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

    
243
    float x,y,z, X,Y,W, ndcX,ndcY;
244

    
245
    for(int i=0; i<len; i++)
246
      {
247
      x = 2*halfX*vertices[3*i  ];
248
      y = 2*halfY*vertices[3*i+1];
249
      z = 2*halfZ*vertices[3*i+2];
250

    
251
      X = mvp[ 0]*x + mvp[ 4]*y + mvp[ 8]*z + mvp[12];
252
      Y = mvp[ 1]*x + mvp[ 5]*y + mvp[ 9]*z + mvp[13];
253
      W = mvp[ 3]*x + mvp[ 7]*y + mvp[11]*z + mvp[15];
254

    
255
      ndcX = X/W;
256
      ndcY = Y/W;
257

    
258
      wx = (int)(surface.mWidth *(ndcX+1)/2);
259
      wy = (int)(surface.mHeight*(ndcY+1)/2);
260

    
261
      if( wx<minx ) minx = wx;
262
      if( wx>maxx ) maxx = wx;
263
      if( wy<miny ) miny = wy;
264
      if( wy>maxy ) maxy = wy;
265
      }
266

    
267
    mDebugProgram.useProgram();
268
    surface.setAsOutput(currTime);
269

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

    
276
    GLES30.glUniform2f(mDebugObjDH, 2*halfX, 2*halfY);
277
    GLES30.glUniformMatrix4fv(mDebugMVPMatrixH, 1, false, mMVPMatrix , 0);
278

    
279
    GLES30.glVertexAttribPointer(mDebugProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
280
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
281
    }
282

    
283
///////////////////////////////////////////////////////////////////////////////////////////////////
284

    
285
  void drawPriv(float halfW, float halfH, MeshObject mesh, DistortedOutputSurface surface, long currTime)
286
    {
287
    mM.compute(currTime);
288
    mV.compute(currTime);
289
    mF.compute(currTime);
290

    
291
    float halfZ = halfW*mesh.zFactor;
292

    
293
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
294

    
295
    mMainProgram.useProgram();
296
    GLES30.glUniform1i(mMainTextureH, 0);
297
    surface.setAsOutput(currTime);
298
    mM.send(surface,halfW,halfH,halfZ);
299
    mM.send(surface,halfW,halfH,halfZ);
300
    mV.send(halfW,halfH,halfZ);
301
    mF.send(halfW,halfH);
302

    
303
    GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, mesh.mAttVBO[0]);
304
    GLES30.glVertexAttribPointer(mMainProgram.mAttribute[0], MeshObject.POSITION_DATA_SIZE, GLES30.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET0);
305
    GLES30.glVertexAttribPointer(mMainProgram.mAttribute[1], MeshObject.NORMAL_DATA_SIZE  , GLES30.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET1);
306
    GLES30.glVertexAttribPointer(mMainProgram.mAttribute[2], MeshObject.TEX_DATA_SIZE     , GLES30.GL_FLOAT, false, MeshObject.VERTSIZE, MeshObject.OFFSET2);
307
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.numVertices);
308
    GLES30.glBindBuffer(GLES30.GL_ARRAY_BUFFER, 0 );
309

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

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

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

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

    
341
///////////////////////////////////////////////////////////////////////////////////////////////////
342

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

    
347
    int len = EffectNames.size();
348

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

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

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

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

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

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

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

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

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

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

    
476
    return 0;
477
    }
478

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

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

    
513
    return false;
514
    }
515

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

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

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

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

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

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

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

    
633
///////////////////////////////////////////////////////////////////////////////////////////////////   
634
///////////////////////////////////////////////////////////////////////////////////////////////////
635
// Individual effect functions.
636
///////////////////////////////////////////////////////////////////////////////////////////////////
637
// Matrix-based effects
638
///////////////////////////////////////////////////////////////////////////////////////////////////
639
/**
640
 * Moves the Object by a (possibly changing in time) vector.
641
 * 
642
 * @param vector 3-dimensional Data which at any given time will return a Static3D
643
 *               representing the current coordinates of the vector we want to move the Object with.
644
 * @return       ID of the effect added, or -1 if we failed to add one.
645
 */
646
  public long move(Data3D vector)
647
    {   
648
    return mM.add(EffectNames.MOVE,vector);
649
    }
650

    
651
///////////////////////////////////////////////////////////////////////////////////////////////////
652
/**
653
 * Scales the Object by (possibly changing in time) 3D scale factors.
654
 * 
655
 * @param scale 3-dimensional Data which at any given time returns a Static3D
656
 *              representing the current x- , y- and z- scale factors.
657
 * @return      ID of the effect added, or -1 if we failed to add one.
658
 */
659
  public long scale(Data3D scale)
660
    {   
661
    return mM.add(EffectNames.SCALE,scale);
662
    }
663

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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