Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedLibrary.java @ 62c869ad

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

    
22
import android.app.ActivityManager;
23
import android.content.Context;
24
import android.content.pm.ConfigurationInfo;
25
import android.content.res.Resources;
26
import android.opengl.GLES30;
27
import android.opengl.GLES31;
28
import android.util.Log;
29

    
30
import org.distorted.library.R;
31
import org.distorted.library.effect.Effect;
32
import org.distorted.library.effectqueue.EffectQueue;
33
import org.distorted.library.effectqueue.EffectQueuePostprocess;
34
import org.distorted.library.effect.EffectType;
35
import org.distorted.library.effect.FragmentEffect;
36
import org.distorted.library.effect.PostprocessEffect;
37
import org.distorted.library.effect.VertexEffect;
38
import org.distorted.library.effectqueue.EffectQueueVertex;
39
import org.distorted.library.mesh.DeferredJobs;
40
import org.distorted.library.mesh.MeshBase;
41
import org.distorted.library.message.EffectMessageSender;
42
import org.distorted.library.program.DistortedProgram;
43
import org.distorted.library.program.VertexCompilationException;
44
import org.distorted.library.type.Dynamic;
45

    
46
import java.io.InputStream;
47
import java.nio.ByteBuffer;
48
import java.nio.ByteOrder;
49
import java.nio.FloatBuffer;
50
import java.nio.IntBuffer;
51
import java.util.regex.Matcher;
52
import java.util.regex.Pattern;
53

    
54
///////////////////////////////////////////////////////////////////////////////////////////////////
55
/**
56
 * A singleton class used to control various global dialog_settings.
57
 */
