Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedLibrary.java @ 97460908

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, mNeedsTransformFeedback;
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
  private static boolean mBuggyUBOs;
125
  private static String mVendor, mVersion, mRenderer;
126

    
127
  //////////////////////////////////////////////////////////////////////////////////////////////
128
  /// MAIN PROGRAM ///
129
  private static DistortedProgram mMainProgram;
130
  private static int mMainTextureH;
131
  private static int mTransformFeedbackH;
132

    
133
  /// NORMAL PROGRAM /////
134
  private static DistortedProgram mNormalProgram;
135
  private static int mNormalProjectionH;
136

    
137
  /// MAIN OIT PROGRAM ///
138
  private static DistortedProgram mMainOITProgram;
139
  private static int mMainOITTextureH;
140
  private static int mMainOITSizeH;
141
  private static int mMainOITNumRecordsH;
142

    
143
  /// BLIT PROGRAM ///
144
  private static DistortedProgram mBlitProgram;
145
  private static int mBlitTextureH;
146
  private static int mBlitDepthH;
147
  private static final FloatBuffer mQuadPositions;
148

    
149
  /// FULL PROGRAM ///
150
  private static DistortedProgram mFullProgram;
151

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

    
159
  /// BLIT DEPTH PROGRAM ///
160
  private static DistortedProgram mBlitDepthProgram;
161
  private static int mBlitDepthTextureH;
162
  private static int mBlitDepthDepthTextureH;
163
  private static int mBlitDepthTexCorrH;
164

    
165
  /// Program Handles ///
166
  private static int mMainProgramH, mFullProgramH, mMainOITProgramH;
167

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

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

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

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

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

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

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

    
212
  /// END PROGRAMS //////
213

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

    
226
  private static ExceptionListener mListener;
227
  private static Resources mResources;
228

    
229
///////////////////////////////////////////////////////////////////////////////////////////////////
230
// private: hide this from Javadoc
231

    
232
  private DistortedLibrary()
233
    {
234

    
235
    }
236

    
237
///////////////////////////////////////////////////////////////////////////////////////////////////
238

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

    
245
    int numF = FragmentEffect.getNumEnabled();
246
    int numV = VertexEffect.getNumEnabled();
247

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

    
251
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
252
    if( MeshBase.getUseCenters() ) mainVertHeader += "#define COMP_CENTERS\n";
253
    if( mBuggyUBOs )               mainVertHeader += "#define BUGGY_UBOS\n";
254

    
255
    String enabledEffectV= VertexEffect.getGLSL();
256
    String enabledEffectF= FragmentEffect.getGLSL();
257

    
258
    String[] feedback = { "v_Position", "v_endPosition" };
259

    
260
    try
261
      {
262
      mMainProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader,
263
                                          mainFragHeader, enabledEffectV, enabledEffectF,
264
                                          mGLSL, mNeedsTransformFeedback ? feedback : null );
265
      }
266
    catch(Exception e)
267
      {
268
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN program: "+e.getMessage());
269
      throw new RuntimeException(e.getMessage());
270
      }
271

    
272
    mMainProgramH = mMainProgram.getProgramHandle();
273
    EffectQueue.getUniforms(mMainProgramH,0);
274
    MeshBase.getUniforms(mMainProgramH,0);
275
    mMainTextureH= GLES30.glGetUniformLocation( mMainProgramH, "u_Texture");
276
    mTransformFeedbackH= GLES30.glGetUniformLocation( mMainProgramH, "u_TransformFeedback");
277

    
278
    // BLIT PROGRAM ////////////////////////////////////
279
    final InputStream blitVertStream = mResources.openRawResource(R.raw.blit_vertex_shader);
280
    final InputStream blitFragStream = mResources.openRawResource(R.raw.blit_fragment_shader);
281

    
282
    try
283
      {
284
      mBlitProgram = new DistortedProgram(blitVertStream,blitFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
285
      }
286
    catch(Exception e)
287
      {
288
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT program: "+e.getMessage());
289
      throw new RuntimeException(e.getMessage());
290
      }
291

    
292
    int blitProgramH = mBlitProgram.getProgramHandle();
293
    mBlitTextureH  = GLES30.glGetUniformLocation( blitProgramH, "u_Texture");
294
    mBlitDepthH    = GLES30.glGetUniformLocation( blitProgramH, "u_Depth");
295

    
296
    // BLIT DEPTH PROGRAM ////////////////////////////////////
297
    final InputStream blitDepthVertStream = mResources.openRawResource(R.raw.blit_depth_vertex_shader);
298
    final InputStream blitDepthFragStream = mResources.openRawResource(R.raw.blit_depth_fragment_shader);
299

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

    
310
    int blitDepthProgramH   = mBlitDepthProgram.getProgramHandle();
311
    mBlitDepthTextureH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Texture");
312
    mBlitDepthDepthTextureH = GLES30.glGetUniformLocation( blitDepthProgramH, "u_DepthTexture");
313
    mBlitDepthTexCorrH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_TexCorr");
314
    }
