Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedLibrary.java @ 78ff6ea9

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

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

    
120
  private static int mMaxTextureSize         = Integer.MAX_VALUE;
121
  private static int mMaxNumberOfVerUniforms = Integer.MAX_VALUE;
122
  private static int mMaxNumberOfFraUniforms = Integer.MAX_VALUE;
123

    
124
  //////////////////////////////////////////////////////////////////////////////////////////////
125
  /// MAIN PROGRAM ///
126
  private static DistortedProgram mMainProgram;
127
  private static int mMainTextureH;
128
  private static int mTransformFeedbackH;
129

    
130
  /// NORMAL PROGRAM /////
131
  private static DistortedProgram mNormalProgram;
132
  private static int mNormalProjectionH;
133

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

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

    
146
  /// FULL PROGRAM ///
147
  private static DistortedProgram mFullProgram;
148

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

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

    
163
  /// Program Handles ///
164
  private static int mMainProgramH, mFullProgramH, mMainOITProgramH;
165

    
166
  /// OIT SSBO BUFFER ///
167
  private static int[] mLinkedListSSBO = new int[1];
168
  private static int[] mAtomicCounter;
169
  private static int   mCurrBuffer;
170

    
171
  static
172
    {
173
    mLinkedListSSBO[0]= -1;
174
    mCurrBuffer       =  0;
175
    }
176

    
177
  ///////////////////////////////////////////////////////////////
178
  // meaning: allocate 1.0 screenful of places for transparent
179
  // fragments in the SSBO backing up the OIT render method.
180
  private static float mBufferSize=1.0f;
181

    
182
  /// OIT CLEAR PROGRAM ///
183
  private static DistortedProgram mOITClearProgram;
184
  private static int mOITClearDepthH;
185
  private static int mOITClearTexCorrH;
186
  private static int mOITClearSizeH;
187

    
188
  /// OIT BUILD PROGRAM ///
189
  private static DistortedProgram mOITBuildProgram;
190
  private static int mOITBuildTextureH;
191
  private static int mOITBuildDepthTextureH;
192
  private static int mOITBuildDepthH;
193
  private static int mOITBuildTexCorrH;
194
  private static int mOITBuildSizeH;
195
  private static int mOITBuildNumRecordsH;
196

    
197
  /// OIT COLLAPSE PROGRAM ///
198
  private static DistortedProgram mOITCollapseProgram;
199
  private static int mOITCollapseDepthTextureH;
200
  private static int mOITCollapseDepthH;
201
  private static int mOITCollapseTexCorrH;
202
  private static int mOITCollapseSizeH;
203

    
204
  /// OIT RENDER PROGRAM ///
205
  private static DistortedProgram mOITRenderProgram;
206
  private static int mOITRenderDepthH;
207
  private static int mOITRenderTexCorrH;
208
  private static int mOITRenderSizeH;
209

    
210
  /// END PROGRAMS //////
211

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

    
224
  private static ExceptionListener mListener;
225
  private static Resources mResources;
226

    
227
///////////////////////////////////////////////////////////////////////////////////////////////////
228
// private: hide this from Javadoc
229

    
230
  private DistortedLibrary()
231
    {
232

    
233
    }
234

    
235
///////////////////////////////////////////////////////////////////////////////////////////////////
236

    
237
  private static void createMainProgram()