58
public class DistortedLibrary
59
  {
60
  private static int mGLSL;
61
  private static String mGLSL_VERSION;
62
  private static boolean mOITCompilationAttempted;
63
  /**
64
   * When creating an instance of a DistortedTexture from another instance, clone the Bitmap that's
65
   * backing up our DistortedTexture.
66
   * <p>
67
   * This way we can have two DistortedTextures, both backed up by the same Bitmap, to which we can
68
   * apply different effects. Used in the copy constructor.
69
   */
70
  public static final int CLONE_SURFACE = 0x1;
71
  /**
72
   * When creating an instance of a DistortedEffects from another instance, clone the Matrix Effects.
73
   * <p>
74
   * This way we can have two different DistortedEffects sharing the MATRIX queue.
75
   */
76
  public static final int CLONE_MATRIX = 0x2;
77
  /**
78
   * When creating an instance of a DistortedEffects from another instance, clone the Vertex Effects.
79
   * <p>
80
   * This way we can have two different DistortedEffects sharing the VERTEX queue.
81
   */
82
  public static final int CLONE_VERTEX  = 0x4;
83
  /**
84
   * When creating an instance of a DistortedEffects from another instance, clone the Fragment Effects.
85
   * <p>
86
   * This way we can have two different DistortedEffects sharing the FRAGMENT queue.
87
   */
88
  public static final int CLONE_FRAGMENT= 0x8;
89
   /**
90
   * When creating an instance of a DistortedEffects from another instance, clone the PostProcess Effects.
91
   * <p>
92
   * This way we can have two different DistortedEffects sharing the POSTPROCESS queue.
93
   */
94
  public static final int CLONE_POSTPROCESS= 0x10;
95
  /**
96
   * When creating an instance of a DistortedNode from another instance, clone the children Nodes.
97
   * <p>
98
   * This is mainly useful for creating many similar sub-trees and rendering then at different places
99
   * on the screen with (optionally) different Effects.
100
   */
101
  public static final int CLONE_CHILDREN= 0x20;
102

    
103
  /**
104
   * When creating a DistortedScreen (which needs to have mFBOQueueSize FBOs attached), pass this
105
   * constant for 'numOfFBOs' and the number of backing FBOs will be taken from 'mFBOQueueSize'
106
   * (the value of which is most likely unknown at the time of creation of the Screen)
107
   */
108
  public static final int WAIT_FOR_FBO_QUEUE_SIZE = -1;
109
  /**
110
   * Work around bugs in ARM Mali driver by, instead to a single FBO, rendering to a circular queue
111
   * of mFBOQueueSize FBOs. (otherwise we sometimes get a 'full pipeline flush' and the end result
112
   * might be missing part of the Objects)
113
   *
114
   * This bug only exists on Mali driver r12. (or more precisely it's there in r12 but fixed in r22)
115
   *
116
   * https://community.arm.com/graphics/f/discussions/10285/opengl-es-3-1-on-mali-t880-flashes
117
   */
118
  private static int mFBOQueueSize;
119

    
120
  private static boolean mInitialized=false;
121

    
122
  //////////////////////////////////////////////////////////////////////////////////////////////
123
  /// MAIN PROGRAM ///
124
  private static DistortedProgram mMainProgram;
125
  private static int mMainTextureH;
126
  private static int mTransformFeedbackH;
127

    
128
  /// NORMAL PROGRAM /////
129
  private static DistortedProgram mNormalProgram;
130
  private static int mNormalProjectionH;
131

    
132
  /// MAIN OIT PROGRAM ///
133
  private static DistortedProgram mMainOITProgram;
134
  private static int mMainOITTextureH;
135
  private static int mMainOITSizeH;
136
  private static int mMainOITNumRecordsH;
137

    
138
  /// BLIT PROGRAM ///
139
  private static DistortedProgram mBlitProgram;
140
  private static int mBlitTextureH;
141
  private static int mBlitDepthH;
142
  private static final FloatBuffer mQuadPositions;
143

    
144
  /// FULL PROGRAM ///
145
  private static DistortedProgram mFullProgram;
146

    
147
  static
148
    {
149
    float[] positionData= { -0.5f, -0.5f,  -0.5f, 0.5f,  0.5f,-0.5f,  0.5f, 0.5f };
150
    mQuadPositions = ByteBuffer.allocateDirect(32).order(ByteOrder.nativeOrder()).asFloatBuffer();
151
    mQuadPositions.put(positionData).position(0);
152
    }
153

    
154
  /// BLIT DEPTH PROGRAM ///
155
  private static DistortedProgram mBlitDepthProgram;
156
  private static int mBlitDepthTextureH;
157
  private static int mBlitDepthDepthTextureH;
158
  private static int mBlitDepthDepthH;
159
  private static int mBlitDepthTexCorrH;
160

    
161
  /// OIT SSBO BUFFER ///
162
  private static int[] mLinkedListSSBO = new int[1];
163
  private static int[] mAtomicCounter;
164
  private static int   mCurrBuffer;
165

    
166
  static
167
    {
168
    mLinkedListSSBO[0]= -1;
169
    mCurrBuffer       =  0;
170
    }
171

    
172
  ///////////////////////////////////////////////////////////////
173
  // meaning: allocate 1.0 screenful of places for transparent
174
  // fragments in the SSBO backing up the OIT render method.
175
  private static float mBufferSize=1.0f;
176

    
177
  /// OIT CLEAR PROGRAM ///
178
  private static DistortedProgram mOITClearProgram;
179
  private static int mOITClearDepthH;
180
  private static int mOITClearTexCorrH;
181
  private static int mOITClearSizeH;
182

    
183
  /// OIT BUILD PROGRAM ///
184
  private static DistortedProgram mOITBuildProgram;
185
  private static int mOITBuildTextureH;
186
  private static int mOITBuildDepthTextureH;
187
  private static int mOITBuildDepthH;
188
  private static int mOITBuildTexCorrH;
189
  private static int mOITBuildSizeH;
190
  private static int mOITBuildNumRecordsH;
191

    
192
  /// OIT COLLAPSE PROGRAM ///
193
  private static DistortedProgram mOITCollapseProgram;
194
  private static int mOITCollapseDepthTextureH;
195
  private static int mOITCollapseDepthH;
196
  private static int mOITCollapseTexCorrH;
197
  private static int mOITCollapseSizeH;
198

    
199
  /// OIT RENDER PROGRAM ///
200
  private static DistortedProgram mOITRenderProgram;
201
  private static int mOITRenderDepthH;
202
  private static int mOITRenderTexCorrH;
203
  private static int mOITRenderSizeH;
204

    
205
  /// END PROGRAMS //////
206

    
207
  /**
208
   * Every application using the library must implement this interface so that the library can send
209
   * it exceptions that arise. The exceptions may come at any time, for example the library will
210
   * compile its OIT problem only on the first attempt to use the OIT
211
   * Those will mainly be hardware-related: shaders do not compile on particular hardware, the required
212
   * OpenGL ES 3.0 is not supported, etc.
213
   */
214
  public interface ExceptionListener
215
    {
216
    void distortedException(Exception ex);
217
    }
218

    
219
  private static ExceptionListener mListener;
220
  private static Resources mResources;
221

    
222
///////////////////////////////////////////////////////////////////////////////////////////////////
223
// private: hide this from Javadoc
224

    
225
  private DistortedLibrary()
226
    {
227

    
228
    }
229

    
230
///////////////////////////////////////////////////////////////////////////////////////////////////
231

    
232
  private static void createMainProgram()
233
    {
234
    // MAIN PROGRAM ////////////////////////////////////
235
    final InputStream mainVertStream = mResources.openRawResource(R.raw.main_vertex_shader);
236
    final InputStream mainFragStream = mResources.openRawResource(R.raw.main_fragment_shader);
237

    
238
    int numF = FragmentEffect.getNumEnabled();
239
    int numV = VertexEffect.getNumEnabled();
240

    
241
    String mainVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n");
242
    String mainFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n");
243

    
244
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
245

    
246
    String enabledEffectV= VertexEffect.getGLSL();
247
    String enabledEffectF= FragmentEffect.getGLSL();
248

    
249
    String[] feedback = { "v_Position", "v_endPosition" };
250

    
251
    try
252
      {
253
      mMainProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
254
                                          enabledEffectV, enabledEffectF, mGLSL, feedback);
255
      }
256
    catch(Exception e)
257
      {
258
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN program: "+e.getMessage());
259
      throw new RuntimeException(e.getMessage());
260
      }
261

    
262
    int mainProgramH = mMainProgram.getProgramHandle();
263
    EffectQueue.getUniforms(mainProgramH,0);
264
    MeshBase.getUniforms(mainProgramH,0);
265
    mMainTextureH= GLES30.glGetUniformLocation( mainProgramH, "u_Texture");
266
    mTransformFeedbackH= GLES30.glGetUniformLocation( mainProgramH, "u_TransformFeedback");
267

    
268
    // BLIT PROGRAM ////////////////////////////////////
269
    final InputStream blitVertStream = mResources.openRawResource(R.raw.blit_vertex_shader);
270
    final InputStream blitFragStream = mResources.openRawResource(R.raw.blit_fragment_shader);
271

    
272
    try
273
      {
274
      mBlitProgram = new DistortedProgram(blitVertStream,blitFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
275
      }
276
    catch(Exception e)
277
      {
278
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT program: "+e.getMessage());
279
      throw new RuntimeException(e.getMessage());
280
      }
281

    
282
    int blitProgramH = mBlitProgram.getProgramHandle();
283
    mBlitTextureH  = GLES30.glGetUniformLocation( blitProgramH, "u_Texture");
284
    mBlitDepthH    = GLES30.glGetUniformLocation( blitProgramH, "u_Depth");
285

    
286
    // BLIT DEPTH PROGRAM ////////////////////////////////////
287
    final InputStream blitDepthVertStream = mResources.openRawResource(R.raw.blit_depth_vertex_shader);
288
    final InputStream blitDepthFragStream = mResources.openRawResource(R.raw.blit_depth_fragment_shader);
289

    
290
    try
291
      {
292
      mBlitDepthProgram = new DistortedProgram(blitDepthVertStream,blitDepthFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
293
      }
294
    catch(Exception e)
295
      {
296
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT DEPTH program: "+e.getMessage());
297
      throw new RuntimeException(e.getMessage());
298
      }
299

    
300
    int blitDepthProgramH   = mBlitDepthProgram.getProgramHandle();
301
    mBlitDepthTextureH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Texture");
302
    mBlitDepthDepthTextureH = GLES30.glGetUniformLocation( blitDepthProgramH, "u_DepthTexture");
303
    mBlitDepthDepthH        = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Depth");
304
    mBlitDepthTexCorrH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_TexCorr");
305
    }
306

    
307
///////////////////////////////////////////////////////////////////////////////////////////////////
308

    
309
  private static void createNormalProgram(Resources resources)
310
    {
311
    // NORMAL PROGRAM //////////////////////////////////////
312
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
313
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
314

    
315
    try
316
      {
317
      mNormalProgram = new DistortedProgram(normalVertexStream,normalFragmentStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
318
      }
319
    catch(Exception e)
320
      {
321
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile NORMAL program: "+e.getMessage());
322
      throw new RuntimeException(e.getMessage());
323
      }
324

    
325
    int normalProgramH = mNormalProgram.getProgramHandle();
326
    mNormalProjectionH = GLES30.glGetUniformLocation( normalProgramH, "u_Projection");
327
    }
328

    
329
///////////////////////////////////////////////////////////////////////////////////////////////////
330

    
331
  private static void createFullProgram(Resources resources)
332
    {
333
    final InputStream fullVertStream = resources.openRawResource(R.raw.main_vertex_shader);
334
    final InputStream fullFragStream = resources.openRawResource(R.raw.main_fragment_shader);
335

    
336
    int numV = VertexEffect.getAllEnabled();
337

    
338
    String fullVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX ) : 0 ) + "\n");
339
    String fullFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " +                                         0   + "\n");
340

    
341
    fullVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
342

    
343
    String enabledEffectV= VertexEffect.getAllGLSL();
344
    String enabledEffectF= "{}";
345

    
346
    fullVertHeader += "#define PREAPPLY\n";
347

    
348
    String[] feedback = { "v_Position", "v_endPosition", "v_Inflate" };
349

    
350
    try
351
      {
352
      mFullProgram = new DistortedProgram(fullVertStream, fullFragStream, fullVertHeader, fullFragHeader,
353
                                          enabledEffectV, enabledEffectF, mGLSL, feedback);
354
      }
355
    catch(Exception e)
356
      {
357
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile FULL program: "+e.getMessage());
358
      throw new RuntimeException(e.getMessage());
359
      }
360

    
361
    int fullProgramH = mFullProgram.getProgramHandle();
362
    EffectQueue.getUniforms(fullProgramH,3);
363
    MeshBase.getUniforms(fullProgramH,3);
364
    }