315

    
316
///////////////////////////////////////////////////////////////////////////////////////////////////
317

    
318
  private static void createNormalProgram(Resources resources)
319
    {
320
    // NORMAL PROGRAM //////////////////////////////////////
321
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
322
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
323

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

    
334
    int normalProgramH = mNormalProgram.getProgramHandle();
335
    mNormalProjectionH = GLES30.glGetUniformLocation( normalProgramH, "u_Projection");
336
    }
337

    
338
///////////////////////////////////////////////////////////////////////////////////////////////////
339

    
340
  private static void createFullProgram(Resources resources)
341
    {
342
    final InputStream fullVertStream = resources.openRawResource(R.raw.main_vertex_shader);
343
    final InputStream fullFragStream = resources.openRawResource(R.raw.main_fragment_shader);
344

    
345
    int numV = VertexEffect.getAllEnabled();
346

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

    
350
    fullVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
351
    if( MeshBase.getUseCenters() ) fullVertHeader += "#define COMP_CENTERS\n";
352
    if( mBuggyUBOs )               fullVertHeader += "#define BUGGY_UBOS\n";
353

    
354
    String enabledEffectV= VertexEffect.getAllGLSL();
355
    String enabledEffectF= "{}";
356

    
357
    fullVertHeader += "#define PREAPPLY\n";
358

    
359
    String[] feedback = { "v_Position", "v_endPosition" };
360

    
361
    try
362
      {
363
      mFullProgram = new DistortedProgram(fullVertStream, fullFragStream, fullVertHeader, fullFragHeader,
364
                                          enabledEffectV, enabledEffectF, mGLSL, feedback);
365
      }
366
    catch(Exception e)
367
      {
368
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile FULL program: "+e.getMessage());
369
      throw new RuntimeException(e.getMessage());
370
      }
371

    
372
    mFullProgramH = mFullProgram.getProgramHandle();
373
    EffectQueue.getUniforms(mFullProgramH,3);
374
    MeshBase.getUniforms(mFullProgramH,3);
375
    }
376

    
377
///////////////////////////////////////////////////////////////////////////////////////////////////
378

    
379
  private static void createOITProgram(Resources resources)
380
    {
381
    // MAIN OIT PROGRAM ////////////////////////////////
382
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
383
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
384

    
385
    int numF = FragmentEffect.getNumEnabled();
386
    int numV = VertexEffect.getNumEnabled();
387

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

    
391
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
392
    if( MeshBase.getUseCenters() ) mainVertHeader += "#define COMP_CENTERS\n";
393
    if( mBuggyUBOs )               mainVertHeader += "#define BUGGY_UBOS\n";
394

    
395
    String enabledEffectV= VertexEffect.getGLSL();
396
    String enabledEffectF= FragmentEffect.getGLSL();
397

    
398
    try
399
      {
400
      mMainOITProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
401
                                             enabledEffectV, enabledEffectF, mGLSL, null);
402
      }
403
    catch(Exception e)
404
      {
405
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN OIT program: "+e.getMessage());
406
      throw new RuntimeException(e.getMessage());
407
      }
408

    
409
    mMainOITProgramH = mMainOITProgram.getProgramHandle();
410
    EffectQueue.getUniforms(mMainOITProgramH,1);
411
    MeshBase.getUniforms(mMainOITProgramH,1);
412
    mMainOITTextureH    = GLES30.glGetUniformLocation( mMainOITProgramH, "u_Texture");
413
    mMainOITSizeH       = GLES30.glGetUniformLocation( mMainOITProgramH, "u_Size");
414
    mMainOITNumRecordsH = GLES30.glGetUniformLocation( mMainOITProgramH, "u_numRecords");
415

    
416
    // OIT CLEAR PROGRAM ////////////////////////////////////
417
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
418
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
419

    
420
    try
