Project

General

Profile

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

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

1 d333eb6b Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2016 Leszek Koltunski                                                               //
3
//                                                                                               //
4 46b572b5 Leszek Koltunski
// This file is part of Distorted.                                                               //
5 d333eb6b Leszek Koltunski
//                                                                                               //
6 46b572b5 Leszek Koltunski
// Distorted is free software: you can redistribute it and/or modify                             //
7 d333eb6b Leszek Koltunski
// 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 46b572b5 Leszek Koltunski
// Distorted is distributed in the hope that it will be useful,                                  //
12 d333eb6b Leszek Koltunski
// 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 46b572b5 Leszek Koltunski
// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
18 d333eb6b Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
19
20 fe82a979 Leszek Koltunski
package org.distorted.library.main;
21 6a06a912 Leszek Koltunski
22 30beb34f Leszek Koltunski
import android.app.ActivityManager;
23 7845dc66 Leszek Koltunski
import android.content.Context;
24 30beb34f Leszek Koltunski
import android.content.pm.ConfigurationInfo;
25 d6e94c84 Leszek Koltunski
import android.content.res.Resources;
26 b7074bc6 Leszek Koltunski
import android.opengl.GLES30;
27 edea9cf3 Leszek Koltunski
import android.opengl.GLES31;
28 bfe45b4a Leszek Koltunski
import android.util.Log;
29 310e14fb leszek
30 bfe45b4a Leszek Koltunski
import org.distorted.library.R;
31 26a4e5f6 leszek
import org.distorted.library.effect.Effect;
32 809dcae3 Leszek Koltunski
import org.distorted.library.effectqueue.EffectQueue;
33
import org.distorted.library.effectqueue.EffectQueuePostprocess;
34 bfe45b4a Leszek Koltunski
import org.distorted.library.effect.EffectType;
35
import org.distorted.library.effect.FragmentEffect;
36 aa2f0486 Leszek Koltunski
import org.distorted.library.effect.PostprocessEffect;
37 bfe45b4a Leszek Koltunski
import org.distorted.library.effect.VertexEffect;
38 07206c71 Leszek Koltunski
import org.distorted.library.effectqueue.EffectQueueVertex;
39
import org.distorted.library.mesh.DeferredJobs;
40 bfe45b4a Leszek Koltunski
import org.distorted.library.mesh.MeshBase;
41 ed06301f Leszek Koltunski
import org.distorted.library.message.EffectMessageSender;
42 bfe45b4a Leszek Koltunski
import org.distorted.library.program.DistortedProgram;
43 b7074bc6 Leszek Koltunski
import org.distorted.library.program.VertexCompilationException;
44 0273ef2a Leszek Koltunski
import org.distorted.library.type.Dynamic;
45 bfe45b4a Leszek Koltunski
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 5f35f1cb Leszek Koltunski
import java.util.regex.Matcher;
52
import java.util.regex.Pattern;
53 6a06a912 Leszek Koltunski
54
///////////////////////////////////////////////////////////////////////////////////////////////////
55
/**
56 f953bee0 Leszek Koltunski
 * A singleton class used to control various global dialog_settings.
57 6a06a912 Leszek Koltunski
 */