238
    {
239
    // MAIN PROGRAM ////////////////////////////////////
240
    final InputStream mainVertStream = mResources.openRawResource(R.raw.main_vertex_shader);
241
    final InputStream mainFragStream = mResources.openRawResource(R.raw.main_fragment_shader);
242

    
243
    int numF = FragmentEffect.getNumEnabled();
244
    int numV = VertexEffect.getNumEnabled();
245

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

    
249
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
250

    
251
    String enabledEffectV= VertexEffect.getGLSL();
252
    String enabledEffectF= FragmentEffect.getGLSL();
253

    
254
    String[] feedback = { "v_Position", "v_endPosition" };
255

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

    
267
    mMainProgramH = mMainProgram.getProgramHandle();
268
    EffectQueue.getUniforms(mMainProgramH,0);
269
    MeshBase.getUniforms(mMainProgramH,0);
270
    mMainTextureH= GLES30.glGetUniformLocation( mMainProgramH, "u_Texture");
271
    mTransformFeedbackH= GLES30.glGetUniformLocation( mMainProgramH, "u_TransformFeedback");
272

    
273
    // BLIT PROGRAM ////////////////////////////////////
274
    final InputStream blitVertStream = mResources.openRawResource(R.raw.blit_vertex_shader);
275
    final InputStream blitFragStream = mResources.openRawResource(R.raw.blit_fragment_shader);
276

    
277
    try
278
      {
279
      mBlitProgram = new DistortedProgram(blitVertStream,blitFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
280
      }
281
    catch(Exception e)
282
      {
283
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT program: "+e.getMessage());
284
      throw new RuntimeException(e.getMessage());
285
      }
286

    
287
    int blitProgramH = mBlitProgram.getProgramHandle();
288
    mBlitTextureH  = GLES30.glGetUniformLocation( blitProgramH, "u_Texture");
289
    mBlitDepthH    = GLES30.glGetUniformLocation( blitProgramH, "u_Depth");
290

    
291
    // BLIT DEPTH PROGRAM ////////////////////////////////////
292
    final InputStream blitDepthVertStream = mResources.openRawResource(R.raw.blit_depth_vertex_shader);
293
    final InputStream blitDepthFragStream = mResources.openRawResource(R.raw.blit_depth_fragment_shader);
294

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

    
305
    int blitDepthProgramH   = mBlitDepthProgram.getProgramHandle();
306
    mBlitDepthTextureH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Texture");
307
    mBlitDepthDepthTextureH = GLES30.glGetUniformLocation( blitDepthProgramH, "u_DepthTexture");
308
    mBlitDepthDepthH        = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Depth");
309
    mBlitDepthTexCorrH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_TexCorr");
310
    }
311

    
312
///////////////////////////////////////////////////////////////////////////////////////////////////
313

    
314
  private static void createNormalProgram(Resources resources)
315
    {
316
    // NORMAL PROGRAM //////////////////////////////////////
317
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
318
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
319

    
320
    try
321
      {
322
      mNormalProgram = new DistortedProgram(normalVertexStream,normalFragmentStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
323
      }
324
    catch(Exception e)
325
      {
326
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile NORMAL program: "+e.getMessage());
327
      throw new RuntimeException(e.getMessage());
328
      }
329

    
330
    int normalProgramH = mNormalProgram.getProgramHandle();
331
    mNormalProjectionH = GLES30.glGetUniformLocation( normalProgramH, "u_Projection");
332
    }
333

    
334
///////////////////////////////////////////////////////////////////////////////////////////////////
335

    
336
  private static void createFullProgram(Resources resources)
337
    {
338
    final InputStream fullVertStream = resources.openRawResource(R.raw.main_vertex_shader);
339
    final InputStream fullFragStream = resources.openRawResource(R.raw.main_fragment_shader);
340

    
341
    int numV = VertexEffect.getAllEnabled();
342

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

    
346
    fullVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
347

    
348
    String enabledEffectV= VertexEffect.getAllGLSL();
349
    String enabledEffectF= "{}";
350

    
351
    fullVertHeader += "#define PREAPPLY\n";
352

    
353
    String[] feedback = { "v_Position", "v_endPosition" };
354

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

    
366
    mFullProgramH = mFullProgram.getProgramHandle();
367
    EffectQueue.getUniforms(mFullProgramH,3);
368
    MeshBase.getUniforms(mFullProgramH,3);
369
    }
370

    
371
///////////////////////////////////////////////////////////////////////////////////////////////////
372

    
373
  private static void createOITProgram(Resources resources)
374
    {
375
    // MAIN OIT PROGRAM ////////////////////////////////
376
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
377
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
378

    
379
    int numF = FragmentEffect.getNumEnabled();
380
    int numV = VertexEffect.getNumEnabled();
381

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

    
385
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
386

    
387
    String enabledEffectV= VertexEffect.getGLSL();
388
    String enabledEffectF= FragmentEffect.getGLSL();
389

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

    
401
    mMainOITProgramH = mMainOITProgram.getProgramHandle();
402
    EffectQueue.getUniforms(mMainOITProgramH,1);
403
    MeshBase.getUniforms(mMainOITProgramH,1);
404
    mMainOITTextureH    = GLES30.glGetUniformLocation( mMainOITProgramH, "u_Texture");
405
    mMainOITSizeH       = GLES30.glGetUniformLocation( mMainOITProgramH, "u_Size");
406
    mMainOITNumRecordsH = GLES30.glGetUniformLocation( mMainOITProgramH, "u_numRecords");
407

    
408
    // OIT CLEAR PROGRAM ////////////////////////////////////
409
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
410
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
411

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

    
422
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
423
    mOITClearDepthH        = GLES30.glGetUniformLocation( oitClearProgramH, "u_Depth");
424
    mOITClearTexCorrH      = GLES30.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
425
    mOITClearSizeH         = GLES30.glGetUniformLocation( oitClearProgramH, "u_Size");
426

    
427
    // OIT BUILD PROGRAM ////////////////////////////////////
428
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
429
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
430

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

    
441
    int oitBuildProgramH   = mOITBuildProgram.getProgramHandle();
442
    mOITBuildTextureH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Texture");
443
    mOITBuildDepthTextureH = GLES30.glGetUniformLocation( oitBuildProgramH, "u_DepthTexture");
444
    mOITBuildDepthH        = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Depth");
445
    mOITBuildTexCorrH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_TexCorr");
446
    mOITBuildSizeH         = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Size");
447
    mOITBuildNumRecordsH   = GLES30.glGetUniformLocation( oitBuildProgramH, "u_numRecords");
448

    
449
    // OIT COLLAPSE PROGRAM ///////////////////////////
450
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
451
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
452

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

    
463
    int oitCollapseProgramH   = mOITCollapseProgram.getProgramHandle();
464
    mOITCollapseDepthTextureH = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_DepthTexture");
465
    mOITCollapseDepthH        = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Depth");
466
    mOITCollapseTexCorrH      = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_TexCorr");
467
    mOITCollapseSizeH         = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Size");
468

    
469
    // OIT RENDER PROGRAM ///////////////////////////
470
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
471
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
472

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

    
483
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
484
    mOITRenderDepthH        = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Depth");
485
    mOITRenderTexCorrH      = GLES30.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
486
    mOITRenderSizeH         = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Size");
487
    }
488

    
489
///////////////////////////////////////////////////////////////////////////////////////////////////
490

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

    
506
    int num = mesh.getNumVertices();
507
    int tfo = mesh.getTFO();
508

    
509
    GLES30.glUniform1i(DistortedLibrary.mTransformFeedbackH, 1);
510
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
511
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
512
    InternalRenderState.switchOffDrawing();
513
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
514
    InternalRenderState.restoreDrawing();
515
    GLES30.glEndTransformFeedback();
516
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
517
    GLES30.glUniform1i(DistortedLibrary.mTransformFeedbackH, 0);
518

    
519
    mNormalProgram.useProgram();
520
    GLES30.glUniformMatrix4fv(mNormalProjectionH, 1, false, projection, 0);
521
    mesh.bindTransformAttribs(mNormalProgram);
522
    GLES30.glLineWidth(8.0f);
523
    GLES30.glDrawArrays(GLES30.GL_LINES, 0, 2*num);
524
    }
525

    
526
///////////////////////////////////////////////////////////////////////////////////////////////////
527
/**
528
 * Execute all VertexEffects and adjust all vertices
529
 *
530
 * @y.exclude
531
 */
532
  public static void adjustVertices(MeshBase mesh, EffectQueueVertex queue)
533
    {
534
    if( mFullProgram==null )
535
      {
536
      try
537
        {
538
        createFullProgram(mResources);
539
        }
540
      catch(Exception ex)
541
        {
542
        mListener.distortedException(ex);
543
        return;
544
        }
545
      }
546

    
547
    int num = mesh.getNumVertices();
548
    int tfo = mesh.getTFO();
549

    
550
    mFullProgram.useProgram();
551
    mesh.bindVertexAttribs(mFullProgram);
552
    queue.compute(1);
553
    queue.send(0.0f,mFullProgramH,3);
554
    mesh.send(mFullProgramH,3);
555

    
556
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
557
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
558
    InternalRenderState.switchOffDrawing();
559
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
560
    InternalRenderState.restoreDrawing();
561
    GLES30.glEndTransformFeedback();
562
    mesh.copyTransformToVertex();
563
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
564
    }
565

    
566
///////////////////////////////////////////////////////////////////////////////////////////////////
567

    
568
  static void drawPrivOIT(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
569
    {
570
    if( mMainOITProgram!=null )
571
      {
572
      EffectQueue[] queues = effects.getQueues();
573

    
574
      EffectQueue.compute(queues, currTime);
575
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
576

    
577
      mMainOITProgram.useProgram();
578
      GLES30.glUniform1i(mMainOITTextureH, 0);
579
      GLES30.glUniform2ui(mMainOITSizeH, surface.mWidth, surface.mHeight);
580
      GLES30.glUniform1ui(mMainOITNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
581
      mesh.bindVertexAttribs(mMainOITProgram);
582
      mesh.send(mMainOITProgramH,1);
583

    
584
      float inflate     = mesh.getInflate();
585
      float distance    = surface.mDistance;
586
      float mipmap      = surface.mMipmap;
587
      float[] projection= surface.mProjectionMatrix;
588

    
589
      EffectQueue.send(queues, mMainOITProgramH, distance, mipmap, projection, inflate, 1 );
590
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
591

    
592
      if( mesh.getShowNormals() )
593
        {
594
        mMainProgram.useProgram();
595
        mesh.send(mMainProgramH,0);
596
        EffectQueue.send(queues, mMainProgramH, distance, mipmap, projection, inflate, 0 );
597
        displayNormals(projection,mesh);
598
        }
599
      }
600
    }
601

    
602
///////////////////////////////////////////////////////////////////////////////////////////////////
603

    
604
  static void drawPriv(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
605
    {
606
    if( mMainProgram!=null )
607
      {
608
      EffectQueue[] queues = effects.getQueues();
609

    
610
      EffectQueue.compute(queues, currTime);
611
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
612

    
613
      mMainProgram.useProgram();
614
      GLES30.glUniform1i(DistortedLibrary.mMainTextureH, 0);
615
      mesh.bindVertexAttribs(DistortedLibrary.mMainProgram);
616
      mesh.send(mMainProgramH,0);
617

    
618
      float inflate     = mesh.getInflate();
619
      float distance    = surface.mDistance;
620
      float mipmap      = surface.mMipmap;
621
      float[] projection= surface.mProjectionMatrix;
622

    
623
      EffectQueue.send(queues, mMainProgramH, distance, mipmap, projection, inflate, 0 );
624
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
625

    
626
      if( mesh.getShowNormals() ) displayNormals(projection,mesh);
627
      }
628
    }
629

    
630
///////////////////////////////////////////////////////////////////////////////////////////////////
631

    
632
  static void blitPriv(InternalOutputSurface surface)
633
    {
634
    if( mBlitProgram!=null )
635
      {
636
      mBlitProgram.useProgram();
637

    
638
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
639
      GLES30.glUniform1i(mBlitTextureH, 0);
640
      GLES30.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
641
      GLES30.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
642
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
643
      }
644
    }
645

    
646
///////////////////////////////////////////////////////////////////////////////////////////////////
647

    
648
  static void blitDepthPriv(InternalOutputSurface surface, float corrW, float corrH)
649
    {
650
    if( mBlitDepthProgram!=null )
651
      {
652
      mBlitDepthProgram.useProgram();
653

    
654
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
655
      GLES30.glUniform1i(mBlitDepthTextureH, 0);
656
      GLES30.glUniform1i(mBlitDepthDepthTextureH, 1);
657
      GLES30.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
658
      GLES30.glUniform1f( mBlitDepthDepthH , 1.0f-surface.mNear);
659
      GLES30.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
660
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
661
      }
662
    }
663

    
664
///////////////////////////////////////////////////////////////////////////////////////////////////
665
// yes it is safe to be mixing 3.0 and 3.1 like that, senior members of the OpenGL discussions forum assert
666

    
667
  private static int printPreviousBuffer()
668
    {
669
    int counter = 0;
670

    
671
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
672
                                                                GLES30.GL_MAP_READ_BIT);
673
    if( atomicBuf!=null )
674
      {
675
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
676
      counter = atomicIntBuf.get(0);
677
      }
678
    else
679
      {
680
      Log.e("effects", "print: failed to map atomic buffer");
681
      }
682

    
683
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
684

    
685
    return counter;
686
    }
687

    
688
///////////////////////////////////////////////////////////////////////////////////////////////////
689

    
690
  private static void zeroBuffer()
691
    {
692
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
693
                                                                GLES30.GL_MAP_WRITE_BIT|GLES30.GL_MAP_INVALIDATE_BUFFER_BIT);
694
    if( atomicBuf!=null )
695
      {
696
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
697
      atomicIntBuf.put(0,0);
698
      }
699
    else
700
      {
701
      Log.e("effects", "zero: failed to map atomic buffer");
702
      }
703

    
704
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
705
    }
706

    
707
///////////////////////////////////////////////////////////////////////////////////////////////////
708
// reset atomic counter to 0
709

    
710
  static int zeroOutAtomic()
711
    {
712
    int counter = 0;
713

    
714
    if( mAtomicCounter==null )
715
      {
716
      mAtomicCounter = new int[mFBOQueueSize];
717

    
718
      GLES30.glGenBuffers(mFBOQueueSize,mAtomicCounter,0);
719

    
720
      for(int i=0; i<mFBOQueueSize; i++)
721
        {
722
        GLES30.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
723
        GLES30.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES30.GL_DYNAMIC_DRAW);
724
        zeroBuffer();
725
        }
726
      }
727

    
728
    // reading the value of the buffer on every frame would slow down rendering by
729
    // about 3%; doing it only once every 5 frames affects speed by less than 1%.
730
    if( mCurrBuffer==0 )
731
      {
732
      GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
733
      counter = printPreviousBuffer();
734
      }
735

    
736
    if( ++mCurrBuffer>=mFBOQueueSize ) mCurrBuffer = 0;
737

    
738
    GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
739
    zeroBuffer();
740

    
741
    return counter;
742
    }
743

    
744
///////////////////////////////////////////////////////////////////////////////////////////////////
745
// Pass1 of the OIT algorithm. Clear per-pixel head-pointers.
746

    
747
  static void oitClear(InternalOutputSurface surface, int counter)
748
    {
749
    if( mOITClearProgram==null )
750
      {
751
      if( mGLSL>=310 && !mOITCompilationAttempted )
752
        {
753
        mOITCompilationAttempted = true;
754

    
755
        try
756
          {
757
          createOITProgram(mResources);
758
          }
759
        catch(Exception ex)
760
          {
761
          mListener.distortedException(ex);
762
          return;
763
          }
764
        }
765
      else
766
        {
767
        return;
768
        }
769
      }
770

    
771
    if( mLinkedListSSBO[0]<0 )
772
      {
773
      GLES30.glGenBuffers(1,mLinkedListSSBO,0);
774

    
775
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
776
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
777
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
778
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
779

    
780
      GLES30.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
781
      }
782

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

    
787
    if( overflow>1.0f )
788
      {
789
      mBufferSize *= (int)(overflow+1.0f);
790
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
791
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
792
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
793
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
794
      }
795

    
796
    mOITClearProgram.useProgram();
797

    
798
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
799
    GLES30.glUniform2f(mOITClearTexCorrH, 1.0f, 1.0f );   // corrections do not really matter here - only present because of common vertex shader.
800
    GLES30.glUniform1f( mOITClearDepthH , 1.0f);          // likewise depth
801
    GLES30.glUniform2ui(mOITClearSizeH, surface.mWidth, surface.mHeight);
802
    GLES30.glVertexAttribPointer(mOITClearProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
803
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
804
    }
805

    
806
///////////////////////////////////////////////////////////////////////////////////////////////////
807
// Pass2 of the OIT algorithm - build per-pixel linked lists.
808

    
809
  static void oitBuild(InternalOutputSurface surface, float corrW, float corrH)
810
    {
811
    if( mOITBuildProgram!=null )
812
      {
813
      mOITBuildProgram.useProgram();
814

    
815
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
816
      GLES30.glUniform1i(mOITBuildTextureH, 0);
817
      GLES30.glUniform1i(mOITBuildDepthTextureH, 1);
818
      GLES30.glUniform2f(mOITBuildTexCorrH, corrW, corrH );
819
      GLES30.glUniform2ui(mOITBuildSizeH, surface.mWidth, surface.mHeight);
820
      GLES30.glUniform1ui(mOITBuildNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
821
      GLES30.glUniform1f(mOITBuildDepthH , 1.0f-surface.mNear);
822
      GLES30.glVertexAttribPointer(mOITBuildProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
823
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
824
      }
825
    }
826

    
827
///////////////////////////////////////////////////////////////////////////////////////////////////
828
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
829

    
830
  static void oitCollapse(InternalOutputSurface surface, float corrW, float corrH)
831
    {
832
    if( mOITCollapseProgram!=null )
833
      {
834
      mOITCollapseProgram.useProgram();
835

    
836
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
837
      GLES30.glUniform1i(mOITCollapseDepthTextureH, 1);
838
      GLES30.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
839
      GLES30.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
840
      GLES30.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
841
      GLES30.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
842
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
843
      }
844
    }
845

    
846
///////////////////////////////////////////////////////////////////////////////////////////////////
847
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
848

    
849
  static void oitRender(InternalOutputSurface surface, float corrW, float corrH)
850
    {
851
    if( mOITRenderProgram!=null )
852
      {
853
      mOITRenderProgram.useProgram();
854

    
855
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
856
      GLES30.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
857
      GLES30.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
858
      GLES30.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
859
      GLES30.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
860
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
861
      }
862
    }
863

    
864
///////////////////////////////////////////////////////////////////////////////////////////////////
865

    
866
  static void setSSBOSize(float size)
867
    {
868
    mBufferSize = size;
869
    }
870

    
871
///////////////////////////////////////////////////////////////////////////////////////////////////
872

    
873
  static int getQueueSize()
874
    {
875
    return mFBOQueueSize;
876
    }
877

    
878
///////////////////////////////////////////////////////////////////////////////////////////////////
879
// ARM Mali driver r12 has problems when we keep swapping many FBOs (fixed in r22)
880
// PowerVR GE8100 / GE8300 compiler fails to compile OIT programs.
881

    
882
  private static void detectBuggyDriversAndSetQueueSize(int queueSize)
883
    {
884
    String vendor  = GLES30.glGetString(GLES30.GL_VENDOR);
885
    String version = GLES30.glGetString(GLES30.GL_VERSION);
886
    String renderer= GLES30.glGetString(GLES30.GL_RENDERER);
887

    
888
    mFBOQueueSize = 1;
889

    
890
    if( vendor.contains("ARM") )
891
      {
892
      try
893
        {
894
        String regex = ".*r(\\d+)p\\d.*";
895
        Pattern pattern = Pattern.compile(regex);
896
        Matcher matcher = pattern.matcher(version);
897

    
898
        if( matcher.find() )
899
          {
900
          String driverVersion = matcher.group(1);
901

    
902
          if( driverVersion!=null )
903
            {
904
            int drvVersion = Integer.parseInt(driverVersion);
905

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

    
911
              mFBOQueueSize = queueSize;
912
              }
913
            }
914
          }
915
        }
916
      catch(Exception ex)
917
        {
918
        android.util.Log.e("library", "exception trying to pattern match version: "+ex.toString());
919
        }
920
      }
921
    else if( vendor.contains("Imagination") )
922
      {
923
      if( renderer.contains("GE8") )
924
        {
925
        Log.e("DISTORTED", "You are running this on a PowerVR GE8XXX.\nDue to a buggy compiler OIT rendering will not work");
926
        Log.e("DISTORTED", "GLSL Version "+GLES30.glGetString(GLES31.GL_SHADING_LANGUAGE_VERSION));
927
        }
928
      }
929
    }
930

    
931
///////////////////////////////////////////////////////////////////////////////////////////////////
932
/**
933
 * Return OpenGL ES version supported by the hardware we are running on.
934
 * There are only three possibilities: 300 (OpenGL ES 3.0) or 310 (at least OpenGL ES 3.1)
935
 * or 200 (OpenGL ES 2.0)
936
 */
937
  public static int getGLSL()
938
    {
939
    return mGLSL;
940
    }
941

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

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

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

    
977
    mListener = listener;
978

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

    
990
    int[] tmp = new int[1];
991
    GLES30.glGetIntegerv(GLES30.GL_MAX_TEXTURE_SIZE, tmp, 0);
992
    mMaxTextureSize = tmp[0];
993
    GLES30.glGetIntegerv(GLES30.GL_MAX_VERTEX_UNIFORM_VECTORS  , tmp, 0);
994
    mMaxNumberOfVerUniforms = tmp[0];
995
    GLES30.glGetIntegerv(GLES30.GL_MAX_FRAGMENT_UNIFORM_VECTORS, tmp, 0);
996
    mMaxNumberOfFraUniforms = tmp[0];
997

    
998
    android.util.Log.e("DISTORTED", "Using OpenGL ES "+major+"."+minor);
999
    android.util.Log.e("DISTORTED", "max texture size: "+mMaxTextureSize);
1000
    android.util.Log.e("DISTORTED", "max num vert: "+mMaxNumberOfVerUniforms);
1001
    android.util.Log.e("DISTORTED", "max num frag: "+mMaxNumberOfFraUniforms);
1002

    
1003
    mGLSL_VERSION = "#version "+mGLSL+" es\n";
1004

    
1005
    InternalStackFrameList.setInitialized(true);
1006
    mOITCompilationAttempted = false;
1007

    
1008
    detectBuggyDriversAndSetQueueSize(queueSize);
1009
    EffectMessageSender.startSending();
1010

    
1011
    mResources = context.getResources();
1012

    
1013
    try
1014
      {
1015
      createMainProgram();
1016
      }
1017
    catch(Exception ex)
1018
      {
1019
      mListener.distortedException(ex);
1020
      }
1021

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

    
1031
    try
1032
      {
1033
      PostprocessEffect.createPrograms(mGLSL);
1034
      }
1035
    catch(Exception ex)
1036
      {
1037
      mListener.distortedException(ex);
1038
      }
1039
    }
1040

    
1041
///////////////////////////////////////////////////////////////////////////////////////////////////
1042
/**
1043
 * Call this so that the Library can initialize its internal data structures.
1044
 * Must be called from Activity.onCreate().
1045
 */
1046
  public static void onCreate()
1047
    {
1048
    onCreate(0);
1049
    }
1050

    
1051
///////////////////////////////////////////////////////////////////////////////////////////////////
1052
/**
1053
 * Call this so that the Library can initialize its internal data structures.
1054
 * Must be called from Activity.onCreate().
1055
 *
1056
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1057
 *           tell between Activities in case you're going to be using it from more than one.
1058
 */
1059
  public static void onCreate(long id)
1060
    {
1061
    InternalStackFrameList.onCreate(id);
1062
    }
1063

    
1064
///////////////////////////////////////////////////////////////////////////////////////////////////
1065
/**
1066
 * Call this so that the Library can resume its operations.
1067
 * Must be called from Activity.onResume().
1068
 */
1069
  public static void onResume()
1070
    {
1071
    onCreate(0);
1072
    }
1073

    
1074
///////////////////////////////////////////////////////////////////////////////////////////////////
1075
/**
1076
 * Call this so that the Library can resume its operations.
1077
 * Must be called from Activity.onResume().
1078
 *
1079
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1080
 *           tell between Activities in case you're going to be using it from more than one.
1081
 */
1082
  public static void onResume(long id)
1083
    {
1084
    InternalStackFrameList.onResume(id);
1085
    }
1086

    
1087
///////////////////////////////////////////////////////////////////////////////////////////////////
1088
/**
1089
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
1090
 * Must be called from Activity.onPause().
1091
 */
1092
  public static void onPause()
1093
    {
1094
    onPause(0);
1095
    }
1096

    
1097
///////////////////////////////////////////////////////////////////////////////////////////////////
1098
/**
1099
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
1100
 * Must be called from Activity.onPause().
1101
 *
1102
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1103
 *           tell between Activities in case you're going to be using it from more than one.
1104
 */
1105
  public static void onPause(long id)
1106
    {
1107
    InternalStackFrameList.onPause(id);
1108
    Dynamic.onPause();  // common for all frames
1109

    
1110
    mLinkedListSSBO[0]= -1;
1111
    mAtomicCounter = null;
1112

    
1113
    mNormalProgram     = null;
1114
    mMainOITProgram    = null;
1115
    mMainProgram       = null;
1116
    mFullProgram       = null;
1117
    mOITClearProgram   = null;
1118
    mOITBuildProgram   = null;
1119
    mOITCollapseProgram= null;
1120
    mOITRenderProgram  = null;
1121
    mBlitDepthProgram  = null;
1122
    mBlitProgram       = null;
1123
    }
1124

    
1125
///////////////////////////////////////////////////////////////////////////////////////////////////
1126
/**
1127
 * Call this so that the Library can release its internal data structures.
1128
 * Must be called from Activity.onDestroy().
1129
 */
1130
  public static void onDestroy()
1131
    {
1132
    onDestroy(0);
1133
    }
1134

    
1135
///////////////////////////////////////////////////////////////////////////////////////////////////
1136
/**
1137
 * Call this so that the Library can release its internal data structures.
1138
 * Must be called from Activity.onDestroy().
1139
 *
1140
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1141
 *           tell between Activities in case you're going to be using it from more than one.
1142
 */
1143
  public static void onDestroy(long id)
1144
    {
1145
    if( InternalStackFrameList.isInitialized() )
1146
      {
1147
      InternalStackFrameList.onDestroy(id);
1148

    
1149
      InternalOutputSurface.onDestroy(); // those three really destroy
1150
      Effect.onDestroy();                // static data that does not
1151
      DeferredJobs.onDestroy();          // need to be part of a frame
1152

    
1153
      mOITCompilationAttempted = false;
1154
      }
1155
    }
1156

    
1157
///////////////////////////////////////////////////////////////////////////////////////////////////
1158
/**
1159
 * Return the maximum size of the texture supported by the driver.
1160
 */
1161
  public static int getMaxTextureSize()
1162
    {
1163
    return mMaxTextureSize;
1164
    }
1165

    
1166
///////////////////////////////////////////////////////////////////////////////////////////////////
1167
/**
1168
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
1169
 * single (InputSurface,MeshBase) combo.
1170
 *
1171
 * @param type {@link EffectType}
1172
 * @return The maximum number of effects of a given type.
1173
 */
1174
  @SuppressWarnings("unused")
1175
  public static int getMax(EffectType type)
1176
    {
1177
    return EffectQueue.getMax(type.ordinal());
1178
    }
1179

    
1180
///////////////////////////////////////////////////////////////////////////////////////////////////
1181
/**
1182
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
1183
 * This can fail if:
1184
 * <ul>
1185
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
1186
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
1187
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link DistortedLibrary#onSurfaceCreated}. After this
1188
 *     time only decreasing the value of 'max' is permitted.
1189
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
1190
 * </ul>
1191
 *
1192
 * @param type {@link EffectType}
1193
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
1194
 *            than Byte.MAX_VALUE
1195
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
1196
 */
1197
  @SuppressWarnings("unused")
1198
  public static boolean setMax(EffectType type, int max)
1199
    {
1200
    return EffectQueue.setMax(type.ordinal(),max);
1201
    }
1202
  }
(3-3/16)