421
      {
422
      mOITClearProgram = new DistortedProgram(oitClearVertStream,oitClearFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
423
      }
424
    catch(Exception e)
425
      {
426
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT CLEAR program: "+e.getMessage());
427
      throw new RuntimeException(e.getMessage());
428
      }
429

    
430
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
431
    mOITClearDepthH        = GLES30.glGetUniformLocation( oitClearProgramH, "u_Depth");
432
    mOITClearTexCorrH      = GLES30.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
433
    mOITClearSizeH         = GLES30.glGetUniformLocation( oitClearProgramH, "u_Size");
434

    
435
    // OIT BUILD PROGRAM ////////////////////////////////////
436
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
437
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
438

    
439
    try
440
      {
441
      mOITBuildProgram = new DistortedProgram(oitBuildVertStream,oitBuildFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
442
      }
443
    catch(Exception e)
444
      {
445
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT BUILD program: "+e.getMessage());
446
      throw new RuntimeException(e.getMessage());
447
      }
448

    
449
    int oitBuildProgramH   = mOITBuildProgram.getProgramHandle();
450
    mOITBuildTextureH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Texture");
451
    mOITBuildDepthTextureH = GLES30.glGetUniformLocation( oitBuildProgramH, "u_DepthTexture");
452
    mOITBuildDepthH        = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Depth");
453
    mOITBuildTexCorrH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_TexCorr");
454
    mOITBuildSizeH         = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Size");
455
    mOITBuildNumRecordsH   = GLES30.glGetUniformLocation( oitBuildProgramH, "u_numRecords");
456

    
457
    // OIT COLLAPSE PROGRAM ///////////////////////////
458
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
459
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
460

    
461
    try
462
      {
463
      mOITCollapseProgram = new DistortedProgram(oitCollapseVertStream,oitCollapseFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
464
      }
465
    catch(Exception e)
466
      {
467
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT COLLAPSE program: "+e.getMessage());
468
      throw new RuntimeException(e.getMessage());
469
      }
470

    
471
    int oitCollapseProgramH   = mOITCollapseProgram.getProgramHandle();
472
    mOITCollapseDepthTextureH = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_DepthTexture");
473
    mOITCollapseDepthH        = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Depth");
474
    mOITCollapseTexCorrH      = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_TexCorr");
475
    mOITCollapseSizeH         = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Size");
476

    
477
    // OIT RENDER PROGRAM ///////////////////////////
478
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
479
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
480

    
481
    try
482
      {
483
      mOITRenderProgram = new DistortedProgram(oitRenderVertStream,oitRenderFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
484
      }
485
    catch(Exception e)
486
      {
487
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT RENDER program: "+e.getMessage());
488
      throw new RuntimeException(e.getMessage());
489
      }
490

    
491
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
492
    mOITRenderDepthH        = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Depth");
493
    mOITRenderTexCorrH      = GLES30.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
494
    mOITRenderSizeH         = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Size");
495
    }
496

    
497
///////////////////////////////////////////////////////////////////////////////////////////////////
498

    
499
  private static void displayNormals(float[] projection, MeshBase mesh)
500
    {
501
    if( mNormalProgram==null )
502
      {
503
      try
504
        {
505
        createNormalProgram(mResources);
506
        }
507
      catch(Exception ex)
508
        {
509
        mListener.distortedException(ex);
510
        return;
511
        }
512
      }
513

    
514
    int num = mesh.getNumVertices();
515
    int tfo = mesh.getTFO();
516

    
517
    GLES30.glUniform1i(DistortedLibrary.mTransformFeedbackH, 1);
518
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
519
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
520
    InternalRenderState.switchOffDrawing();
521
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
522
    InternalRenderState.restoreDrawing();
523
    GLES30.glEndTransformFeedback();
524
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
525
    GLES30.glUniform1i(DistortedLibrary.mTransformFeedbackH, 0);
526

    
527
    mNormalProgram.useProgram();
528
    GLES30.glUniformMatrix4fv(mNormalProjectionH, 1, false, projection, 0);
529
    mesh.bindTransformAttribs(mNormalProgram);
530
    GLES30.glLineWidth(8.0f);
531
    GLES30.glDrawArrays(GLES30.GL_LINES, 0, 2*num);
532
    mNormalProgram.stopUsingProgram();
533
    }
534

    
535
///////////////////////////////////////////////////////////////////////////////////////////////////
536
/**
537
 * Execute all VertexEffects and adjust all vertices
538
 *
539
 * @y.exclude
540
 */
541
  public static void adjustVertices(MeshBase mesh, EffectQueueVertex queue)
542
    {
543
    if( mFullProgram==null )
544
      {
545
      try
546
        {
547
        createFullProgram(mResources);
548
        }
549
      catch(Exception ex)
550
        {
551
        mListener.distortedException(ex);
552
        return;
553
        }
554
      }
555

    
556
    int num = mesh.getNumVertices();
557
    int tfo = mesh.getTFO();
558

    
559
    mFullProgram.useProgram();
560
    mesh.bindVertexAttribs(mFullProgram);
561
    queue.compute(1,0);
562
    queue.send(0.0f,mFullProgramH,3);
563
    mesh.send(mFullProgramH,3);
564

    
565
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
566
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
567
    InternalRenderState.switchOffDrawing();
568
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
569
    InternalRenderState.restoreDrawing();
570
    GLES30.glEndTransformFeedback();
571
    mesh.copyTransformToVertex();
572
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
573
    mFullProgram.stopUsingProgram();
574
    }
575

    
576
///////////////////////////////////////////////////////////////////////////////////////////////////
577

    
578
  static void drawPrivOIT(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime, long step)
579
    {
580
    if( mMainOITProgram!=null )
581
      {
582
      EffectQueue[] queues = effects.getQueues();
583

    
584
      EffectQueue.compute(queues, currTime, step);
585
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
586

    
587
      mMainOITProgram.useProgram();
588
      GLES30.glUniform1i(mMainOITTextureH, 0);
589
      GLES30.glUniform2ui(mMainOITSizeH, surface.mWidth, surface.mHeight);
590
      GLES30.glUniform1ui(mMainOITNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
591
      mesh.bindVertexAttribs(mMainOITProgram);
592
      mesh.send(mMainOITProgramH,1);
593

    
594
      float inflate     = mesh.getInflate();
595
      float distance    = surface.mDistance;
596
      float mipmap      = surface.mMipmap;
597
      float[] projection= surface.mProjectionMatrix;
598

    
599
      EffectQueue.send(queues, mMainOITProgramH, distance, mipmap, projection, inflate, 1 );
600
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
601
      mMainOITProgram.stopUsingProgram();
602

    
603
      if( mesh.getShowNormals() ) displayNormals(projection,mesh);
604
      }
605
    }
606

    
607
///////////////////////////////////////////////////////////////////////////////////////////////////
608

    
609
  static void drawPriv(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime, long step)
610
    {
611
    if( mMainProgram!=null )
612
      {
613
      EffectQueue[] queues = effects.getQueues();
614

    
615
      EffectQueue.compute(queues, currTime, step);
616
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
617

    
618
      mMainProgram.useProgram();
619
      GLES30.glUniform1i(DistortedLibrary.mMainTextureH, 0);
620
      mesh.bindVertexAttribs(DistortedLibrary.mMainProgram);
621
      mesh.send(mMainProgramH,0);
622

    
623
      float inflate     = mesh.getInflate();
624
      float distance    = surface.mDistance;
625
      float mipmap      = surface.mMipmap;
626
      float[] projection= surface.mProjectionMatrix;
627

    
628
      EffectQueue.send(queues, mMainProgramH, distance, mipmap, projection, inflate, 0 );
629
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
630
      mMainProgram.stopUsingProgram();
631

    
632
      if( mesh.getShowNormals() ) displayNormals(projection,mesh);
633
      }
634
    }
635

    
636
///////////////////////////////////////////////////////////////////////////////////////////////////
637

    
638
  static void blitPriv(InternalOutputSurface surface)
639
    {
640
    if( mBlitProgram!=null )
641
      {
642
      mBlitProgram.useProgram();
643
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
644
      GLES30.glUniform1i(mBlitTextureH, 0);
645
      GLES30.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
646
      GLES30.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
647
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
648
      mBlitProgram.stopUsingProgram();
649
      }
650
    }
651

    
652
///////////////////////////////////////////////////////////////////////////////////////////////////
653

    
654
  static void blitDepthPriv(InternalOutputSurface surface, float corrW, float corrH)
655
    {
656
    if( mBlitDepthProgram!=null )
657
      {
658
      mBlitDepthProgram.useProgram();
659
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
660
      GLES30.glUniform1i(mBlitDepthTextureH, 0);
661
      GLES30.glUniform1i(mBlitDepthDepthTextureH, 1);
662
      GLES30.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
663
      GLES30.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
664
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
665
      mBlitDepthProgram.stopUsingProgram();
666
      }
667
    }
668

    
669
///////////////////////////////////////////////////////////////////////////////////////////////////
670
// yes it is safe to be mixing 3.0 and 3.1 like that, senior members of the OpenGL discussions forum assert
671

    
672
  private static int printPreviousBuffer()
673
    {
674
    int counter = 0;
675

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

    
688
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
689

    
690
    return counter;
691
    }
692

    
693
///////////////////////////////////////////////////////////////////////////////////////////////////
694

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

    
709
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
710
    }
711

    
712
///////////////////////////////////////////////////////////////////////////////////////////////////
713
// reset atomic counter to 0
714

    
715
  static int zeroOutAtomic()
716
    {
717
    int counter = 0;
718

    
719
    if( mAtomicCounter==null )
720
      {
721
      mAtomicCounter = new int[mFBOQueueSize];
722

    
723
      GLES30.glGenBuffers(mFBOQueueSize,mAtomicCounter,0);
724

    
725
      for(int i=0; i<mFBOQueueSize; i++)
726
        {
727
        GLES30.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
728
        GLES30.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES30.GL_DYNAMIC_DRAW);
729
        zeroBuffer();
730
        }
731
      }
732

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

    
741
    if( ++mCurrBuffer>=mFBOQueueSize ) mCurrBuffer = 0;
742

    
743
    GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
744
    zeroBuffer();
745

    
746
    return counter;
747
    }
748

    
749
///////////////////////////////////////////////////////////////////////////////////////////////////
750
// Pass1 of the OIT algorithm. Clear per-pixel head-pointers.
751

    
752
  static void oitClear(InternalOutputSurface surface, int counter)
753
    {
754
    if( mOITClearProgram==null )
755
      {
756
      if( mGLSL>=310 && !mOITCompilationAttempted )
757
        {
758
        mOITCompilationAttempted = true;
759

    
760
        try
761
          {
762
          createOITProgram(mResources);
763
          }
764
        catch(Exception ex)
765
          {
766
          mListener.distortedException(ex);
767
          return;
768
          }
769
        }
770
      else
771
        {
772
        return;
773
        }
774
      }
775

    
776
    if( mLinkedListSSBO[0]<0 )
777
      {
778
      GLES30.glGenBuffers(1,mLinkedListSSBO,0);
779

    
780
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
781
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
782
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
783
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
784

    
785
      GLES30.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
786
      }
787

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

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

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

    
811
///////////////////////////////////////////////////////////////////////////////////////////////////
812
// Pass2 of the OIT algorithm - build per-pixel linked lists.
813

    
814
  static void oitBuild(InternalOutputSurface surface, float corrW, float corrH)
815
    {
816
    if( mOITBuildProgram!=null )
817
      {
818
      mOITBuildProgram.useProgram();
819
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
820
      GLES30.glUniform1i(mOITBuildTextureH, 0);
821
      GLES30.glUniform1i(mOITBuildDepthTextureH, 1);
822
      GLES30.glUniform2f(mOITBuildTexCorrH, corrW, corrH );
823
      GLES30.glUniform2ui(mOITBuildSizeH, surface.mWidth, surface.mHeight);
824
      GLES30.glUniform1ui(mOITBuildNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
825
      GLES30.glUniform1f(mOITBuildDepthH , 1.0f-surface.mNear);
826
      GLES30.glVertexAttribPointer(mOITBuildProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
827
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
828
      mOITBuildProgram.stopUsingProgram();
829
      }
830
    }
831

    
832
///////////////////////////////////////////////////////////////////////////////////////////////////
833
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
834

    
835
  static void oitCollapse(InternalOutputSurface surface, float corrW, float corrH)
836
    {
837
    if( mOITCollapseProgram!=null )
838
      {
839
      mOITCollapseProgram.useProgram();
840
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
841
      GLES30.glUniform1i(mOITCollapseDepthTextureH, 1);
842
      GLES30.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
843
      GLES30.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
844
      GLES30.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
845
      GLES30.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
846
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
847
      mOITCollapseProgram.stopUsingProgram();
848
      }
849
    }
850

    
851
///////////////////////////////////////////////////////////////////////////////////////////////////
852
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
853

    
854
  static void oitRender(InternalOutputSurface surface, float corrW, float corrH)
855
    {
856
    if( mOITRenderProgram!=null )
857
      {
858
      mOITRenderProgram.useProgram();
859
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
860
      GLES30.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
861
      GLES30.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
862
      GLES30.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
863
      GLES30.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
864
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
865
      mOITRenderProgram.stopUsingProgram();
866
      }
867
    }
868

    
869
///////////////////////////////////////////////////////////////////////////////////////////////////
870

    
871
  static void setSSBOSize(float size)
872
    {
873
    mBufferSize = size;
874
    }
875

    
876
///////////////////////////////////////////////////////////////////////////////////////////////////
877

    
878
  static int getQueueSize()
879
    {
880
    return mFBOQueueSize;
881
    }
882

    
883
///////////////////////////////////////////////////////////////////////////////////////////////////
884
// ARM Mali driver r12 has problems when we keep swapping many FBOs (fixed in r22)
885
// PowerVR GE8100 / GE8300 compiler fails to compile OIT programs.
886

    
887
  private static void detectBuggyDriversAndSetQueueSize(int queueSize)
888
    {
889
    mVendor  = GLES30.glGetString(GLES30.GL_VENDOR);
890
    mVersion = GLES30.glGetString(GLES30.GL_VERSION);
891
    mRenderer= GLES30.glGetString(GLES30.GL_RENDERER);
892

    
893
    mFBOQueueSize = 1;
894

    
895
    if( mVendor.contains("ARM") )
896
      {
897
      try
898
        {
899
        String regex = ".*r(\\d+)p\\d.*";
900
        Pattern pattern = Pattern.compile(regex);
901
        Matcher matcher = pattern.matcher(mVersion);
902

    
903
        if( matcher.find() )
904
          {
905
          String driverVersion = matcher.group(1);
906

    
907
          if( driverVersion!=null )
908
            {
909
            int drvVersion = Integer.parseInt(driverVersion);
910

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

    
916
              mFBOQueueSize = queueSize;
917
              }
918
            }
919
          }
920
        }
921
      catch(Exception ex)
922
        {
923
        android.util.Log.e("library", "exception trying to pattern match version: "+ex.toString());
924
        }
925
      }
926
    else if( mVendor.contains("Imagination") )
927
      {
928
      if( mRenderer.contains("GE8") )
929
        {
930
        Log.e("DISTORTED", "You are running this on a PowerVR GE8XXX.\nDue to a buggy compiler OIT rendering will not work");
931
        Log.e("DISTORTED", "GLSL Version "+GLES30.glGetString(GLES31.GL_SHADING_LANGUAGE_VERSION));
932
        }
933
      }
934
    else if( mVendor.contains("Qualcomm"))
935
      {
936
      if( mRenderer.contains("308") && (mVersion.contains("V@331.0") || mVersion.contains("V@415.0") ) )
937
        {
938
        Log.e("DISTORTED", "You are running this on an Adreno 308 driver 331 or 415.\nStrange shit might happen.");
939
        mBuggyUBOs = true;
940
        }
941
      }
942
    }
943

    
944
///////////////////////////////////////////////////////////////////////////////////////////////////
945
/**
946
 * Return OpenGL ES version supported by the hardware we are running on.
947
 * There are only three possibilities: 300 (OpenGL ES 3.0) or 310 (at least OpenGL ES 3.1)
948
 * or 200 (OpenGL ES 2.0)
949
 */
950
  public static int getGLSL()
951
    {
952
    return mGLSL;
953
    }
954

    
955
///////////////////////////////////////////////////////////////////////////////////////////////////
956
/**
957
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
958
 * I.e. best called from GLSurfaceView.Renderer.onSurfaceCreated().
959
 * <p>
960
 * Needs to be called from a thread holding the OpenGL context.
961
 *
962
 * @param context  Context of the App using the library - used to open up Resources and read Shader code.
963
 * @param listener The library will send all (asynchronous!) exceptions there.
964
 */
965
  public static void onSurfaceCreated(final Context context, final ExceptionListener listener)
966
    {
967
    onSurfaceCreated(context,listener,4);
968
    }
969

    
970
///////////////////////////////////////////////////////////////////////////////////////////////////
971
/**
972
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
973
 * I.e. best called from GLSurfaceView.Renderer.onSurfaceCreated().
974
 * <p>
975
 * Needs to be called from a thread holding the OpenGL context.
976
 *   
977
 * @param context   Context of the App using the library - used to open up Resources and read Shader code.
978
 * @param listener  The library will send all (asynchronous!) exceptions there.
979
 * @param queueSize the size of the FBO queue, a workaround for the bug on Mali drivers. Use a small integer - 1,...,4
980
 */
981
  public static void onSurfaceCreated(final Context context, final ExceptionListener listener, int queueSize)
982
    {
983
    final ActivityManager activityManager     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
984
    final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
985

    
986
    int glESversion = configurationInfo.reqGlEsVersion;
987
    int major = glESversion >> 16;
988
    int minor = glESversion & 0xff;
989

    
990
    mListener = listener;
991

    
992
    if( major< 3 )
993
      {
994
      mGLSL = 100*major + 10*minor;
995
      VertexCompilationException ex = new VertexCompilationException("at least OpenGL ES 3.0 required, this device supports only "+major+"."+minor);
996
      mListener.distortedException(ex);
997
      }
998
    else
999
      {
1000
      mGLSL = (major==3 && minor==0) ? 300 : 310;
1001
      }
1002

    
1003
    int[] tmp = new int[1];
1004
    GLES30.glGetIntegerv(GLES30.GL_MAX_TEXTURE_SIZE, tmp, 0);
1005
    mMaxTextureSize = tmp[0];
1006
    GLES30.glGetIntegerv(GLES30.GL_MAX_VERTEX_UNIFORM_VECTORS  , tmp, 0);
1007
    mMaxNumberOfVerUniforms = tmp[0];
1008
    GLES30.glGetIntegerv(GLES30.GL_MAX_FRAGMENT_UNIFORM_VECTORS, tmp, 0);
1009
    mMaxNumberOfFraUniforms = tmp[0];
1010

    
1011
    android.util.Log.e("DISTORTED", "Using OpenGL ES "+major+"."+minor);
1012
/*
1013
    android.util.Log.e("DISTORTED", "max texture size: "+mMaxTextureSize);
1014
    android.util.Log.e("DISTORTED", "max num vert: "+mMaxNumberOfVerUniforms);
1015
    android.util.Log.e("DISTORTED", "max num frag: "+mMaxNumberOfFraUniforms);
1016
*/
1017
    mGLSL_VERSION = "#version "+mGLSL+" es\n";
1018

    
1019
    InternalStackFrameList.setInitialized(true);
1020
    mOITCompilationAttempted = false;
1021

    
1022
    detectBuggyDriversAndSetQueueSize(queueSize);
1023
    EffectMessageSender.startSending();
1024

    
1025
    mResources = context.getResources();
1026

    
1027
    try
1028
      {
1029
      createMainProgram();
1030
      }
1031
    catch(Exception ex)
1032
      {
1033
      mListener.distortedException(ex);
1034
      }
1035

    
1036
    try
1037
      {
1038
      EffectQueuePostprocess.createPrograms(mResources, mGLSL);
1039
      }
1040
    catch(Exception ex)
1041
      {
1042
      mListener.distortedException(ex);
1043
      }
1044

    
1045
    try
1046
      {
1047
      PostprocessEffect.createPrograms(mGLSL);
1048
      }
1049
    catch(Exception ex)
1050
      {
1051
      mListener.distortedException(ex);
1052
      }
1053
    }
1054

    
1055
///////////////////////////////////////////////////////////////////////////////////////////////////
1056
/**
1057
 * Switch face culling on/off
1058
 */
1059
  public static void setCull(boolean on)
1060
    {
1061
    if( on )
1062
      {
1063
      GLES30.glEnable(GLES30.GL_CULL_FACE);
1064
      GLES30.glCullFace(GLES30.GL_FRONT);
1065
      }
1066
    else
1067
      {
1068
      GLES30.glDisable(GLES30.GL_CULL_FACE);
1069
      }
1070
    }
1071

    
1072
///////////////////////////////////////////////////////////////////////////////////////////////////
1073
/**
1074
 * Call this so that the Library can initialize its internal data structures.
1075
 * Must be called from Activity.onCreate().
1076
 */
1077
  public static void onCreate()
1078
    {
1079
    onCreate(0);
1080
    }
1081

    
1082
///////////////////////////////////////////////////////////////////////////////////////////////////
1083
/**
1084
 * Call this so that the Library can initialize its internal data structures.
1085
 * Must be called from Activity.onCreate().
1086
 *
1087
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1088
 *           tell between Activities in case you're going to be using it from more than one.
1089
 */
1090
  public static void onCreate(long id)
1091
    {
1092
    InternalStackFrameList.onCreate(id);
1093
    }
1094

    
1095
///////////////////////////////////////////////////////////////////////////////////////////////////
1096
/**
1097
 * Call this so that the Library can resume its operations.
1098
 * Must be called from Activity.onResume().
1099
 */
1100
  public static void onResume()
1101
    {
1102
    onResume(0);
1103
    }
1104

    
1105
///////////////////////////////////////////////////////////////////////////////////////////////////
1106
/**
1107
 * Call this so that the Library can resume its operations.
1108
 * Must be called from Activity.onResume().
1109
 *
1110
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1111
 *           tell between Activities in case you're going to be using it from more than one.
1112
 */
1113
  public static void onResume(long id)
1114
    {
1115
    InternalStackFrameList.onResume(id);
1116
    }
1117

    
1118
///////////////////////////////////////////////////////////////////////////////////////////////////
1119
/**
1120
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
1121
 * Must be called from Activity.onPause().
1122
 */
1123
  public static void onPause()
1124
    {
1125
    onPause(0);
1126
    }
1127

    
1128
///////////////////////////////////////////////////////////////////////////////////////////////////
1129
/**
1130
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
1131
 * Must be called from Activity.onPause().
1132
 *
1133
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1134
 *           tell between Activities in case you're going to be using it from more than one.
1135
 */
1136
  public static void onPause(long id)
1137
    {
1138
    InternalStackFrameList.onPause(id);
1139

    
1140
    Dynamic.onPause();  // common for all frames
1141
    InternalOutputSurface.onPause();
1142
    Effect.onPause();
1143
    DeferredJobs.onPause();
1144

    
1145
    mOITCompilationAttempted = false;
1146
    mNeedsTransformFeedback  = false;
1147

    
1148
    mLinkedListSSBO[0]= -1;
1149
    mAtomicCounter = null;
1150

    
1151
    mNormalProgram     = null;
1152
    mMainOITProgram    = null;
1153
    mMainProgram       = null;
1154
    mFullProgram       = null;
1155
    mOITClearProgram   = null;
1156
    mOITBuildProgram   = null;
1157
    mOITCollapseProgram= null;
1158
    mOITRenderProgram  = null;
1159
    mBlitDepthProgram  = null;
1160
    mBlitProgram       = null;
1161
    }
1162

    
1163
///////////////////////////////////////////////////////////////////////////////////////////////////
1164
/**
1165
 * Call this so that the Library can release its internal data structures.
1166
 * Must be called from Activity.onDestroy().
1167
 */
1168
  public static void onDestroy()
1169
    {
1170
    onDestroy(0);
1171
    }
1172

    
1173
///////////////////////////////////////////////////////////////////////////////////////////////////
1174
/**
1175
 * Call this so that the Library can release its internal data structures.
1176
 * Must be called from Activity.onDestroy().
1177
 *
1178
 * @param id id of an Activity that is using the library; anything unique so that the Library can
1179
 *           tell between Activities in case you're going to be using it from more than one.
1180
 */
1181
  public static void onDestroy(long id)
1182
    {
1183
    if( InternalStackFrameList.isInitialized() )
1184
      {
1185
      InternalStackFrameList.onDestroy(id);
1186
      }
1187
    }
1188

    
1189
///////////////////////////////////////////////////////////////////////////////////////////////////
1190
/**
1191
 * Return the maximum size of the texture supported by the driver.
1192
 */
1193
  public static int getMaxTextureSize()
1194
    {
1195
    return mMaxTextureSize;
1196
    }
1197

    
1198
///////////////////////////////////////////////////////////////////////////////////////////////////
1199
/**
1200
 * Call this before calling onSurfaceCreated() if you want to access normal vectors in CPU.
1201
 */
1202
  public static void needTransformFeedback()
1203
    {
1204
    mNeedsTransformFeedback = true;
1205
    }
1206

    
1207
///////////////////////////////////////////////////////////////////////////////////////////////////
1208
/**
1209
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
1210
 * single (InputSurface,MeshBase) combo.
1211
 *
1212
 * @param type {@link EffectType}
1213
 * @return The maximum number of effects of a given type.
1214
 */
1215
  @SuppressWarnings("unused")
1216
  public static int getMax(EffectType type)
1217
    {
1218
    return EffectQueue.getMax(type.ordinal());
1219
    }
1220

    
1221
///////////////////////////////////////////////////////////////////////////////////////////////////
1222
/**
1223
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
1224
 * This can fail if:
1225
 * <ul>
1226
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
1227
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
1228
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link DistortedLibrary#onSurfaceCreated}. After this
1229
 *     time only decreasing the value of 'max' is permitted.
1230
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
1231
 * </ul>
1232
 *
1233
 * @param type {@link EffectType}
1234
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
1235
 *            than Byte.MAX_VALUE
1236
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
1237
 */
1238
  @SuppressWarnings("unused")
1239
  public static boolean setMax(EffectType type, int max)
1240
    {
1241
    return EffectQueue.setMax(type.ordinal(),max);
1242
    }
1243

    
1244
///////////////////////////////////////////////////////////////////////////////////////////////////
1245
/**
1246
 * Return a String defining the vendor of the graphics driver.
1247
 */
1248
  public static String getDriverVendor()
1249
    {
1250
    return mVendor;
1251
    }
1252

    
1253
///////////////////////////////////////////////////////////////////////////////////////////////////
1254
/**
1255
 * Return a String defining the version of the graphics driver.
1256
 */
1257
  public static String getDriverVersion()
1258
    {
1259
    return mVersion;
1260
    }
1261

    
1262
///////////////////////////////////////////////////////////////////////////////////////////////////
1263
/**
1264
 * Return a String defining the renderer of the graphics driver.
1265
 */
1266
  public static String getDriverRenderer()
1267
    {
1268
    return mRenderer;
1269
    }
1270
  }
(3-3/17)