365

    
366
///////////////////////////////////////////////////////////////////////////////////////////////////
367

    
368
  private static void createOITProgram(Resources resources)
369
    {
370
    // MAIN OIT PROGRAM ////////////////////////////////
371
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
372
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
373

    
374
    int numF = FragmentEffect.getNumEnabled();
375
    int numV = VertexEffect.getNumEnabled();
376

    
377
    String mainVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n") + ("#define OIT\n");
378
    String mainFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n") + ("#define OIT\n");
379

    
380
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
381

    
382
    String enabledEffectV= VertexEffect.getGLSL();
383
    String enabledEffectF= FragmentEffect.getGLSL();
384

    
385
    try
386
      {
387
      mMainOITProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
388
                                             enabledEffectV, enabledEffectF, mGLSL, null);
389
      }
390
    catch(Exception e)
391
      {
392
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN OIT program: "+e.getMessage());
393
      throw new RuntimeException(e.getMessage());
394
      }
395

    
396
    int mainOITProgramH = mMainOITProgram.getProgramHandle();
397
    EffectQueue.getUniforms(mainOITProgramH,1);
398
    MeshBase.getUniforms(mainOITProgramH,1);
399
    mMainOITTextureH    = GLES30.glGetUniformLocation( mainOITProgramH, "u_Texture");