58 7602a827 Leszek Koltunski
public class DistortedLibrary
59 39cbf9dc Leszek Koltunski
  {
60 b7074bc6 Leszek Koltunski
  private static int mGLSL;
61
  private static String mGLSL_VERSION;
62 d99fcc9c Leszek Koltunski
  private static boolean mOITCompilationAttempted;
63 6a06a912 Leszek Koltunski
  /**
64 cacc63de Leszek Koltunski
   * When creating an instance of a DistortedTexture from another instance, clone the Bitmap that's
65
   * backing up our DistortedTexture.
66 6a06a912 Leszek Koltunski
   * <p>
67 cacc63de Leszek Koltunski
   * This way we can have two DistortedTextures, both backed up by the same Bitmap, to which we can
68 6a06a912 Leszek Koltunski
   * apply different effects. Used in the copy constructor.
69
   */
70 29a06526 Leszek Koltunski
  public static final int CLONE_SURFACE = 0x1;
71 6a06a912 Leszek Koltunski
  /**
72 cacc63de Leszek Koltunski
   * When creating an instance of a DistortedEffects from another instance, clone the Matrix Effects.
73 6a06a912 Leszek Koltunski
   * <p>
74 cacc63de Leszek Koltunski
   * This way we can have two different DistortedEffects sharing the MATRIX queue.
75 6a06a912 Leszek Koltunski
   */
76 015642fb Leszek Koltunski
  public static final int CLONE_MATRIX = 0x2;
77 6a06a912 Leszek Koltunski
  /**
78 cacc63de Leszek Koltunski
   * When creating an instance of a DistortedEffects from another instance, clone the Vertex Effects.
79 6a06a912 Leszek Koltunski
   * <p>
80 cacc63de Leszek Koltunski
   * This way we can have two different DistortedEffects sharing the VERTEX queue.
81 6a06a912 Leszek Koltunski
   */
82
  public static final int CLONE_VERTEX  = 0x4;
83
  /**
84 cacc63de Leszek Koltunski
   * When creating an instance of a DistortedEffects from another instance, clone the Fragment Effects.
85 6a06a912 Leszek Koltunski
   * <p>
86 cacc63de Leszek Koltunski
   * This way we can have two different DistortedEffects sharing the FRAGMENT queue.
87 6a06a912 Leszek Koltunski
   */
88
  public static final int CLONE_FRAGMENT= 0x8;
89 d6e94c84 Leszek Koltunski
   /**
90
   * When creating an instance of a DistortedEffects from another instance, clone the PostProcess Effects.
91
   * <p>
92
   * This way we can have two different DistortedEffects sharing the POSTPROCESS queue.
93
   */
94
  public static final int CLONE_POSTPROCESS= 0x10;
95 6a06a912 Leszek Koltunski
  /**
96 a09ada4c Leszek Koltunski
   * When creating an instance of a DistortedNode from another instance, clone the children Nodes.
97 6a06a912 Leszek Koltunski
   * <p>
98 cacc63de Leszek Koltunski
   * This is mainly useful for creating many similar sub-trees and rendering then at different places
99
   * on the screen with (optionally) different Effects.
100 6a06a912 Leszek Koltunski
   */
101 d6e94c84 Leszek Koltunski
  public static final int CLONE_CHILDREN= 0x20;
102 b3618cb5 Leszek Koltunski
103 5f35f1cb Leszek Koltunski
  /**
104
   * When creating a DistortedScreen (which needs to have mFBOQueueSize FBOs attached), pass this
105
   * constant for 'numOfFBOs' and the number of backing FBOs will be taken from 'mFBOQueueSize'
106
   * (the value of which is most likely unknown at the time of creation of the Screen)
107
   */
108
  public static final int WAIT_FOR_FBO_QUEUE_SIZE = -1;
109 586b5fa1 Leszek Koltunski
  /**
110
   * Work around bugs in ARM Mali driver by, instead to a single FBO, rendering to a circular queue
111 5f35f1cb Leszek Koltunski
   * of mFBOQueueSize FBOs. (otherwise we sometimes get a 'full pipeline flush' and the end result
112 586b5fa1 Leszek Koltunski
   * might be missing part of the Objects)
113 6672d895 Leszek Koltunski
   *
114 5f35f1cb Leszek Koltunski
   * This bug only exists on Mali driver r12. (or more precisely it's there in r12 but fixed in r22)
115 6672d895 Leszek Koltunski
   *
116
   * https://community.arm.com/graphics/f/discussions/10285/opengl-es-3-1-on-mali-t880-flashes
117 586b5fa1 Leszek Koltunski
   */
118 5f35f1cb Leszek Koltunski
  private static int mFBOQueueSize;
119 586b5fa1 Leszek Koltunski
120 55c14a19 Leszek Koltunski
  private static boolean mInitialized=false;
121 6a06a912 Leszek Koltunski
122 bfe45b4a Leszek Koltunski
  //////////////////////////////////////////////////////////////////////////////////////////////
123
  /// MAIN PROGRAM ///
124
  private static DistortedProgram mMainProgram;
125
  private static int mMainTextureH;
126 62c869ad Leszek Koltunski
  private static int mTransformFeedbackH;
127 bfe45b4a Leszek Koltunski
128
  /// NORMAL PROGRAM /////
129
  private static DistortedProgram mNormalProgram;
130 62c869ad Leszek Koltunski
  private static int mNormalProjectionH;
131 bfe45b4a Leszek Koltunski
132
  /// MAIN OIT PROGRAM ///
133
  private static DistortedProgram mMainOITProgram;
134
  private static int mMainOITTextureH;
135
  private static int mMainOITSizeH;
136
  private static int mMainOITNumRecordsH;
137
138
  /// BLIT PROGRAM ///
139
  private static DistortedProgram mBlitProgram;
140
  private static int mBlitTextureH;
141
  private static int mBlitDepthH;
142
  private static final FloatBuffer mQuadPositions;
143
144 f046b159 Leszek Koltunski
  /// FULL PROGRAM ///
145
  private static DistortedProgram mFullProgram;
146
147 bfe45b4a Leszek Koltunski
  static
148
    {
149
    float[] positionData= { -0.5f, -0.5f,  -0.5f, 0.5f,  0.5f,-0.5f,  0.5f, 0.5f };
150
    mQuadPositions = ByteBuffer.allocateDirect(32).order(ByteOrder.nativeOrder()).asFloatBuffer();
151
    mQuadPositions.put(positionData).position(0);
152
    }
153
154
  /// BLIT DEPTH PROGRAM ///
155
  private static DistortedProgram mBlitDepthProgram;
156
  private static int mBlitDepthTextureH;
157
  private static int mBlitDepthDepthTextureH;
158
  private static int mBlitDepthDepthH;
159
  private static int mBlitDepthTexCorrH;
160
161 0bd9f644 Leszek Koltunski
  /// Program Handles ///
162
  private static int mMainProgramH, mFullProgramH, mMainOITProgramH;
163
164 bfe45b4a Leszek Koltunski
  /// OIT SSBO BUFFER ///
165
  private static int[] mLinkedListSSBO = new int[1];
166 5f35f1cb Leszek Koltunski
  private static int[] mAtomicCounter;
167 bfe45b4a Leszek Koltunski
  private static int   mCurrBuffer;
168
169
  static
170
    {
171
    mLinkedListSSBO[0]= -1;
172
    mCurrBuffer       =  0;
173
    }
174
175
  ///////////////////////////////////////////////////////////////
176
  // meaning: allocate 1.0 screenful of places for transparent
177
  // fragments in the SSBO backing up the OIT render method.
178
  private static float mBufferSize=1.0f;
179
180
  /// OIT CLEAR PROGRAM ///
181
  private static DistortedProgram mOITClearProgram;
182
  private static int mOITClearDepthH;
183
  private static int mOITClearTexCorrH;
184
  private static int mOITClearSizeH;
185
186
  /// OIT BUILD PROGRAM ///
187
  private static DistortedProgram mOITBuildProgram;
188
  private static int mOITBuildTextureH;
189
  private static int mOITBuildDepthTextureH;
190
  private static int mOITBuildDepthH;
191
  private static int mOITBuildTexCorrH;
192
  private static int mOITBuildSizeH;
193
  private static int mOITBuildNumRecordsH;
194
195
  /// OIT COLLAPSE PROGRAM ///
196
  private static DistortedProgram mOITCollapseProgram;
197
  private static int mOITCollapseDepthTextureH;
198
  private static int mOITCollapseDepthH;
199
  private static int mOITCollapseTexCorrH;
200
  private static int mOITCollapseSizeH;
201
202
  /// OIT RENDER PROGRAM ///
203
  private static DistortedProgram mOITRenderProgram;
204
  private static int mOITRenderDepthH;
205
  private static int mOITRenderTexCorrH;
206
  private static int mOITRenderSizeH;
207
208
  /// END PROGRAMS //////
209
210 d99fcc9c Leszek Koltunski
  /**
211
   * Every application using the library must implement this interface so that the library can send
212
   * it exceptions that arise. The exceptions may come at any time, for example the library will
213
   * compile its OIT problem only on the first attempt to use the OIT
214
   * Those will mainly be hardware-related: shaders do not compile on particular hardware, the required
215
   * OpenGL ES 3.0 is not supported, etc.
216
   */
217
  public interface ExceptionListener
218
    {
219
    void distortedException(Exception ex);
220
    }
221
222
  private static ExceptionListener mListener;
223
  private static Resources mResources;
224
225 6a06a912 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
226 c638c1b0 Leszek Koltunski
// private: hide this from Javadoc
227 6a06a912 Leszek Koltunski
228 7602a827 Leszek Koltunski
  private DistortedLibrary()
229 6a06a912 Leszek Koltunski
    {
230 8eccf334 Leszek Koltunski
231 6a06a912 Leszek Koltunski
    }
232
233 bfe45b4a Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
234
235 d99fcc9c Leszek Koltunski
  private static void createMainProgram()
236 bfe45b4a Leszek Koltunski
    {
237
    // MAIN PROGRAM ////////////////////////////////////
238 d99fcc9c Leszek Koltunski
    final InputStream mainVertStream = mResources.openRawResource(R.raw.main_vertex_shader);
239
    final InputStream mainFragStream = mResources.openRawResource(R.raw.main_fragment_shader);
240 bfe45b4a Leszek Koltunski
241
    int numF = FragmentEffect.getNumEnabled();
242
    int numV = VertexEffect.getNumEnabled();
243
244 b7074bc6 Leszek Koltunski
    String mainVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n");
245
    String mainFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n");
246 36d65d88 Leszek Koltunski
247 e8925fcd Leszek Koltunski
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
248 36d65d88 Leszek Koltunski
249 bfe45b4a Leszek Koltunski
    String enabledEffectV= VertexEffect.getGLSL();
250
    String enabledEffectF= FragmentEffect.getGLSL();
251
252
    String[] feedback = { "v_Position", "v_endPosition" };
253
254
    try
255
      {
256
      mMainProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
257 b7074bc6 Leszek Koltunski
                                          enabledEffectV, enabledEffectF, mGLSL, feedback);
258 bfe45b4a Leszek Koltunski
      }
259
    catch(Exception e)
260
      {
261
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN program: "+e.getMessage());
262
      throw new RuntimeException(e.getMessage());
263
      }
264
265 0bd9f644 Leszek Koltunski
    mMainProgramH = mMainProgram.getProgramHandle();
266
    EffectQueue.getUniforms(mMainProgramH,0);
267
    mMainTextureH= GLES30.glGetUniformLocation( mMainProgramH, "u_Texture");
268
    mTransformFeedbackH= GLES30.glGetUniformLocation( mMainProgramH, "u_TransformFeedback");
269 bfe45b4a Leszek Koltunski
270
    // BLIT PROGRAM ////////////////////////////////////
271 d99fcc9c Leszek Koltunski
    final InputStream blitVertStream = mResources.openRawResource(R.raw.blit_vertex_shader);
272
    final InputStream blitFragStream = mResources.openRawResource(R.raw.blit_fragment_shader);
273 bfe45b4a Leszek Koltunski
274
    try
275
      {
276 b7074bc6 Leszek Koltunski
      mBlitProgram = new DistortedProgram(blitVertStream,blitFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
277 bfe45b4a Leszek Koltunski
      }
278
    catch(Exception e)
279
      {
280
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT program: "+e.getMessage());
281
      throw new RuntimeException(e.getMessage());
282
      }
283
284
    int blitProgramH = mBlitProgram.getProgramHandle();
285 b7074bc6 Leszek Koltunski
    mBlitTextureH  = GLES30.glGetUniformLocation( blitProgramH, "u_Texture");
286
    mBlitDepthH    = GLES30.glGetUniformLocation( blitProgramH, "u_Depth");
287 bfe45b4a Leszek Koltunski
288
    // BLIT DEPTH PROGRAM ////////////////////////////////////
289 d99fcc9c Leszek Koltunski
    final InputStream blitDepthVertStream = mResources.openRawResource(R.raw.blit_depth_vertex_shader);
290
    final InputStream blitDepthFragStream = mResources.openRawResource(R.raw.blit_depth_fragment_shader);
291 bfe45b4a Leszek Koltunski
292
    try
293
      {
294 b7074bc6 Leszek Koltunski
      mBlitDepthProgram = new DistortedProgram(blitDepthVertStream,blitDepthFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
295 bfe45b4a Leszek Koltunski
      }
296
    catch(Exception e)
297
      {
298
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile BLIT DEPTH program: "+e.getMessage());
299
      throw new RuntimeException(e.getMessage());
300
      }
301
302
    int blitDepthProgramH   = mBlitDepthProgram.getProgramHandle();
303 b7074bc6 Leszek Koltunski
    mBlitDepthTextureH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Texture");
304
    mBlitDepthDepthTextureH = GLES30.glGetUniformLocation( blitDepthProgramH, "u_DepthTexture");
305
    mBlitDepthDepthH        = GLES30.glGetUniformLocation( blitDepthProgramH, "u_Depth");
306
    mBlitDepthTexCorrH      = GLES30.glGetUniformLocation( blitDepthProgramH, "u_TexCorr");
307 d99fcc9c Leszek Koltunski
    }
308
309
///////////////////////////////////////////////////////////////////////////////////////////////////
310 bfe45b4a Leszek Koltunski
311 d99fcc9c Leszek Koltunski
  private static void createNormalProgram(Resources resources)
312
    {
313 bfe45b4a Leszek Koltunski
    // NORMAL PROGRAM //////////////////////////////////////
314
    final InputStream normalVertexStream   = resources.openRawResource(R.raw.normal_vertex_shader);
315
    final InputStream normalFragmentStream = resources.openRawResource(R.raw.normal_fragment_shader);
316
317
    try
318
      {
319 b7074bc6 Leszek Koltunski
      mNormalProgram = new DistortedProgram(normalVertexStream,normalFragmentStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
320 bfe45b4a Leszek Koltunski
      }
321
    catch(Exception e)
322
      {
323
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile NORMAL program: "+e.getMessage());
324
      throw new RuntimeException(e.getMessage());
325
      }
326
327
    int normalProgramH = mNormalProgram.getProgramHandle();
328 62c869ad Leszek Koltunski
    mNormalProjectionH = GLES30.glGetUniformLocation( normalProgramH, "u_Projection");
329 bfe45b4a Leszek Koltunski
    }
330
331 f046b159 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
332
333
  private static void createFullProgram(Resources resources)
334
    {
335
    final InputStream fullVertStream = resources.openRawResource(R.raw.main_vertex_shader);
336
    final InputStream fullFragStream = resources.openRawResource(R.raw.main_fragment_shader);
337
338
    int numV = VertexEffect.getAllEnabled();
339
340
    String fullVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX ) : 0 ) + "\n");
341
    String fullFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " +                                         0   + "\n");
342 36d65d88 Leszek Koltunski
343 e8925fcd Leszek Koltunski
    fullVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
344 36d65d88 Leszek Koltunski
345 f046b159 Leszek Koltunski
    String enabledEffectV= VertexEffect.getAllGLSL();
346
    String enabledEffectF= "{}";
347
348 667884b0 Leszek Koltunski
    fullVertHeader += "#define PREAPPLY\n";
349
350 a2878a67 Leszek Koltunski
    String[] feedback = { "v_Position", "v_endPosition" };
351 f046b159 Leszek Koltunski
352
    try
353
      {
354
      mFullProgram = new DistortedProgram(fullVertStream, fullFragStream, fullVertHeader, fullFragHeader,
355
                                          enabledEffectV, enabledEffectF, mGLSL, feedback);
356
      }
357
    catch(Exception e)
358
      {
359
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile FULL program: "+e.getMessage());
360
      throw new RuntimeException(e.getMessage());
361
      }
362
363 0bd9f644 Leszek Koltunski
    mFullProgramH = mFullProgram.getProgramHandle();
364
    EffectQueue.getUniforms(mFullProgramH,3);
365 f046b159 Leszek Koltunski
    }