400
    mMainOITSizeH       = GLES30.glGetUniformLocation( mainOITProgramH, "u_Size");
401
    mMainOITNumRecordsH = GLES30.glGetUniformLocation( mainOITProgramH, "u_numRecords");
402

    
403
    // OIT CLEAR PROGRAM ////////////////////////////////////
404
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
405
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
406

    
407
    try
408
      {
409
      mOITClearProgram = new DistortedProgram(oitClearVertStream,oitClearFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
410
      }
411
    catch(Exception e)
412
      {
413
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT CLEAR program: "+e.getMessage());
414
      throw new RuntimeException(e.getMessage());
415
      }
416

    
417
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
418
    mOITClearDepthH        = GLES30.glGetUniformLocation( oitClearProgramH, "u_Depth");
419
    mOITClearTexCorrH      = GLES30.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
420
    mOITClearSizeH         = GLES30.glGetUniformLocation( oitClearProgramH, "u_Size");
421

    
422
    // OIT BUILD PROGRAM ////////////////////////////////////
423
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
424
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
425

    
426
    try
427
      {
428
      mOITBuildProgram = new DistortedProgram(oitBuildVertStream,oitBuildFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
429
      }
430
    catch(Exception e)
431
      {
432
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT BUILD program: "+e.getMessage());
433
      throw new RuntimeException(e.getMessage());
434
      }
435

    
436
    int oitBuildProgramH   = mOITBuildProgram.getProgramHandle();
437
    mOITBuildTextureH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Texture");
438
    mOITBuildDepthTextureH = GLES30.glGetUniformLocation( oitBuildProgramH, "u_DepthTexture");
439
    mOITBuildDepthH        = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Depth");
440
    mOITBuildTexCorrH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_TexCorr");
441
    mOITBuildSizeH         = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Size");
442
    mOITBuildNumRecordsH   = GLES30.glGetUniformLocation( oitBuildProgramH, "u_numRecords");
443

    
444
    // OIT COLLAPSE PROGRAM ///////////////////////////
445
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
446
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
447

    
448
    try
449
      {
450
      mOITCollapseProgram = new DistortedProgram(oitCollapseVertStream,oitCollapseFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
451
      }
452
    catch(Exception e)
453
      {
454
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT COLLAPSE program: "+e.getMessage());
455
      throw new RuntimeException(e.getMessage());
456
      }
457

    
458
    int oitCollapseProgramH   = mOITCollapseProgram.getProgramHandle();
459
    mOITCollapseDepthTextureH = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_DepthTexture");
460
    mOITCollapseDepthH        = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Depth");
461
    mOITCollapseTexCorrH      = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_TexCorr");
462
    mOITCollapseSizeH         = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Size");
463

    
464
    // OIT RENDER PROGRAM ///////////////////////////
465
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
466
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
467

    
468
    try
469
      {
470
      mOITRenderProgram = new DistortedProgram(oitRenderVertStream,oitRenderFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
471
      }
472
    catch(Exception e)
473
      {
474
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT RENDER program: "+e.getMessage());
475
      throw new RuntimeException(e.getMessage());
476
      }
477

    
478
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
479
    mOITRenderDepthH        = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Depth");
480
    mOITRenderTexCorrH      = GLES30.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
481
    mOITRenderSizeH         = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Size");
482
    }
483

    
484
///////////////////////////////////////////////////////////////////////////////////////////////////
485

    
486
  private static void displayNormals(float[] projection, MeshBase mesh)
487
    {
488
    if( mNormalProgram==null )
489
      {
490
      try
491
        {
492
        createNormalProgram(mResources);
493
        }
494
      catch(Exception ex)
495
        {
496
        mListener.distortedException(ex);
497
        return;
498
        }
499
      }
500

    
501
    int num = mesh.getNumVertices();
502
    int tfo = mesh.getTFO();
503

    
504
    GLES30.glUniform1i(DistortedLibrary.mTransformFeedbackH, 1);
505
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
506
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
507
    InternalRenderState.switchOffDrawing();
508
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
509
    InternalRenderState.restoreDrawing();
510
    GLES30.glEndTransformFeedback();
511
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
512

    
513
    mNormalProgram.useProgram();
514
    GLES30.glUniformMatrix4fv(mNormalProjectionH, 1, false, projection, 0);
515
    mesh.bindTransformAttribs(mNormalProgram);
516
    GLES30.glLineWidth(8.0f);
517
    GLES30.glDrawArrays(GLES30.GL_LINES, 0, 2*num);
518
    }
519

    
520
///////////////////////////////////////////////////////////////////////////////////////////////////
521
// execute all VertexEffects and adjust all vertices
522

    
523
  public static void adjustVertices(MeshBase mesh, EffectQueueVertex queue)
524
    {
525
    if( mFullProgram==null )
526
      {
527
      try
528
        {
529
        createFullProgram(mResources);
530
        }
531
      catch(Exception ex)
532
        {
533
        mListener.distortedException(ex);
534
        return;
535
        }
536
      }
537

    
538
    int num = mesh.getNumVertices();
539
    int tfo = mesh.getTFO();
540

    
541
    mFullProgram.useProgram();
542
    mesh.bindVertexAttribs(mFullProgram);
543
    queue.compute(1);
544
    queue.send(0.0f,3);
545
    mesh.send(3);
546

    
547
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
548
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
549
    InternalRenderState.switchOffDrawing();
550
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
551
    InternalRenderState.restoreDrawing();
552
    GLES30.glEndTransformFeedback();
553
    mesh.copyTransformToVertex();
554
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
555
    }
556

    
557
///////////////////////////////////////////////////////////////////////////////////////////////////
558

    
559
  static void drawPrivOIT(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
560
    {
561
    if( mMainOITProgram!=null )
562
      {
563
      EffectQueue[] queues = effects.getQueues();
564

    
565
      EffectQueue.compute(queues, currTime);
566
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
567

    
568
      mMainOITProgram.useProgram();
569
      GLES30.glUniform1i(mMainOITTextureH, 0);
570
      GLES30.glUniform2ui(mMainOITSizeH, surface.mWidth, surface.mHeight);
571
      GLES30.glUniform1ui(mMainOITNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
572
      mesh.bindVertexAttribs(mMainOITProgram);
573
      mesh.send(1);
574

    
575
      float inflate     = mesh.getInflate();
576
      float distance    = surface.mDistance;
577
      float mipmap      = surface.mMipmap;
578
      float[] projection= surface.mProjectionMatrix;
579

    
580
      EffectQueue.send(queues, distance, mipmap, projection, inflate, 1 );
581
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
582

    
583
      if( mesh.getShowNormals() )
584
        {
585
        mMainProgram.useProgram();
586
        mesh.send(0);
587
        EffectQueue.send(queues, distance, mipmap, projection, inflate, 0 );
588
        displayNormals(projection,mesh);
589
        }
590
      }
591
    }
592

    
593
///////////////////////////////////////////////////////////////////////////////////////////////////
594

    
595
  static void drawPriv(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
596
    {
597
    if( mMainProgram!=null )
598
      {
599
      EffectQueue[] queues = effects.getQueues();
600

    
601
      EffectQueue.compute(queues, currTime);
602
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
603

    
604
      mMainProgram.useProgram();
605
      GLES30.glUniform1i(DistortedLibrary.mMainTextureH, 0);
606
      mesh.bindVertexAttribs(DistortedLibrary.mMainProgram);
607
      mesh.send(0);
608

    
609
      float inflate     = mesh.getInflate();
610
      float distance    = surface.mDistance;
611
      float mipmap      = surface.mMipmap;
612
      float[] projection= surface.mProjectionMatrix;
613

    
614
      EffectQueue.send(queues, distance, mipmap, projection, inflate, 0 );
615
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
616

    
617
      if( mesh.getShowNormals() ) displayNormals(projection,mesh);
618
      }
619
    }
620

    
621
///////////////////////////////////////////////////////////////////////////////////////////////////
622

    
623
  static void blitPriv(InternalOutputSurface surface)
624
    {
625
    if( mBlitProgram!=null )
626
      {
627
      mBlitProgram.useProgram();
628

    
629
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
630
      GLES30.glUniform1i(mBlitTextureH, 0);
631
      GLES30.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
632
      GLES30.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
633
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
634
      }
635
    }
636

    
637
///////////////////////////////////////////////////////////////////////////////////////////////////
638

    
639
  static void blitDepthPriv(InternalOutputSurface surface, float corrW, float corrH)
640
    {
641
    if( mBlitDepthProgram!=null )
642
      {
643
      mBlitDepthProgram.useProgram();
644

    
645
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
646
      GLES30.glUniform1i(mBlitDepthTextureH, 0);
647
      GLES30.glUniform1i(mBlitDepthDepthTextureH, 1);
648
      GLES30.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
649
      GLES30.glUniform1f( mBlitDepthDepthH , 1.0f-surface.mNear);
650
      GLES30.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
651
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
652
      }
653
    }
654

    
655
///////////////////////////////////////////////////////////////////////////////////////////////////
656
// yes it is safe to be mixing 3.0 and 3.1 like that, senior members of the OpenGL discussions forum assert
657

    
658
  private static int printPreviousBuffer()
659
    {
660
    int counter = 0;
661

    
662
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
663
                                                                GLES30.GL_MAP_READ_BIT);
664
    if( atomicBuf!=null )
665
      {
666
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
667
      counter = atomicIntBuf.get(0);
668
      }
669
    else
670
      {
671
      Log.e("effects", "print: failed to map atomic buffer");
672
      }
673

    
674
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
675

    
676
    return counter;
677
    }
678

    
679
///////////////////////////////////////////////////////////////////////////////////////////////////
680

    
681
  private static void zeroBuffer()
682
    {
683
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
684
                                                                GLES30.GL_MAP_WRITE_BIT|GLES30.GL_MAP_INVALIDATE_BUFFER_BIT);
685
    if( atomicBuf!=null )
686
      {
687
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
688
      atomicIntBuf.put(0,0);
689
      }
690
    else
691
      {
692
      Log.e("effects", "zero: failed to map atomic buffer");
693
      }
694

    
695
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
696
    }
697

    
698
///////////////////////////////////////////////////////////////////////////////////////////////////
699
// reset atomic counter to 0
700

    
701
  static int zeroOutAtomic()
702
    {
703
    int counter = 0;
704

    
705
    if( mAtomicCounter==null )
706
      {
707
      mAtomicCounter = new int[mFBOQueueSize];
708

    
709
      GLES30.glGenBuffers(mFBOQueueSize,mAtomicCounter,0);
710

    
711
      for(int i=0; i<mFBOQueueSize; i++)
712
        {
713
        GLES30.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
714
        GLES30.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES30.GL_DYNAMIC_DRAW);
715
        zeroBuffer();
716
        }
717
      }
718

    
719
    // reading the value of the buffer on every frame would slow down rendering by
720
    // about 3%; doing it only once every 5 frames affects speed by less than 1%.
721
    if( mCurrBuffer==0 )
722
      {
723
      GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
724
      counter = printPreviousBuffer();
725
      }
726

    
727
    if( ++mCurrBuffer>=mFBOQueueSize ) mCurrBuffer = 0;
728

    
729
    GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
730
    zeroBuffer();
731

    
732
    return counter;
733
    }
734

    
735
///////////////////////////////////////////////////////////////////////////////////////////////////
736
// Pass1 of the OIT algorithm. Clear per-pixel head-pointers.
737

    
738
  static void oitClear(InternalOutputSurface surface, int counter)
739
    {
740
    if( mOITClearProgram==null )
741
      {
742
      if( mGLSL>=310 && !mOITCompilationAttempted )
743
        {
744
        mOITCompilationAttempted = true;
745

    
746
        try
747
          {
748
          createOITProgram(mResources);
749
          }
750
        catch(Exception ex)
751
          {
752
          mListener.distortedException(ex);
753
          return;
754
          }
755
        }
756
      else
757
        {
758
        return;
759
        }
760
      }
761

    
762
    if( mLinkedListSSBO[0]<0 )
763
      {
764
      GLES30.glGenBuffers(1,mLinkedListSSBO,0);
765

    
766
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
767
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
768
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
769
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
770

    
771
      GLES30.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
772
      }
773

    
774
    // See if we have overflown the SSBO in one of the previous frames.
775
    // If yes, assume we need to make the SSBO larger.
776
    float overflow = counter/(mBufferSize*surface.mWidth*surface.mHeight);
777

    
778
    if( overflow>1.0f )
779
      {
780
      mBufferSize *= (int)(overflow+1.0f);
781
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
782
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
783
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
784
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
785
      }
786

    
787
    mOITClearProgram.useProgram();
788

    
789
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
790
    GLES30.glUniform2f(mOITClearTexCorrH, 1.0f, 1.0f );   // corrections do not really matter here - only present because of common vertex shader.
791
    GLES30.glUniform1f( mOITClearDepthH , 1.0f);          // likewise depth
792
    GLES30.glUniform2ui(mOITClearSizeH, surface.mWidth, surface.mHeight);
793
    GLES30.glVertexAttribPointer(mOITClearProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
794
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
795
    }
796

    
797
///////////////////////////////////////////////////////////////////////////////////////////////////
798
// Pass2 of the OIT algorithm - build per-pixel linked lists.
799

    
800
  static void oitBuild(InternalOutputSurface surface, float corrW, float corrH)
801
    {
802
    if( mOITBuildProgram!=null )
803
      {
804
      mOITBuildProgram.useProgram();
805

    
806
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
807
      GLES30.glUniform1i(mOITBuildTextureH, 0);
808
      GLES30.glUniform1i(mOITBuildDepthTextureH, 1);
809
      GLES30.glUniform2f(mOITBuildTexCorrH, corrW, corrH );
810
      GLES30.glUniform2ui(mOITBuildSizeH, surface.mWidth, surface.mHeight);
811
      GLES30.glUniform1ui(mOITBuildNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
812
      GLES30.glUniform1f(mOITBuildDepthH , 1.0f-surface.mNear);
813
      GLES30.glVertexAttribPointer(mOITBuildProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
814
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
815
      }
816
    }
817

    
818
///////////////////////////////////////////////////////////////////////////////////////////////////
819
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
820

    
821
  static void oitCollapse(InternalOutputSurface surface, float corrW, float corrH)
822
    {
823
    if( mOITCollapseProgram!=null )
824
      {
825
      mOITCollapseProgram.useProgram();
826

    
827
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
828
      GLES30.glUniform1i(mOITCollapseDepthTextureH, 1);
829
      GLES30.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
830
      GLES30.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
831
      GLES30.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
832
      GLES30.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
833
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
834
      }
835
    }
836

    
837
///////////////////////////////////////////////////////////////////////////////////////////////////
838
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
839

    
840
  static void oitRender(InternalOutputSurface surface, float corrW, float corrH)
841
    {
842
    if( mOITRenderProgram!=null )
843
      {
844
      mOITRenderProgram.useProgram();
845

    
846
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
847
      GLES30.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
848
      GLES30.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
849
      GLES30.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
850
      GLES30.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
851
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
852
      }
853
    }
854

    
855
///////////////////////////////////////////////////////////////////////////////////////////////////
856

    
857
  static void setSSBOSize(float size)
858
    {
859
    mBufferSize = size;
860
    }
861

    
862
///////////////////////////////////////////////////////////////////////////////////////////////////
863

    
864
  static int getQueueSize()
865
    {
866
    return mFBOQueueSize;
867
    }
868

    
869
///////////////////////////////////////////////////////////////////////////////////////////////////
870
// ARM Mali driver r12 has problems when we keep swapping many FBOs (fixed in r22)
871
// PowerVR GE8100 / GE8300 compiler fails to compile OIT programs.
872

    
873
  private static void detectBuggyDriversAndSetQueueSize(int queueSize)
874
    {
875
    String vendor  = GLES30.glGetString(GLES30.GL_VENDOR);
876
    String version = GLES30.glGetString(GLES30.GL_VERSION);
877
    String renderer= GLES30.glGetString(GLES30.GL_RENDERER);
878

    
879
    mFBOQueueSize = 1;
880

    
881
    if( vendor.contains("ARM") )
882
      {
883
      try
884
        {
885
        String regex = ".*r(\\d+)p\\d.*";
886
        Pattern pattern = Pattern.compile(regex);
887
        Matcher matcher = pattern.matcher(version);
888

    
889
        if( matcher.find() )
890
          {
891
          String driverVersion = matcher.group(1);
892

    
893
          if( driverVersion!=null )
894
            {
895
            int drvVersion = Integer.parseInt(driverVersion);
896

    
897
            if( drvVersion<22 )
898
              {
899
              Log.e("DISTORTED", "You are running this on a ARM Mali driver r"+driverVersion+".\n" +
900
                    "This is a buggy driver, please update to r22. Inserting workaround which uses a lot of memory.");
901

    
902
              mFBOQueueSize = queueSize;
903
              }
904
            }
905
          }
906
        }
907
      catch(Exception ex)
908
        {
909
        android.util.Log.e("library", "exception trying to pattern match version: "+ex.toString());
910
        }
911
      }
912
    else if( vendor.contains("Imagination") )
913
      {
914
      if( renderer.contains("GE8") )
915
        {
916
        Log.e("DISTORTED", "You are running this on a PowerVR GE8XXX.\nDue to a buggy compiler OIT rendering will not work");
917
        Log.e("DISTORTED", "GLSL Version "+GLES30.glGetString(GLES31.GL_SHADING_LANGUAGE_VERSION));
918
        }
919
      }
920
    }
921

    
922
///////////////////////////////////////////////////////////////////////////////////////////////////
923
/**
924
 * Return OpenGL ES version supported by the hardware we are running on.
925
 * There are only three possibilities: 300 (OpenGL ES 3.0) or 310 (at least OpenGL ES 3.1)
926
 * or 200 (OpenGL ES 2.0)
927
 */
928
  public static int getGLSL()
929
    {
930
    return mGLSL;
931
    }
932

    
933
///////////////////////////////////////////////////////////////////////////////////////////////////
934
/**
935
 * Have we called onCreate yet, ie have we initialized the library?
936
 * @return <code>true</code> if the library is initialized and ready for action.
937
 */
938
  public static boolean isInitialized()
939
    {
940
    return mInitialized;
941
    }
942

    
943
///////////////////////////////////////////////////////////////////////////////////////////////////
944
/**
945
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
946
 * I.e. best called from GLSurfaceView.onCreate().
947
 * <p>
948
 * Needs to be called from a thread holding the OpenGL context.
949
 *
950
 * @param context Context of the App using the library - used to open up Resources and read Shader code.
951
 * @param listener The library will send all (asynchronous!) exceptions there.
952
 */
953
  public static void onCreate(final Context context, final ExceptionListener listener)
954
    {
955
    onCreate(context,listener,4);
956
    }
957

    
958
///////////////////////////////////////////////////////////////////////////////////////////////////
959
/**
960
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
961
 * I.e. best called from GLSurfaceView.onCreate().
962
 * <p>
963
 * Needs to be called from a thread holding the OpenGL context.
964
 *   
965
 * @param context Context of the App using the library - used to open up Resources and read Shader code.
966
 * @param listener The library will send all (asynchronous!) exceptions there.
967
 * @param queueSize the size of the FBO queue, a workaround for the bug on Mali drivers.
968
 */
969
  public static void onCreate(final Context context, final ExceptionListener listener, int queueSize)
970
    {
971
    final ActivityManager activityManager     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
972
    final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
973

    
974
    int glESversion = configurationInfo.reqGlEsVersion;
975
    int major = glESversion >> 16;
976
    int minor = glESversion & 0xff;
977

    
978
    mListener = listener;
979

    
980
    if( major< 3 )
981
      {
982
      mGLSL = 100*major + 10*minor;
983
      VertexCompilationException ex = new VertexCompilationException("at least OpenGL ES 3.0 required, this device supports only "+major+"."+minor);
984
      mListener.distortedException(ex);
985
      }
986
    else
987
      {
988
      mGLSL = (major==3 && minor==0) ? 300 : 310;
989
      }
990

    
991
    android.util.Log.e("DISTORTED", "Using OpenGL ES "+major+"."+minor);
992
    mGLSL_VERSION = "#version "+mGLSL+" es\n";
993

    
994
    mInitialized = true;
995
    mOITCompilationAttempted = false;
996

    
997
    detectBuggyDriversAndSetQueueSize(queueSize);
998

    
999
    EffectMessageSender.startSending();
1000

    
1001
    mResources = context.getResources();
1002

    
1003
    try
1004
      {
1005
      createMainProgram();
1006
      }
1007
    catch(Exception ex)
1008
      {
1009
      mListener.distortedException(ex);
1010
      }
1011

    
1012
    try
1013
      {
1014
      EffectQueuePostprocess.createPrograms(mResources, mGLSL);
1015
      }
1016
    catch(Exception ex)
1017
      {
1018
      mListener.distortedException(ex);
1019
      }
1020

    
1021
    try
1022
      {
1023
      PostprocessEffect.createPrograms(mGLSL);
1024
      }
1025
    catch(Exception ex)
1026
      {
1027
      mListener.distortedException(ex);
1028
      }
1029
    }
1030

    
1031
///////////////////////////////////////////////////////////////////////////////////////////////////
1032
/**
1033
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
1034
 * Must be called from Activity.onPause().
1035
 */
1036
  public static void onPause()
1037
    {
1038
    InternalObject.onPause();
1039
    Dynamic.onPause();
1040
    mLinkedListSSBO[0]= -1;
1041
    mAtomicCounter = null;
1042

    
1043
    mFullProgram        = null;
1044
    mNormalProgram      = null;
1045
    mOITRenderProgram   = null;
1046
    mOITCollapseProgram = null;
1047
    mOITBuildProgram    = null;
1048
    mOITClearProgram    = null;
1049
    }
1050

    
1051
///////////////////////////////////////////////////////////////////////////////////////////////////
1052
/**
1053
 * Call this so that the Library can release its internal data structures.
1054
 * Must be called from Activity.onDestroy(). 
1055
 */
1056
  public static void onDestroy()
1057
    {
1058
    InternalObject.onDestroy();
1059
    InternalNodeData.onDestroy();
1060
    InternalMaster.onDestroy();
1061
    InternalOutputSurface.onDestroy();
1062
    DistortedEffects.onDestroy();
1063
    EffectQueue.onDestroy();
1064
    Effect.onDestroy();
1065
    DeferredJobs.onDestroy();
1066
    EffectMessageSender.stopSending();
1067

    
1068
    mInitialized = false;
1069
    mOITCompilationAttempted = false;
1070

    
1071
    mNormalProgram     = null;
1072
    mMainOITProgram    = null;
1073
    mMainProgram       = null;
1074
    mFullProgram       = null;
1075
    mOITClearProgram   = null;
1076
    mOITBuildProgram   = null;
1077
    mOITCollapseProgram= null;
1078
    mOITRenderProgram  = null;
1079
    mBlitDepthProgram  = null;
1080
    mBlitProgram       = null;
1081
    }
1082

    
1083
///////////////////////////////////////////////////////////////////////////////////////////////////
1084
/**
1085
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
1086
 * single (InputSurface,MeshBase) combo.
1087
 *
1088
 * @param type {@link EffectType}
1089
 * @return The maximum number of effects of a given type.
1090
 */
1091
  @SuppressWarnings("unused")
1092
  public static int getMax(EffectType type)
1093
    {
1094
    return EffectQueue.getMax(type.ordinal());
1095
    }
1096

    
1097
///////////////////////////////////////////////////////////////////////////////////////////////////
1098
/**
1099
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
1100
 * This can fail if:
1101
 * <ul>
1102
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
1103
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
1104
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link DistortedLibrary#onCreate}. After this
1105
 *     time only decreasing the value of 'max' is permitted.
1106
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
1107
 * </ul>
1108
 *
1109
 * @param type {@link EffectType}
1110
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
1111
 *            than Byte.MAX_VALUE
1112
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
1113
 */
1114
  @SuppressWarnings("unused")
1115
  public static boolean setMax(EffectType type, int max)
1116
    {
1117
    return EffectQueue.setMax(type.ordinal(),max);
1118
    }
1119
  }
(3-3/14)