366
367 bfe45b4a Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
368
369 d99fcc9c Leszek Koltunski
  private static void createOITProgram(Resources resources)
370 bfe45b4a Leszek Koltunski
    {
371
    // MAIN OIT PROGRAM ////////////////////////////////
372
    final InputStream mainVertStream = resources.openRawResource(R.raw.main_vertex_shader);
373
    final InputStream mainFragStream = resources.openRawResource(R.raw.main_fragment_shader);
374
375
    int numF = FragmentEffect.getNumEnabled();
376
    int numV = VertexEffect.getNumEnabled();
377
378 b7074bc6 Leszek Koltunski
    String mainVertHeader= mGLSL_VERSION + ("#define NUM_VERTEX "   + ( numV>0 ? getMax(EffectType.VERTEX  ) : 0 ) + "\n") + ("#define OIT\n");
379
    String mainFragHeader= mGLSL_VERSION + ("#define NUM_FRAGMENT " + ( numF>0 ? getMax(EffectType.FRAGMENT) : 0 ) + "\n") + ("#define OIT\n");
380 bfe45b4a Leszek Koltunski
381 e8925fcd Leszek Koltunski
    mainVertHeader += "#define MAX_COMPON " + MeshBase.getMaxEffComponents() + "\n";
382 36d65d88 Leszek Koltunski
383 bfe45b4a Leszek Koltunski
    String enabledEffectV= VertexEffect.getGLSL();
384
    String enabledEffectF= FragmentEffect.getGLSL();
385
386
    try
387
      {
388
      mMainOITProgram = new DistortedProgram(mainVertStream, mainFragStream, mainVertHeader, mainFragHeader,
389 b7074bc6 Leszek Koltunski
                                             enabledEffectV, enabledEffectF, mGLSL, null);
390 bfe45b4a Leszek Koltunski
      }
391
    catch(Exception e)
392
      {
393
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile MAIN OIT program: "+e.getMessage());
394
      throw new RuntimeException(e.getMessage());
395
      }
396
397 0bd9f644 Leszek Koltunski
    mMainOITProgramH = mMainOITProgram.getProgramHandle();
398
    EffectQueue.getUniforms(mMainOITProgramH,1);
399
    mMainOITTextureH    = GLES30.glGetUniformLocation( mMainOITProgramH, "u_Texture");
400
    mMainOITSizeH       = GLES30.glGetUniformLocation( mMainOITProgramH, "u_Size");
401
    mMainOITNumRecordsH = GLES30.glGetUniformLocation( mMainOITProgramH, "u_numRecords");
402 bfe45b4a Leszek Koltunski
403
    // OIT CLEAR PROGRAM ////////////////////////////////////
404
    final InputStream oitClearVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
405
    final InputStream oitClearFragStream = resources.openRawResource(R.raw.oit_clear_fragment_shader);
406
407
    try
408
      {
409 b7074bc6 Leszek Koltunski
      mOITClearProgram = new DistortedProgram(oitClearVertStream,oitClearFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
410 bfe45b4a Leszek Koltunski
      }
411
    catch(Exception e)
412
      {
413
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT CLEAR program: "+e.getMessage());
414
      throw new RuntimeException(e.getMessage());
415
      }
416
417
    int oitClearProgramH   = mOITClearProgram.getProgramHandle();
418 b7074bc6 Leszek Koltunski
    mOITClearDepthH        = GLES30.glGetUniformLocation( oitClearProgramH, "u_Depth");
419
    mOITClearTexCorrH      = GLES30.glGetUniformLocation( oitClearProgramH, "u_TexCorr");
420
    mOITClearSizeH         = GLES30.glGetUniformLocation( oitClearProgramH, "u_Size");
421 bfe45b4a Leszek Koltunski
422
    // OIT BUILD PROGRAM ////////////////////////////////////
423
    final InputStream oitBuildVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
424
    final InputStream oitBuildFragStream = resources.openRawResource(R.raw.oit_build_fragment_shader);
425
426
    try
427
      {
428 b7074bc6 Leszek Koltunski
      mOITBuildProgram = new DistortedProgram(oitBuildVertStream,oitBuildFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
429 bfe45b4a Leszek Koltunski
      }
430
    catch(Exception e)
431
      {
432
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT BUILD program: "+e.getMessage());
433
      throw new RuntimeException(e.getMessage());
434
      }
435
436
    int oitBuildProgramH   = mOITBuildProgram.getProgramHandle();
437 b7074bc6 Leszek Koltunski
    mOITBuildTextureH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Texture");
438
    mOITBuildDepthTextureH = GLES30.glGetUniformLocation( oitBuildProgramH, "u_DepthTexture");
439
    mOITBuildDepthH        = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Depth");
440
    mOITBuildTexCorrH      = GLES30.glGetUniformLocation( oitBuildProgramH, "u_TexCorr");
441
    mOITBuildSizeH         = GLES30.glGetUniformLocation( oitBuildProgramH, "u_Size");
442
    mOITBuildNumRecordsH   = GLES30.glGetUniformLocation( oitBuildProgramH, "u_numRecords");
443 bfe45b4a Leszek Koltunski
444
    // OIT COLLAPSE PROGRAM ///////////////////////////
445
    final InputStream oitCollapseVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
446
    final InputStream oitCollapseFragStream = resources.openRawResource(R.raw.oit_collapse_fragment_shader);
447
448
    try
449
      {
450 b7074bc6 Leszek Koltunski
      mOITCollapseProgram = new DistortedProgram(oitCollapseVertStream,oitCollapseFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
451 bfe45b4a Leszek Koltunski
      }
452
    catch(Exception e)
453
      {
454
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT COLLAPSE program: "+e.getMessage());
455
      throw new RuntimeException(e.getMessage());
456
      }
457
458
    int oitCollapseProgramH   = mOITCollapseProgram.getProgramHandle();
459 b7074bc6 Leszek Koltunski
    mOITCollapseDepthTextureH = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_DepthTexture");
460
    mOITCollapseDepthH        = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Depth");
461
    mOITCollapseTexCorrH      = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_TexCorr");
462
    mOITCollapseSizeH         = GLES30.glGetUniformLocation( oitCollapseProgramH, "u_Size");
463 bfe45b4a Leszek Koltunski
464
    // OIT RENDER PROGRAM ///////////////////////////
465
    final InputStream oitRenderVertStream = resources.openRawResource(R.raw.oit_vertex_shader);
466
    final InputStream oitRenderFragStream = resources.openRawResource(R.raw.oit_render_fragment_shader);
467
468
    try
469
      {
470 b7074bc6 Leszek Koltunski
      mOITRenderProgram = new DistortedProgram(oitRenderVertStream,oitRenderFragStream, mGLSL_VERSION, mGLSL_VERSION, mGLSL);
471 bfe45b4a Leszek Koltunski
      }
472
    catch(Exception e)
473
      {
474
      Log.e("EFFECTS", e.getClass().getSimpleName()+" trying to compile OIT RENDER program: "+e.getMessage());
475
      throw new RuntimeException(e.getMessage());
476
      }
477
478
    int oitRenderProgramH   = mOITRenderProgram.getProgramHandle();
479 b7074bc6 Leszek Koltunski
    mOITRenderDepthH        = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Depth");
480
    mOITRenderTexCorrH      = GLES30.glGetUniformLocation( oitRenderProgramH, "u_TexCorr");
481
    mOITRenderSizeH         = GLES30.glGetUniformLocation( oitRenderProgramH, "u_Size");
482 bfe45b4a Leszek Koltunski
    }
483
484
///////////////////////////////////////////////////////////////////////////////////////////////////
485
486 62c869ad Leszek Koltunski
  private static void displayNormals(float[] projection, MeshBase mesh)
487 bfe45b4a Leszek Koltunski
    {
488 d99fcc9c Leszek Koltunski
    if( mNormalProgram==null )
489
      {
490
      try
491
        {
492
        createNormalProgram(mResources);
493
        }
494
      catch(Exception ex)
495
        {
496
        mListener.distortedException(ex);
497
        return;
498
        }
499
      }
500
501 bfe45b4a Leszek Koltunski
    int num = mesh.getNumVertices();
502
    int tfo = mesh.getTFO();
503
504 62c869ad Leszek Koltunski
    GLES30.glUniform1i(DistortedLibrary.mTransformFeedbackH, 1);
505 b7074bc6 Leszek Koltunski
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
506
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
507 7602a827 Leszek Koltunski
    InternalRenderState.switchOffDrawing();
508 b7074bc6 Leszek Koltunski
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
509 7602a827 Leszek Koltunski
    InternalRenderState.restoreDrawing();
510 b7074bc6 Leszek Koltunski
    GLES30.glEndTransformFeedback();
511
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
512 bfe45b4a Leszek Koltunski
513 f046b159 Leszek Koltunski
    mNormalProgram.useProgram();
514 62c869ad Leszek Koltunski
    GLES30.glUniformMatrix4fv(mNormalProjectionH, 1, false, projection, 0);
515 f046b159 Leszek Koltunski
    mesh.bindTransformAttribs(mNormalProgram);
516 b7074bc6 Leszek Koltunski
    GLES30.glLineWidth(8.0f);
517
    GLES30.glDrawArrays(GLES30.GL_LINES, 0, 2*num);
518 bfe45b4a Leszek Koltunski
    }
519
520 f046b159 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
521 0bd9f644 Leszek Koltunski
/**
522
 * Execute all VertexEffects and adjust all vertices
523
 *
524
 * @y.exclude
525
 */
526 07206c71 Leszek Koltunski
  public static void adjustVertices(MeshBase mesh, EffectQueueVertex queue)
527 f046b159 Leszek Koltunski
    {
528 d99fcc9c Leszek Koltunski
    if( mFullProgram==null )
529 f046b159 Leszek Koltunski
      {
530 d99fcc9c Leszek Koltunski
      try
531
        {
532
        createFullProgram(mResources);
533
        }
534
      catch(Exception ex)
535
        {
536
        mListener.distortedException(ex);
537
        return;
538
        }
539 f046b159 Leszek Koltunski
      }
540 d99fcc9c Leszek Koltunski
541
    int num = mesh.getNumVertices();
542
    int tfo = mesh.getTFO();
543
544
    mFullProgram.useProgram();
545
    mesh.bindVertexAttribs(mFullProgram);
546
    queue.compute(1);
547
    queue.send(0.0f,3);
548 0bd9f644 Leszek Koltunski
    mesh.send(mFullProgramH);
549 d99fcc9c Leszek Koltunski
550
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tfo );
551
    GLES30.glBeginTransformFeedback( GLES30.GL_POINTS);
552
    InternalRenderState.switchOffDrawing();
553
    GLES30.glDrawArrays( GLES30.GL_POINTS, 0, num );
554
    InternalRenderState.restoreDrawing();
555
    GLES30.glEndTransformFeedback();
556
    mesh.copyTransformToVertex();
557
    GLES30.glBindBufferBase(GLES30.GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0);
558 f046b159 Leszek Koltunski
    }
559
560 bfe45b4a Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
561
562 c90aca24 Leszek Koltunski
  static void drawPrivOIT(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
563 bfe45b4a Leszek Koltunski
    {
564 06ddd60d Leszek Koltunski
    if( mMainOITProgram!=null )
565
      {
566
      EffectQueue[] queues = effects.getQueues();
567 c90aca24 Leszek Koltunski
568 06ddd60d Leszek Koltunski
      EffectQueue.compute(queues, currTime);
569
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
570 bfe45b4a Leszek Koltunski
571 06ddd60d Leszek Koltunski
      mMainOITProgram.useProgram();
572
      GLES30.glUniform1i(mMainOITTextureH, 0);
573
      GLES30.glUniform2ui(mMainOITSizeH, surface.mWidth, surface.mHeight);
574
      GLES30.glUniform1ui(mMainOITNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
575
      mesh.bindVertexAttribs(mMainOITProgram);
576 0bd9f644 Leszek Koltunski
      mesh.send(mMainOITProgramH);
577 bfe45b4a Leszek Koltunski
578 06ddd60d Leszek Koltunski
      float inflate     = mesh.getInflate();
579
      float distance    = surface.mDistance;
580
      float mipmap      = surface.mMipmap;
581
      float[] projection= surface.mProjectionMatrix;
582 bfe45b4a Leszek Koltunski
583 62c869ad Leszek Koltunski
      EffectQueue.send(queues, distance, mipmap, projection, inflate, 1 );
584 06ddd60d Leszek Koltunski
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
585 bfe45b4a Leszek Koltunski
586 06ddd60d Leszek Koltunski
      if( mesh.getShowNormals() )
587
        {
588
        mMainProgram.useProgram();
589 0bd9f644 Leszek Koltunski
        mesh.send(mMainProgramH);
590 62c869ad Leszek Koltunski
        EffectQueue.send(queues, distance, mipmap, projection, inflate, 0 );
591
        displayNormals(projection,mesh);
592 06ddd60d Leszek Koltunski
        }
593 bfe45b4a Leszek Koltunski
      }
594
    }
595
596
///////////////////////////////////////////////////////////////////////////////////////////////////
597
598 c90aca24 Leszek Koltunski
  static void drawPriv(DistortedEffects effects, MeshBase mesh, InternalOutputSurface surface, long currTime)
599 bfe45b4a Leszek Koltunski
    {
600 f046b159 Leszek Koltunski
    if( mMainProgram!=null )
601 f482efa3 Leszek Koltunski
      {
602
      EffectQueue[] queues = effects.getQueues();
603 bfe45b4a Leszek Koltunski
604 f482efa3 Leszek Koltunski
      EffectQueue.compute(queues, currTime);
605
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
606 46b572b5 Leszek Koltunski
607 f482efa3 Leszek Koltunski
      mMainProgram.useProgram();
608
      GLES30.glUniform1i(DistortedLibrary.mMainTextureH, 0);
609
      mesh.bindVertexAttribs(DistortedLibrary.mMainProgram);
610 0bd9f644 Leszek Koltunski
      mesh.send(mMainProgramH);
611 809dcae3 Leszek Koltunski
612 f482efa3 Leszek Koltunski
      float inflate     = mesh.getInflate();
613
      float distance    = surface.mDistance;
614
      float mipmap      = surface.mMipmap;
615
      float[] projection= surface.mProjectionMatrix;
616 809dcae3 Leszek Koltunski
617 62c869ad Leszek Koltunski
      EffectQueue.send(queues, distance, mipmap, projection, inflate, 0 );
618 f482efa3 Leszek Koltunski
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, mesh.getNumVertices() );
619 bfe45b4a Leszek Koltunski
620 62c869ad Leszek Koltunski
      if( mesh.getShowNormals() ) displayNormals(projection,mesh);
621 f482efa3 Leszek Koltunski
      }
622 bfe45b4a Leszek Koltunski
    }
623
624
///////////////////////////////////////////////////////////////////////////////////////////////////
625
626 7602a827 Leszek Koltunski
  static void blitPriv(InternalOutputSurface surface)
627 bfe45b4a Leszek Koltunski
    {
628 f482efa3 Leszek Koltunski
    if( mBlitProgram!=null )
629
      {
630
      mBlitProgram.useProgram();
631 bfe45b4a Leszek Koltunski
632 f482efa3 Leszek Koltunski
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
633
      GLES30.glUniform1i(mBlitTextureH, 0);
634
      GLES30.glUniform1f( mBlitDepthH , 1.0f-surface.mNear);
635
      GLES30.glVertexAttribPointer(mBlitProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
636
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
637
      }
638 bfe45b4a Leszek Koltunski
    }
639
640
///////////////////////////////////////////////////////////////////////////////////////////////////
641
642 7602a827 Leszek Koltunski
  static void blitDepthPriv(InternalOutputSurface surface, float corrW, float corrH)
643 bfe45b4a Leszek Koltunski
    {
644 f482efa3 Leszek Koltunski
    if( mBlitDepthProgram!=null )
645
      {
646
      mBlitDepthProgram.useProgram();
647
648
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
649
      GLES30.glUniform1i(mBlitDepthTextureH, 0);
650
      GLES30.glUniform1i(mBlitDepthDepthTextureH, 1);
651
      GLES30.glUniform2f(mBlitDepthTexCorrH, corrW, corrH );
652
      GLES30.glUniform1f( mBlitDepthDepthH , 1.0f-surface.mNear);
653
      GLES30.glVertexAttribPointer(mBlitDepthProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
654
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
655
      }
656 bfe45b4a Leszek Koltunski
    }
657
658
///////////////////////////////////////////////////////////////////////////////////////////////////
659 b7074bc6 Leszek Koltunski
// yes it is safe to be mixing 3.0 and 3.1 like that, senior members of the OpenGL discussions forum assert
660 bfe45b4a Leszek Koltunski
661
  private static int printPreviousBuffer()
662
    {
663
    int counter = 0;
664
665 b7074bc6 Leszek Koltunski
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
666
                                                                GLES30.GL_MAP_READ_BIT);
667 bfe45b4a Leszek Koltunski
    if( atomicBuf!=null )
668
      {
669
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
670
      counter = atomicIntBuf.get(0);
671
      }
672
    else
673
      {
674 b7074bc6 Leszek Koltunski
      Log.e("effects", "print: failed to map atomic buffer");
675 bfe45b4a Leszek Koltunski
      }
676
677 b7074bc6 Leszek Koltunski
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
678 bfe45b4a Leszek Koltunski
679
    return counter;
680
    }
681
682
///////////////////////////////////////////////////////////////////////////////////////////////////
683
684
  private static void zeroBuffer()
685
    {
686 b7074bc6 Leszek Koltunski
    ByteBuffer atomicBuf = (ByteBuffer)GLES30.glMapBufferRange( GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, 4,
687 fd836a41 Leszek Koltunski
                                                                GLES30.GL_MAP_WRITE_BIT|GLES30.GL_MAP_INVALIDATE_BUFFER_BIT);
688 bfe45b4a Leszek Koltunski
    if( atomicBuf!=null )
689
      {
690
      IntBuffer atomicIntBuf = atomicBuf.order(ByteOrder.nativeOrder()).asIntBuffer();
691
      atomicIntBuf.put(0,0);
692
      }
693
    else
694
      {
695 b7074bc6 Leszek Koltunski
      Log.e("effects", "zero: failed to map atomic buffer");
696 bfe45b4a Leszek Koltunski
      }
697
698 b7074bc6 Leszek Koltunski
    GLES30.glUnmapBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER);
699 bfe45b4a Leszek Koltunski
    }
700
701
///////////////////////////////////////////////////////////////////////////////////////////////////
702
// reset atomic counter to 0
703
704
  static int zeroOutAtomic()
705
    {
706
    int counter = 0;
707
708 5f35f1cb Leszek Koltunski
    if( mAtomicCounter==null )
709 bfe45b4a Leszek Koltunski
      {
710 5f35f1cb Leszek Koltunski
      mAtomicCounter = new int[mFBOQueueSize];
711
712
      GLES30.glGenBuffers(mFBOQueueSize,mAtomicCounter,0);
713 bfe45b4a Leszek Koltunski
714 5f35f1cb Leszek Koltunski
      for(int i=0; i<mFBOQueueSize; i++)
715 bfe45b4a Leszek Koltunski
        {
716 b7074bc6 Leszek Koltunski
        GLES30.glBindBuffer(GLES31.GL_ATOMIC_COUNTER_BUFFER, mAtomicCounter[i]);
717
        GLES30.glBufferData(GLES31.GL_ATOMIC_COUNTER_BUFFER, 4, null, GLES30.GL_DYNAMIC_DRAW);
718 bfe45b4a Leszek Koltunski
        zeroBuffer();
719
        }
720
      }
721
722
    // reading the value of the buffer on every frame would slow down rendering by
723 d99fcc9c Leszek Koltunski
    // about 3%; doing it only once every 5 frames affects speed by less than 1%.
724 bfe45b4a Leszek Koltunski
    if( mCurrBuffer==0 )
725
      {
726 b7074bc6 Leszek Koltunski
      GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
727 bfe45b4a Leszek Koltunski
      counter = printPreviousBuffer();
728
      }
729
730 5f35f1cb Leszek Koltunski
    if( ++mCurrBuffer>=mFBOQueueSize ) mCurrBuffer = 0;
731 bfe45b4a Leszek Koltunski
732 b7074bc6 Leszek Koltunski
    GLES30.glBindBufferBase(GLES31.GL_ATOMIC_COUNTER_BUFFER, 0, mAtomicCounter[mCurrBuffer]);
733 bfe45b4a Leszek Koltunski
    zeroBuffer();
734
735
    return counter;
736
    }
737
738
///////////////////////////////////////////////////////////////////////////////////////////////////
739 809dcae3 Leszek Koltunski
// Pass1 of the OIT algorithm. Clear per-pixel head-pointers.
740 bfe45b4a Leszek Koltunski
741 7602a827 Leszek Koltunski
  static void oitClear(InternalOutputSurface surface, int counter)
742 bfe45b4a Leszek Koltunski
    {
743 d99fcc9c Leszek Koltunski
    if( mOITClearProgram==null )
744 bfe45b4a Leszek Koltunski
      {
745 d99fcc9c Leszek Koltunski
      if( mGLSL>=310 && !mOITCompilationAttempted )
746 f482efa3 Leszek Koltunski
        {
747 d99fcc9c Leszek Koltunski
        mOITCompilationAttempted = true;
748 bfe45b4a Leszek Koltunski
749 d99fcc9c Leszek Koltunski
        try
750
          {
751
          createOITProgram(mResources);
752
          }
753
        catch(Exception ex)
754
          {
755
          mListener.distortedException(ex);
756
          return;
757
          }
758 f482efa3 Leszek Koltunski
        }
759 d99fcc9c Leszek Koltunski
      else
760 f482efa3 Leszek Koltunski
        {
761 d99fcc9c Leszek Koltunski
        return;
762 f482efa3 Leszek Koltunski
        }
763 d99fcc9c Leszek Koltunski
      }
764 bfe45b4a Leszek Koltunski
765 d99fcc9c Leszek Koltunski
    if( mLinkedListSSBO[0]<0 )
766
      {
767
      GLES30.glGenBuffers(1,mLinkedListSSBO,0);
768 bfe45b4a Leszek Koltunski
769 d99fcc9c Leszek Koltunski
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
770
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
771
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
772
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
773
774
      GLES30.glBindBufferBase(GLES31.GL_SHADER_STORAGE_BUFFER, 1, mLinkedListSSBO[0]);
775
      }
776
777
    // See if we have overflown the SSBO in one of the previous frames.
778
    // If yes, assume we need to make the SSBO larger.
779
    float overflow = counter/(mBufferSize*surface.mWidth*surface.mHeight);
780
781
    if( overflow>1.0f )
782
      {
783
      mBufferSize *= (int)(overflow+1.0f);
784
      int size = (int)(surface.mWidth*surface.mHeight*(3*mBufferSize+1)*4);
785
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, mLinkedListSSBO[0]);
786
      GLES30.glBufferData(GLES31.GL_SHADER_STORAGE_BUFFER, size, null, GLES30.GL_DYNAMIC_READ|GLES30.GL_DYNAMIC_DRAW);
787
      GLES30.glBindBuffer(GLES31.GL_SHADER_STORAGE_BUFFER, 0);
788 f482efa3 Leszek Koltunski
      }
789 d99fcc9c Leszek Koltunski
790
    mOITClearProgram.useProgram();
791
792
    GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
793
    GLES30.glUniform2f(mOITClearTexCorrH, 1.0f, 1.0f );   // corrections do not really matter here - only present because of common vertex shader.
794
    GLES30.glUniform1f( mOITClearDepthH , 1.0f);          // likewise depth
795
    GLES30.glUniform2ui(mOITClearSizeH, surface.mWidth, surface.mHeight);
796
    GLES30.glVertexAttribPointer(mOITClearProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
797
    GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
798 bfe45b4a Leszek Koltunski
    }
799
800
///////////////////////////////////////////////////////////////////////////////////////////////////
801
// Pass2 of the OIT algorithm - build per-pixel linked lists.
802
803 7602a827 Leszek Koltunski
  static void oitBuild(InternalOutputSurface surface, float corrW, float corrH)
804 bfe45b4a Leszek Koltunski
    {
805 f482efa3 Leszek Koltunski
    if( mOITBuildProgram!=null )
806
      {
807
      mOITBuildProgram.useProgram();
808
809
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
810
      GLES30.glUniform1i(mOITBuildTextureH, 0);
811
      GLES30.glUniform1i(mOITBuildDepthTextureH, 1);
812
      GLES30.glUniform2f(mOITBuildTexCorrH, corrW, corrH );
813
      GLES30.glUniform2ui(mOITBuildSizeH, surface.mWidth, surface.mHeight);
814
      GLES30.glUniform1ui(mOITBuildNumRecordsH, (int)(mBufferSize*surface.mWidth*surface.mHeight) );
815
      GLES30.glUniform1f(mOITBuildDepthH , 1.0f-surface.mNear);
816
      GLES30.glVertexAttribPointer(mOITBuildProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
817
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
818
      }
819 bfe45b4a Leszek Koltunski
    }
820
821
///////////////////////////////////////////////////////////////////////////////////////////////////
822
// Pass3 of the OIT algorithm. Cut occluded parts of the linked list.
823
824 7602a827 Leszek Koltunski
  static void oitCollapse(InternalOutputSurface surface, float corrW, float corrH)
825 bfe45b4a Leszek Koltunski
    {
826 f482efa3 Leszek Koltunski
    if( mOITCollapseProgram!=null )
827
      {
828
      mOITCollapseProgram.useProgram();
829
830
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
831
      GLES30.glUniform1i(mOITCollapseDepthTextureH, 1);
832
      GLES30.glUniform2f(mOITCollapseTexCorrH, corrW, corrH );
833
      GLES30.glUniform2ui(mOITCollapseSizeH, surface.mWidth, surface.mHeight);
834
      GLES30.glUniform1f( mOITCollapseDepthH , 1.0f-surface.mNear);
835
      GLES30.glVertexAttribPointer(mOITCollapseProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
836
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
837
      }
838 bfe45b4a Leszek Koltunski
    }
839
840
///////////////////////////////////////////////////////////////////////////////////////////////////
841
// Pass4 of the OIT algorithm. Render all the transparent pixels from the per-pixel linked lists.
842
843 7602a827 Leszek Koltunski
  static void oitRender(InternalOutputSurface surface, float corrW, float corrH)
844 bfe45b4a Leszek Koltunski
    {
845 f482efa3 Leszek Koltunski
    if( mOITRenderProgram!=null )
846
      {
847
      mOITRenderProgram.useProgram();
848
849
      GLES30.glViewport(0, 0, surface.mWidth, surface.mHeight );
850
      GLES30.glUniform2f(mOITRenderTexCorrH, corrW, corrH );
851
      GLES30.glUniform2ui(mOITRenderSizeH, surface.mWidth, surface.mHeight);
852
      GLES30.glUniform1f( mOITRenderDepthH , 1.0f-surface.mNear);
853
      GLES30.glVertexAttribPointer(mOITRenderProgram.mAttribute[0], 2, GLES30.GL_FLOAT, false, 0, mQuadPositions);
854
      GLES30.glDrawArrays(GLES30.GL_TRIANGLE_STRIP, 0, 4);
855
      }
856 bfe45b4a Leszek Koltunski
    }
857
858
///////////////////////////////////////////////////////////////////////////////////////////////////
859
860
  static void setSSBOSize(float size)
861
    {
862
    mBufferSize = size;
863
    }
864
865 5f35f1cb Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
866
867
  static int getQueueSize()
868
    {
869
    return mFBOQueueSize;
870
    }
871
872 edea9cf3 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
873
// ARM Mali driver r12 has problems when we keep swapping many FBOs (fixed in r22)
874 b7074bc6 Leszek Koltunski
// PowerVR GE8100 / GE8300 compiler fails to compile OIT programs.
875 edea9cf3 Leszek Koltunski
876 5f35f1cb Leszek Koltunski
  private static void detectBuggyDriversAndSetQueueSize(int queueSize)
877 edea9cf3 Leszek Koltunski
    {
878 b7074bc6 Leszek Koltunski
    String vendor  = GLES30.glGetString(GLES30.GL_VENDOR);
879
    String version = GLES30.glGetString(GLES30.GL_VERSION);
880
    String renderer= GLES30.glGetString(GLES30.GL_RENDERER);
881 edea9cf3 Leszek Koltunski
882 5f35f1cb Leszek Koltunski
    mFBOQueueSize = 1;
883 edea9cf3 Leszek Koltunski
884
    if( vendor.contains("ARM") )
885
      {
886 5f35f1cb Leszek Koltunski
      try
887 edea9cf3 Leszek Koltunski
        {
888 5f35f1cb Leszek Koltunski
        String regex = ".*r(\\d+)p\\d.*";
889
        Pattern pattern = Pattern.compile(regex);
890
        Matcher matcher = pattern.matcher(version);
891
892
        if( matcher.find() )
893
          {
894
          String driverVersion = matcher.group(1);
895
896
          if( driverVersion!=null )
897
            {
898
            int drvVersion = Integer.parseInt(driverVersion);
899
900
            if( drvVersion<22 )
901
              {
902
              Log.e("DISTORTED", "You are running this on a ARM Mali driver r"+driverVersion+".\n" +
903
                    "This is a buggy driver, please update to r22. Inserting workaround which uses a lot of memory.");
904
905
              mFBOQueueSize = queueSize;
906
              }
907
            }
908
          }
909
        }
910
      catch(Exception ex)
911
        {
912
        android.util.Log.e("library", "exception trying to pattern match version: "+ex.toString());
913 edea9cf3 Leszek Koltunski
        }
914
      }
915
    else if( vendor.contains("Imagination") )
916
      {
917
      if( renderer.contains("GE8") )
918
        {
919 b7074bc6 Leszek Koltunski
        Log.e("DISTORTED", "You are running this on a PowerVR GE8XXX.\nDue to a buggy compiler OIT rendering will not work");
920 a79650a2 Leszek Koltunski
        Log.e("DISTORTED", "GLSL Version "+GLES30.glGetString(GLES31.GL_SHADING_LANGUAGE_VERSION));
921 edea9cf3 Leszek Koltunski
        }
922
      }
923
    }
924
925 b7074bc6 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
926
/**
927
 * Return OpenGL ES version supported by the hardware we are running on.
928 60fdf71d Leszek Koltunski
 * There are only three possibilities: 300 (OpenGL ES 3.0) or 310 (at least OpenGL ES 3.1)
929
 * or 200 (OpenGL ES 2.0)
930 b7074bc6 Leszek Koltunski
 */
931 60fdf71d Leszek Koltunski
  public static int getGLSL()
932 b7074bc6 Leszek Koltunski
    {
933
    return mGLSL;
934
    }
935
936 421c2728 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
937 310e14fb leszek
/**
938
 * Have we called onCreate yet, ie have we initialized the library?
939 1dfc9074 leszek
 * @return <code>true</code> if the library is initialized and ready for action.
940 310e14fb leszek
 */
941
  public static boolean isInitialized()
942 421c2728 Leszek Koltunski
    {
943 55c14a19 Leszek Koltunski
    return mInitialized;
944 421c2728 Leszek Koltunski
    }
945
946 6a06a912 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
947
/**
948 c43abe6c Leszek Koltunski
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
949 432442f9 Leszek Koltunski
 * I.e. best called from GLSurfaceView.onCreate().
950 6a06a912 Leszek Koltunski
 * <p>
951 432442f9 Leszek Koltunski
 * Needs to be called from a thread holding the OpenGL context.
952 5f35f1cb Leszek Koltunski
 *
953 015642fb Leszek Koltunski
 * @param context Context of the App using the library - used to open up Resources and read Shader code.
954 d99fcc9c Leszek Koltunski
 * @param listener The library will send all (asynchronous!) exceptions there.
955 6a06a912 Leszek Koltunski
 */
956 d99fcc9c Leszek Koltunski
  public static void onCreate(final Context context, final ExceptionListener listener)
957 5f35f1cb Leszek Koltunski
    {
958 d99fcc9c Leszek Koltunski
    onCreate(context,listener,4);
959 5f35f1cb Leszek Koltunski
    }
960
961
///////////////////////////////////////////////////////////////////////////////////////////////////
962
/**
963
 * When OpenGL context gets created, call this method so that the library can initialise its internal data structures.
964
 * I.e. best called from GLSurfaceView.onCreate().
965
 * <p>
966
 * Needs to be called from a thread holding the OpenGL context.
967
 *   
968
 * @param context Context of the App using the library - used to open up Resources and read Shader code.
969 d99fcc9c Leszek Koltunski
 * @param listener The library will send all (asynchronous!) exceptions there.
970 5f35f1cb Leszek Koltunski
 * @param queueSize the size of the FBO queue, a workaround for the bug on Mali drivers.
971
 */
972 d99fcc9c Leszek Koltunski
  public static void onCreate(final Context context, final ExceptionListener listener, int queueSize)
973 d6e94c84 Leszek Koltunski
    {
974 30beb34f Leszek Koltunski
    final ActivityManager activityManager     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
975
    final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
976 b7074bc6 Leszek Koltunski
977
    int glESversion = configurationInfo.reqGlEsVersion;
978
    int major = glESversion >> 16;
979
    int minor = glESversion & 0xff;
980
981 d99fcc9c Leszek Koltunski
    mListener = listener;
982
983 b7074bc6 Leszek Koltunski
    if( major< 3 )
984
      {
985
      mGLSL = 100*major + 10*minor;
986 d99fcc9c Leszek Koltunski
      VertexCompilationException ex = new VertexCompilationException("at least OpenGL ES 3.0 required, this device supports only "+major+"."+minor);
987
      mListener.distortedException(ex);
988 b7074bc6 Leszek Koltunski
      }
989
    else
990
      {
991
      mGLSL = (major==3 && minor==0) ? 300 : 310;
992
      }
993
994
    android.util.Log.e("DISTORTED", "Using OpenGL ES "+major+"."+minor);
995
    mGLSL_VERSION = "#version "+mGLSL+" es\n";
996 edea9cf3 Leszek Koltunski
997
    mInitialized = true;
998 d99fcc9c Leszek Koltunski
    mOITCompilationAttempted = false;
999 edea9cf3 Leszek Koltunski
1000 5f35f1cb Leszek Koltunski
    detectBuggyDriversAndSetQueueSize(queueSize);
1001 edea9cf3 Leszek Koltunski
1002 0e924ba5 Leszek Koltunski
    EffectMessageSender.startSending();
1003
1004 d99fcc9c Leszek Koltunski
    mResources = context.getResources();
1005 edea9cf3 Leszek Koltunski
1006
    try
1007
      {
1008 d99fcc9c Leszek Koltunski
      createMainProgram();
1009 edea9cf3 Leszek Koltunski
      }
1010
    catch(Exception ex)
1011
      {
1012 d99fcc9c Leszek Koltunski
      mListener.distortedException(ex);
1013 edea9cf3 Leszek Koltunski
      }
1014
1015 f046b159 Leszek Koltunski
    try
1016
      {
1017 d99fcc9c Leszek Koltunski
      EffectQueuePostprocess.createPrograms(mResources, mGLSL);
1018 f046b159 Leszek Koltunski
      }
1019
    catch(Exception ex)
1020
      {
1021 d99fcc9c Leszek Koltunski
      mListener.distortedException(ex);
1022 a13dde77 Leszek Koltunski
      }
1023
1024 edea9cf3 Leszek Koltunski
    try
1025
      {
1026 b7074bc6 Leszek Koltunski
      PostprocessEffect.createPrograms(mGLSL);
1027 edea9cf3 Leszek Koltunski
      }
1028
    catch(Exception ex)
1029
      {
1030 d99fcc9c Leszek Koltunski
      mListener.distortedException(ex);
1031 edea9cf3 Leszek Koltunski
      }
1032 6a06a912 Leszek Koltunski
    }
1033
1034 05ecc6fe Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
1035
/**
1036 78e89fb5 Leszek Koltunski
 * Call this so that the Library can release the OpenGL related data that needs to be recreated.
1037 05ecc6fe Leszek Koltunski
 * Must be called from Activity.onPause().
1038
 */
1039
  public static void onPause()
1040
    {
1041 7602a827 Leszek Koltunski
    InternalObject.onPause();
1042 0273ef2a Leszek Koltunski
    Dynamic.onPause();
1043 bfe45b4a Leszek Koltunski
    mLinkedListSSBO[0]= -1;
1044 5f35f1cb Leszek Koltunski
    mAtomicCounter = null;
1045 fd836a41 Leszek Koltunski
1046
    mFullProgram        = null;
1047
    mNormalProgram      = null;
1048
    mOITRenderProgram   = null;
1049
    mOITCollapseProgram = null;
1050
    mOITBuildProgram    = null;
1051
    mOITClearProgram    = null;
1052 05ecc6fe Leszek Koltunski
    }
1053
1054 6a06a912 Leszek Koltunski
///////////////////////////////////////////////////////////////////////////////////////////////////
1055
/**
1056
 * Call this so that the Library can release its internal data structures.
1057
 * Must be called from Activity.onDestroy(). 
1058
 */
1059
  public static void onDestroy()
1060
    {
1061 7602a827 Leszek Koltunski
    InternalObject.onDestroy();
1062
    InternalNodeData.onDestroy();
1063
    InternalMaster.onDestroy();
1064
    InternalOutputSurface.onDestroy();
1065 46b572b5 Leszek Koltunski
    DistortedEffects.onDestroy();
1066 42571056 Leszek Koltunski
    EffectQueue.onDestroy();
1067 26a4e5f6 leszek
    Effect.onDestroy();
1068 07206c71 Leszek Koltunski
    DeferredJobs.onDestroy();
1069 6a06a912 Leszek Koltunski
    EffectMessageSender.stopSending();
1070 f8686932 Leszek Koltunski
1071 55c14a19 Leszek Koltunski
    mInitialized = false;
1072 d99fcc9c Leszek Koltunski
    mOITCompilationAttempted = false;
1073
1074
    mNormalProgram     = null;
1075
    mMainOITProgram    = null;
1076
    mMainProgram       = null;
1077
    mFullProgram       = null;
1078
    mOITClearProgram   = null;
1079
    mOITBuildProgram   = null;
1080
    mOITCollapseProgram= null;
1081
    mOITRenderProgram  = null;
1082
    mBlitDepthProgram  = null;
1083
    mBlitProgram       = null;
1084 6a06a912 Leszek Koltunski
    }
1085 bfe45b4a Leszek Koltunski
1086
///////////////////////////////////////////////////////////////////////////////////////////////////
1087
/**
1088
 * Returns the maximum number of effects of a given type that can be simultaneously applied to a
1089
 * single (InputSurface,MeshBase) combo.
1090
 *
1091
 * @param type {@link EffectType}
1092
 * @return The maximum number of effects of a given type.
1093
 */
1094
  @SuppressWarnings("unused")
1095
  public static int getMax(EffectType type)
1096
    {
1097
    return EffectQueue.getMax(type.ordinal());
1098
    }
1099
1100
///////////////////////////////////////////////////////////////////////////////////////////////////
1101
/**
1102
 * Sets the maximum number of effects that can be stored in a single EffectQueue at one time.
1103
 * This can fail if:
1104
 * <ul>
1105
 * <li>the value of 'max' is outside permitted range (0 &le; max &le; Byte.MAX_VALUE)
1106
 * <li>We try to increase the value of 'max' when it is too late to do so already. It needs to be called
1107 7602a827 Leszek Koltunski
 *     before the Vertex Shader gets compiled, i.e. before the call to {@link DistortedLibrary#onCreate}. After this
1108 bfe45b4a Leszek Koltunski
 *     time only decreasing the value of 'max' is permitted.
1109
 * <li>Furthermore, this needs to be called before any instances of the DistortedEffects class get created.
1110
 * </ul>
1111
 *
1112
 * @param type {@link EffectType}
1113
 * @param max new maximum number of simultaneous effects. Has to be a non-negative number not greater
1114
 *            than Byte.MAX_VALUE
1115
 * @return <code>true</code> if operation was successful, <code>false</code> otherwise.
1116
 */
1117
  @SuppressWarnings("unused")
1118
  public static boolean setMax(EffectType type, int max)
1119
    {
1120
    return EffectQueue.setMax(type.ordinal(),max);
1121
    }
1122 f8f6d457 leszek
  }