Project

General

Profile

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

library / src / main / java / org / distorted / library / main / InternalOutputSurface.java @ 40f0cea6

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2016 Leszek Koltunski  leszek@koltunski.pl                                          //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// This library is free software; you can redistribute it and/or                                 //
7
// modify it under the terms of the GNU Lesser General Public                                    //
8
// License as published by the Free Software Foundation; either                                  //
9
// version 2.1 of the License, or (at your option) any later version.                            //
10
//                                                                                               //
11
// This library 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 GNU                             //
14
// Lesser General Public License for more details.                                               //
15
//                                                                                               //
16
// You should have received a copy of the GNU Lesser General Public                              //
17
// License along with this library; if not, write to the Free Software                           //
18
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA                //
19
///////////////////////////////////////////////////////////////////////////////////////////////////
20

    
21
package org.distorted.library.main;
22

    
23
import android.opengl.GLES30;
24
import android.opengl.GLES31;
25
import android.opengl.Matrix;
26

    
27
import org.distorted.library.effect.EffectQuality;
28
import org.distorted.library.effectqueue.EffectQueuePostprocess;
29
import org.distorted.library.mesh.MeshBase;
30

    
31
///////////////////////////////////////////////////////////////////////////////////////////////////
32
/**
33
 * This is not really part of the public API.
34
 *
35
 * @y.exclude
36
 */
37
public abstract class InternalOutputSurface extends InternalSurface implements InternalChildrenList.Parent
38
{
39
  public static final int NO_DEPTH_NO_STENCIL = 0;
40
  public static final int DEPTH_NO_STENCIL    = 1;
41
  public static final int BOTH_DEPTH_STENCIL  = 2;
42

    
43
  static final float DEFAULT_FOV = 60.0f;
44
  static final float DEFAULT_NEAR=  0.1f;
45

    
46
  private float mFOV;
47
  private final int mTmpFBO;
48

    
49
  private long[] mTime;
50
  private float mClearR, mClearG, mClearB, mClearA, mClearDepth;
51
  private int mClear, mClearStencil;
52
  private boolean mRenderWayOIT;
53
  private final InternalChildrenList mChildren;
54

    
55
  // Global buffers used for postprocessing
56
  private final static DistortedFramebuffer[] mBuffer= new DistortedFramebuffer[EffectQuality.LENGTH];
57
  private final boolean[] mBufferInitialized;
58

    
59
  float mDistance, mNear, mMipmap;
60
  float[] mProjectionMatrix;
61
  int mDepthStencilCreated, mDepthStencil;
62
  int[] mDepthStencilH, mFBOH;
63
  int mRealWidth;   // the Surface can be backed up by a texture larger than the viewport we have to it.
64
  int mRealHeight;  // mWidth,mHeight are the sizes of the Viewport, those - sizes of the backing up texture.
65
  int mCurrFBO;     // internal current FBO (see DistortedLibrary.FBO_QUEUE_SIZE)
66
  int mWidth, mHeight;
67

    
68
///////////////////////////////////////////////////////////////////////////////////////////////////
69

    
70
  InternalOutputSurface(int width, int height, int createColor, int numfbos, int numcolors, int depthStencil, int fbo, int type, int storage)
71
    {
72
    super(createColor,numfbos,numcolors,type,storage);
73

    
74
    mRenderWayOIT = false;
75
    mCurrFBO      = 0;
76

    
77
    mRealWidth = mWidth = width;
78
    mRealHeight= mHeight= height;
79

    
80
    mProjectionMatrix = new float[16];
81

    
82
    mFOV = DEFAULT_FOV;
83
    mNear= DEFAULT_NEAR;
84

    
85
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
86
    mDepthStencil = depthStencil;
87

    
88
    mClearR = 0.0f;
89
    mClearG = 0.0f;
90
    mClearB = 0.0f;
91
    mClearA = 0.0f;
92

    
93
    mClearDepth = 1.0f;
94
    mClearStencil = 0;
95
    mClear = GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT;
96

    
97
    mMipmap = 1.0f;
98

    
99
    mChildren = new InternalChildrenList(this);
100

    
101
    mTmpFBO = fbo;
102

    
103
    mFBOH = new int[10];  // Crashlytics shows the library occasionally crashing in setAsOutput()
104
    mTime = new long[10]; // when trying to read from 'null array' mFBOH. Probably sometimes a
105
                          // a Framebuffer gets created in the wrong moment, just after we did a
106
                          // round of create(), but before we start rendering.
107
                          // Create an empty FBO and Time here so that setAsOutput() is always safe to call.
108

    
109
    mBufferInitialized = new boolean[EffectQuality.LENGTH];
110

    
111
    allocateStuffDependantOnNumFBOS();
112
    createProjection();
113
    }
114

    
115
///////////////////////////////////////////////////////////////////////////////////////////////////
116

    
117
  void allocateStuffDependantOnNumFBOS()
118
    {
119
    if( mNumFBOs>0 )
120
      {
121
      mDepthStencilH   = new int[mNumFBOs];
122
      mDepthStencilH[0]= 0;
123

    
124
      mFBOH   = new int[mNumFBOs];
125
      mFBOH[0]= mTmpFBO;
126

    
127
      mTime = new long[mNumFBOs];
128
      for(int i=0; i<mNumFBOs;i++) mTime[i]=0;
129
      }
130
    }
131

    
132
///////////////////////////////////////////////////////////////////////////////////////////////////
133

    
134
  private void createProjection()
135
    {
136
    if( mWidth>0 && mHeight>1 )
137
      {
138
      if( mFOV>0.0f )  // perspective projection
139
        {
140
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
141
        float q = mWidth*mNear;
142
        float c = mHeight*mNear;
143

    
144
        float left   = -q/2;
145
        float right  = +q/2;
146
        float bottom = -c/2;
147
        float top    = +c/2;
148
        float near   =  c/a;
149

    
150
        mDistance    = mHeight/a;
151
        float far    = 2*mDistance-near;
152

    
153
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
154
        }
155
      else             // parallel projection
156
        {
157
        float left   = -mWidth/2.0f;
158
        float right  = +mWidth/2.0f;
159
        float bottom = -mHeight/2.0f;
160
        float top    = +mHeight/2.0f;
161
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
162
        mDistance    = mWidth+mHeight;
163
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
164

    
165
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
166
        }
167
      }
168
    }
169

    
170
///////////////////////////////////////////////////////////////////////////////////////////////////
171

    
172
  private static void createPostprocessingBuffers(int quality, int width, int height, float near)
173
    {
174
    final float CLEAR_R = 1.0f;
175
    final float CLEAR_G = 1.0f;
176
    final float CLEAR_B = 1.0f;
177
    final float CLEAR_A = 0.0f;
178
    final float CLEAR_D = 1.0f;
179
    final int   CLEAR_S = 0;
180

    
181
    final int queueSize = DistortedLibrary.getQueueSize();
182
    float mipmap=1.0f;
183

    
184
    for (int j=0; j<quality; j++) mipmap *= EffectQuality.MULTIPLIER;
185

    
186
    mBuffer[quality] = new DistortedFramebuffer(queueSize,2,BOTH_DEPTH_STENCIL,TYPE_SYST, STORAGE_COMMON, (int)(width*mipmap), (int)(height*mipmap) );
187
    mBuffer[quality].mMipmap = mipmap;
188
    mBuffer[quality].mNear = near;  // copy mNear as well (for blitting- see PostprocessEffect.apply() )
189
    mBuffer[quality].glClearColor(CLEAR_R, CLEAR_G, CLEAR_B, CLEAR_A);
190

    
191
    InternalStackFrameList.toDo(); // create the FBOs immediately. This is safe as we must be holding the OpenGL context now.
192

    
193
    InternalRenderState.colorDepthStencilOn();
194
    GLES30.glClearColor(CLEAR_R, CLEAR_G, CLEAR_B, CLEAR_A);
195
    GLES30.glClearDepthf(CLEAR_D);
196
    GLES30.glClearStencil(CLEAR_S);
197

    
198
    for(int k=0; k<queueSize; k++)
199
      {
200
      GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mBuffer[quality].mFBOH[k]);
201
      GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mBuffer[quality].mColorH[2*k+1], 0);
202
      GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT | GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_STENCIL_BUFFER_BIT);
203
      GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mBuffer[quality].mColorH[2*k  ], 0);
204
      GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
205
      }
206

    
207
    InternalRenderState.colorDepthStencilRestore();
208

    
209
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0);
210
    }
211

    
212
///////////////////////////////////////////////////////////////////////////////////////////////////
213

    
214
  static synchronized void onPause()
215
    {
216
    for (int j=0; j<EffectQuality.LENGTH; j++)
217
      if( mBuffer[j]!=null )
218
        {
219
        mBuffer[j].markForDeletion();
220
        mBuffer[j] = null;
221
        }
222
    }
223

    
224
///////////////////////////////////////////////////////////////////////////////////////////////////
225

    
226
  private int blitWithDepth(long currTime, InternalOutputSurface buffer, int fbo)
227
    {
228
    GLES30.glViewport(0, 0, mWidth, mHeight);
229
    setAsOutput(currTime);
230
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
231
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
232
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
233
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
234

    
235
    GLES30.glDisable(GLES30.GL_STENCIL_TEST);
236
    GLES30.glStencilMask(0x00);
237

    
238
    DistortedLibrary.blitDepthPriv(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
239
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
240
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
241
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
242
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
243

    
244
    // clear buffers
245
    GLES30.glStencilMask(0xff);
246
    GLES30.glDepthMask(true);
247
    GLES30.glColorMask(true,true,true,true);
248
    GLES30.glClearColor(buffer.mClearR,buffer.mClearG,buffer.mClearB,buffer.mClearA);
249
    GLES30.glClearDepthf(buffer.mClearDepth);
250
    GLES30.glClearStencil(buffer.mClearStencil);
251

    
252
    buffer.setAsOutput();
253
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, buffer.mColorH[2*fbo+1], 0);
254
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT|GLES30.GL_DEPTH_BUFFER_BIT|GLES30.GL_STENCIL_BUFFER_BIT);
255
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, buffer.mColorH[2*fbo  ], 0);
256
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
257

    
258
    return 1;
259
    }
260

    
261
///////////////////////////////////////////////////////////////////////////////////////////////////
262

    
263
  private static void oitClear(InternalOutputSurface buffer)
264
    {
265
    int counter = DistortedLibrary.zeroOutAtomic();
266
    DistortedLibrary.oitClear(buffer,counter);
267
    GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT|GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
268
    }
269

    
270
///////////////////////////////////////////////////////////////////////////////////////////////////
271

    
272
  private int oitBuild(long time, InternalOutputSurface buffer, int fbo)
273
    {
274
    GLES30.glViewport(0, 0, mWidth, mHeight);
275
    setAsOutput(time);
276
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
277
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
278
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
279
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
280

    
281
    InternalRenderState.colorDepthStencilOn();
282
    InternalRenderState.enableDepthTest();
283

    
284
    DistortedLibrary.oitBuild(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
285
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
286
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
287
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
288
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
289

    
290
    InternalRenderState.colorDepthStencilRestore();
291
    InternalRenderState.restoreDepthTest();
292

    
293
    return 1;
294
    }
295

    
296
///////////////////////////////////////////////////////////////////////////////////////////////////
297
// two phases: 1. collapse the SSBO 2. blend the ssbo's color
298

    
299
  private int oitRender(long currTime, int fbo)
300
    {
301
    float corrW = getWidthCorrection();
302
    float corrH = getHeightCorrection();
303

    
304
    // Do the Collapse Pass only if we do have a Depth attachment.
305
    // Otherwise there's no point (in fact we then would create a feedback loop!)
306

    
307
    if( mDepthStencilH[fbo] != 0 )
308
      {
309
      GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0);
310
      GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
311
      GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, mDepthStencilH[fbo]);
312
      InternalRenderState.switchOffColorDepthStencil();
313
      DistortedLibrary.oitCollapse(this, corrW, corrH);
314
      GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
315
      }
316

    
317
    setAsOutput(currTime);
318
    InternalRenderState.switchColorDepthOnStencilOff();
319
    DistortedLibrary.oitRender(this, corrW, corrH);
320
    InternalRenderState.restoreColorDepthStencil();
321

    
322
    return 1;
323
    }
324

    
325
///////////////////////////////////////////////////////////////////////////////////////////////////
326

    
327
  private void clear()
328
    {
329
    InternalRenderState.colorDepthStencilOn();
330
    GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
331
    GLES30.glClearDepthf(mClearDepth);
332
    GLES30.glClearStencil(mClearStencil);
333
    GLES30.glClear(mClear);
334
    InternalRenderState.colorDepthStencilRestore();
335
    }
336

    
337
///////////////////////////////////////////////////////////////////////////////////////////////////
338

    
339
  void setCurrFBO(int fbo)
340
    {
341
    mCurrFBO = fbo;
342
    }
343

    
344
///////////////////////////////////////////////////////////////////////////////////////////////////
345
// Render all children from the current bucket to the buffer, apply the postprocessing once to the
346
// whole buffer (queue.postprocess) and merge it to 'this' (oitBuild or blitWithDepth depending on
347
// the type of rendering)
348

    
349
  private int accumulateAndBlit(EffectQueuePostprocess queue, InternalChildrenList children, DistortedFramebuffer buffer,
350
                                int begIndex, int endIndex, boolean isFinal, long time, int fbo, boolean oit )
351
    {
352
    int numRenders = 0;
353

    
354
    for(int j=begIndex; j<endIndex; j++)
355
       {
356
       DistortedNode node = children.getChild(j);
357

    
358
       if( node.getSurface().setAsInput() )
359
         {
360
         buffer.setAsOutput();
361
         numRenders += queue.preprocess( buffer, node, buffer.mDistance, buffer.mMipmap, buffer.mProjectionMatrix );
362
         }
363
       }
364
    numRenders += queue.postprocess(buffer);
365

    
366
    if( oit )
367
      {
368
      numRenders += oitBuild(time, buffer, fbo);
369
      GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
370
      buffer.clearBuffer(fbo);
371
      }
372
    else
373
      {
374
      numRenders += blitWithDepth(time, buffer, fbo);
375
      if( !isFinal ) buffer.clearBuffer(fbo);
376
      }
377

    
378
    return numRenders;
379
    }
380

    
381
///////////////////////////////////////////////////////////////////////////////////////////////////
382

    
383
  private int renderChildToThisOrToBuffer(DistortedNode child, DistortedFramebuffer buffer, long time, boolean oit, boolean toThis)
384
    {
385
    int numRenders;
386

    
387
    if( toThis )
388
      {
389
      setAsOutput(time);
390

    
391
      if( oit )
392
        {
393
        numRenders = child.drawOIT(time, this);
394
        GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
395
        }
396
      else
397
        {
398
        numRenders = child.draw(time, this);
399
        }
400
      }
401
    else
402
      {
403
      buffer.setAsOutput(time);
404
      numRenders = child.drawNoBlend(time, buffer);
405
      }
406

    
407
    return numRenders;
408
    }
409

    
410
///////////////////////////////////////////////////////////////////////////////////////////////////
411
// The postprocessing buffers mBuffer[] are generally speaking too large (there's just one static
412
// set of them) so before we use them for output, we need to adjust the Viewport as if they were
413
// smaller. That takes care of outputting pixels to them. When we use them as input, we have to
414
// adjust the texture coords - see the get{Width|Height}Correction functions.
415
//
416
// Also, adjust the Buffers so their Projection is the same like the surface we are supposed to be
417
// rendering to.
418

    
419
  private void clonePostprocessingViewportAndProjection(InternalOutputSurface surface, InternalOutputSurface from)
420
    {
421
    if( surface.mWidth != from.mWidth || surface.mHeight != from.mHeight ||
422
        surface.mFOV   != from.mFOV   || surface.mNear   != from.mNear    )
423
      {
424
      surface.mWidth  = (int)(from.mWidth *surface.mMipmap);
425
      surface.mHeight = (int)(from.mHeight*surface.mMipmap);
426
      surface.mFOV    = from.mFOV;
427
      surface.mNear   = from.mNear;  // Near plane is independent of the mipmap level
428

    
429
      surface.createProjection();
430

    
431
      int maxw = Math.max(surface.mWidth , surface.mRealWidth );
432
      int maxh = Math.max(surface.mHeight, surface.mRealHeight);
433

    
434
      if (maxw > surface.mRealWidth || maxh > surface.mRealHeight)
435
        {
436
        surface.mRealWidth = maxw;
437
        surface.mRealHeight = maxh;
438

    
439
        surface.recreate();
440
        surface.create();
441
        }
442
      }
443
    }
444

    
445
///////////////////////////////////////////////////////////////////////////////////////////////////
446

    
447
  private DistortedFramebuffer initializeBuffer(EffectQueuePostprocess queue, int fbo )
448
    {
449
    int currQuality = queue.getQuality();
450
    if( mBuffer[currQuality]==null ) createPostprocessingBuffers(currQuality, mWidth, mHeight, mNear);
451
    mBuffer[currQuality].setCurrFBO(fbo);
452

    
453
    if( !mBufferInitialized[currQuality] )
454
      {
455
      mBufferInitialized[currQuality] = true;
456
      clonePostprocessingViewportAndProjection(mBuffer[currQuality],this);
457
      }
458

    
459
    return mBuffer[currQuality];
460
    }
461

    
462
///////////////////////////////////////////////////////////////////////////////////////////////////
463
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
464
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
465
// to a whole buffer (lastQueue.postprocess) and merge it (this.oitBuild or blitWithDepth - depending
466
// on the type of rendering)
467

    
468
  int renderChildren(long time, int numChildren, InternalChildrenList children, int fbo, boolean oit)
469
    {
470
    int numRenders=0, bucketChange=0;
471
    DistortedNode child;
472
    DistortedFramebuffer buffer=null;
473
    EffectQueuePostprocess lastQueue=null, currQueue;
474
    long lastBucket=0, currBucket;
475
    boolean toThis=false;
476

    
477
    setCurrFBO(fbo);
478
    if( numChildren==0 ) setAsOutput(time);
479
    if( oit && numChildren>0 ) oitClear(this);
480
    for(int i=0; i<EffectQuality.LENGTH; i++) mBufferInitialized[i]=false;
481

    
482
    for(int i=0; i<numChildren; i++)
483
      {
484
      child = children.getChild(i);
485
      currQueue = (EffectQueuePostprocess)child.getEffects().getQueues()[3];
486
      currBucket= currQueue.getID();
487

    
488
      if( currBucket!=0 && lastBucket!=currBucket )
489
        {
490
        buffer = initializeBuffer(currQueue,fbo);
491
        if( lastBucket!=0 ) numRenders += accumulateAndBlit(lastQueue,children,buffer,bucketChange,i,false,time,fbo,oit);
492
        bucketChange= i;
493
        toThis = currQueue.getRenderDirectly();
494
        }
495
      numRenders += renderChildToThisOrToBuffer(child,buffer,time,oit,currBucket==0 || toThis);
496
      if( currBucket!=0 && i==numChildren-1 ) numRenders += accumulateAndBlit(currQueue,children,buffer,bucketChange,numChildren,true,time,fbo,oit);
497

    
498
      lastQueue = currQueue;
499
      lastBucket= currBucket;
500
      }
501

    
502
    if( oit && numChildren>0 ) numRenders += oitRender(time, fbo);  // merge the OIT linked list
503

    
504
    return numRenders;
505
    }
506

    
507
///////////////////////////////////////////////////////////////////////////////////////////////////
508
/**
509
 * Not part of the public API.
510
 *
511
 * @y.exclude
512
 */
513
  public void adjustIsomorphism() { }
514

    
515
///////////////////////////////////////////////////////////////////////////////////////////////////
516
/**
517
 * Not part of the Public API.
518
 *
519
 * @y.exclude
520
 */
521
  public float getWidthCorrection()
522
    {
523
    return (float)mWidth/mRealWidth;
524
    }
525

    
526
///////////////////////////////////////////////////////////////////////////////////////////////////
527
/**
528
 * Not part of the Public API.
529
 *
530
 * @y.exclude
531
 */
532
  public float getHeightCorrection()
533
    {
534
    return (float)mHeight/mRealHeight;
535
    }
536

    
537
///////////////////////////////////////////////////////////////////////////////////////////////////
538

    
539
  void clearBuffer(int fbo)
540
    {
541
    InternalRenderState.colorDepthStencilOn();
542

    
543
    GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
544
    GLES30.glClearDepthf(mClearDepth);
545
    GLES30.glClearStencil(mClearStencil);
546

    
547
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[fbo]);
548
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mColorH[2*fbo+1], 0);
549
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT|GLES30.GL_DEPTH_BUFFER_BIT|GLES30.GL_STENCIL_BUFFER_BIT);
550
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mColorH[2*fbo  ], 0);
551
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
552

    
553
    InternalRenderState.colorDepthStencilRestore();
554
    }
555

    
556
///////////////////////////////////////////////////////////////////////////////////////////////////
557

    
558
  void setAsOutput(long time)
559
    {
560
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[mCurrFBO]);
561

    
562
    if( mTime[mCurrFBO]!=time )
563
      {
564
      mTime[mCurrFBO] = time;
565
      clear();
566
      }
567
    }
568

    
569
///////////////////////////////////////////////////////////////////////////////////////////////////
570
// PUBLIC API
571
///////////////////////////////////////////////////////////////////////////////////////////////////
572
/**
573
 * Draws all the attached children to this OutputSurface's 0th FBO.
574
 * <p>
575
 * Must be called from a thread holding OpenGL Context.
576
 *
577
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
578
 * @return Number of objects rendered.
579
 */
580
  public int render(long time)
581
    {
582
    return render(time,0);
583
    }
584

    
585
///////////////////////////////////////////////////////////////////////////////////////////////////
586
/**
587
 * Draws all the attached children to this OutputSurface.
588
 * <p>
589
 * Must be called from a thread holding OpenGL Context.
590
 *
591
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
592
 * @param fbo The surface can have many FBOs backing it up - render this to FBO number 'fbo'.
593
 * @return Number of objects rendered.
594
 */
595
  public int render(long time, int fbo)
596
    {
597
    InternalMaster.toDo();
598
    InternalStackFrameList.toDo();
599
    InternalRenderState.reset();
600

    
601
    int numRenders=0, numChildren = mChildren.getNumChildren();
602
    DistortedNode node;
603
    long oldBucket=0, newBucket;
604

    
605
    for(int i=0; i<numChildren; i++)
606
      {
607
      node = mChildren.getChild(i);
608
      newBucket = node.getBucket();
609
      numRenders += node.renderRecursive(time);
610
      if( newBucket<oldBucket ) mChildren.rearrangeByBuckets(i,newBucket);
611
      else oldBucket=newBucket;
612
      }
613

    
614
    numRenders += renderChildren(time,numChildren,mChildren,fbo, mRenderWayOIT);
615

    
616
    return numRenders;
617
    }
618

    
619
///////////////////////////////////////////////////////////////////////////////////////////////////
620
/**
621
 * Recursively print all the effect queues attached to the children Nodes and to this Node.
622
 */
623
  public void debug()
624
    {
625
    int numChildren = mChildren.getNumChildren();
626

    
627
    for(int i=0; i<numChildren; i++)
628
      {
629
      DistortedNode node = mChildren.getChild(i);
630
      node.debug(0);
631
      }
632
    }
633

    
634
///////////////////////////////////////////////////////////////////////////////////////////////////
635
/**
636
 * Bind this Surface as a Framebuffer we can render to.
637
 * <p>
638
 * This version does not attempt to clear anything.
639
 */
640
  public void setAsOutput()
641
    {
642
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[mCurrFBO]);
643
    }
644

    
645
///////////////////////////////////////////////////////////////////////////////////////////////////
646
/**
647
 * Return the Near plane of the Projection included in the Surface.
648
 *
649
 * @return the Near plane.
650
 */
651
  public float getNear()
652
    {
653
    return mNear;
654
    }
655

    
656
///////////////////////////////////////////////////////////////////////////////////////////////////
657
/**
658
 * Set mipmap level.
659
 * <p>
660
 * Trick for speeding up your renders - one can create a pyramid of OutputSurface objects, each next
661
 * one some constant FACTOR smaller than the previous (0.5 is the common value), then set the Mipmap
662
 * Level of the i-th object to be FACTOR^i (we start counting from 0). When rendering any scene into
663
 * such prepared OutputSurface, the library will make sure to scale any Effects used so that the end
664
 * scene will end up looking identical no matter which object we render to. Identical, that is, except
665
 * for the loss of quality and gain in speed associated with rendering to a smaller Surface.
666
 * <p>
667
 * Example: if you create two FBOs, one 1000x1000 and another 500x500 in size, and set the second one
668
 * mipmap to 0.5 (the first one's is 1.0 by default), define Effects to be a single move by (100,100),
669
 * and render a skinned Mesh into both FBO, the end result will look proportionally the same, because
670
 * in the second case the move vector (100,100) will be auto-scaled to (50,50).
671
 *
672
 * @param mipmap The mipmap level. Acceptable range: 0&lt;mipmap&lt;infinity, although mipmap&gt;1
673
 *               does not make any sense (that would result in loss of speed and no gain in quality)
674
 */
675
  public void setMipmap(float mipmap)
676
    {
677
    mMipmap = mipmap;
678
    }
679

    
680
///////////////////////////////////////////////////////////////////////////////////////////////////
681
/**
682
 * Set the (R,G,B,A) values of GLES31.glClearColor() to set up color with which to clear
683
 * this Surface at the beginning of each frame.
684
 *
685
 * @param r the Red component. Default: 0.0f
686
 * @param g the Green component. Default: 0.0f
687
 * @param b the Blue component. Default: 0.0f
688
 * @param a the Alpha component. Default: 0.0f
689
 */
690
  public void glClearColor(float r, float g, float b, float a)
691
    {
692
    mClearR = r;
693
    mClearG = g;
694
    mClearB = b;
695
    mClearA = a;
696
    }
697

    
698
///////////////////////////////////////////////////////////////////////////////////////////////////
699
/**
700
 * Uses glClearDepthf() to set up a value with which to clear
701
 * the Depth buffer of our Surface at the beginning of each frame.
702
 *
703
 * @param d the Depth. Default: 1.0f
704
 */
705
  public void glClearDepthf(float d)
706
    {
707
    mClearDepth = d;
708
    }
709

    
710
///////////////////////////////////////////////////////////////////////////////////////////////////
711
/**
712
 * Uses glClearStencil() to set up a value with which to clear the
713
 * Stencil buffer of our Surface at the beginning of each frame.
714
 *
715
 * @param s the Stencil. Default: 0
716
 */
717
  public void glClearStencil(int s)
718
    {
719
    mClearStencil = s;
720
    }
721

    
722
///////////////////////////////////////////////////////////////////////////////////////////////////
723
/**
724
 * Which buffers to Clear at the beginning of each frame?
725
 * <p>
726
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
727
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
728
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
729
 *
730
 * @param mask bitwise OR of BUFFER_BITs to clear.
731
 */
732
  public void glClear(int mask)
733
    {
734
    mClear = mask;
735
    }
736

    
737
///////////////////////////////////////////////////////////////////////////////////////////////////
738
/**
739
 * Create new Projection matrix.
740
 *
741
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
742
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
743
 * @param near The Near plane.
744
 */
745
  public void setProjection(float fov, float near)
746
    {
747
    if( fov < 180.0f && fov >=0.0f )
748
      {
749
      mFOV = fov;
750
      }
751

    
752
    if( near<   1.0f && near> 0.0f )
753
      {
754
      mNear= near;
755
      }
756
    else if( near<=0.0f )
757
      {
758
      mNear = 0.01f;
759
      }
760
    else if( near>=1.0f )
761
      {
762
      mNear=0.99f;
763
      }
764

    
765
    for(int j=0; j<EffectQuality.LENGTH; j++)
766
      {
767
      if( mBuffer[j]!=null ) mBuffer[j].mNear = mNear;
768
      }
769

    
770
    createProjection();
771
    }
772

    
773
///////////////////////////////////////////////////////////////////////////////////////////////////
774
/**
775
 * Return the vertical field of view angle.
776
 *
777
 * @return Vertival Field of View Angle, in degrees.
778
 */
779
  public float getFOV()
780
    {
781
    return mFOV;
782
    }
783

    
784
///////////////////////////////////////////////////////////////////////////////////////////////////
785
/**
786
 * Resize the underlying Framebuffer.
787
 * <p>
788
 * This method can be safely called mid-render as it doesn't interfere with rendering.
789
 *
790
 * @param width The new width.
791
 * @param height The new height.
792
 */
793
  public void resize(int width, int height)
794
    {
795
    if( mWidth!=width || mHeight!=height )
796
      {
797
      mWidth = mRealWidth = width;
798
      mHeight= mRealHeight= height;
799

    
800
      createProjection();
801

    
802
      if( mColorCreated==CREATED )
803
        {
804
        markForCreation();
805
        recreate();
806
        }
807
      }
808
    }
809

    
810
///////////////////////////////////////////////////////////////////////////////////////////////////
811
/**
812
 * Return true if the Surface contains a DEPTH attachment.
813
 *
814
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
815
 */
816
  public boolean hasDepth()
817
    {
818
    return mDepthStencilCreated==CREATED;
819
    }
820

    
821
///////////////////////////////////////////////////////////////////////////////////////////////////
822
/**
823
 * Return true if the Surface contains a STENCIL attachment.
824
 *
825
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
826
 */
827
  public boolean hasStencil()
828
    {
829
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
830
    }
831

    
832
///////////////////////////////////////////////////////////////////////////////////////////////////
833
/**
834
 * When rendering this Node, should we use the Order Independent Transparency render mode?
835
 * <p>
836
 * This feature requires OpenGL ES 3.1. If we are running on OpenGL 3.0, this will do nothing.
837
 * Also, if you are running on a buggy driver ( Imagination GE8100/8300 driver build 1.8@4490469 )
838
 * then do nothing.
839
 *
840
 * There are two modes of rendering: the fast 'normal' way, which however renders transparent
841
 * fragments in different ways depending on which fragments get rendered first, or the slower
842
 * 'oit' way, which renders transparent fragments correctly regardless of their order.
843
 *
844
 * @param oit True if we want to render more slowly, but in a way which accounts for transparency.
845
 */
846
  public void setOrderIndependentTransparency(boolean oit)
847
    {
848
    if( DistortedLibrary.getGLSL()>=310 )
849
      {
850
      mRenderWayOIT = oit;
851
      }
852
    }
853

    
854
///////////////////////////////////////////////////////////////////////////////////////////////////
855
/**
856
 * When rendering this Node, should we use the Order Independent Transparency render mode?
857
 * <p>
858
 * This feature requires OpenGL ES 3.1. If we are running on OpenGL 3.0, this will do nothing.
859
 * Also, if you are running on a buggy driver ( Imagination GE8100/8300 driver build 1.8@4490469 )
860
 * then do nothing.
861
 *
862
 * There are two modes of rendering: the fast 'normal' way, which however renders transparent
863
 * fragments in different ways depending on which fragments get rendered first, or the slower
864
 * 'oit' way, which renders transparent fragments correctly regardless of their order.
865
 *
866
 * @param oit True if we want to render more slowly, but in a way which accounts for transparency.
867
 * @param initialSize Initial number of transparent fragments we expect, in screenfuls.
868
 *                    I.e '1.0' means 'the scene we are going to render contains dialog_about 1 screen
869
 *                    worth of transparent fragments'. Valid values: 0.0 &lt; initialSize &lt; 10.0
870
 *                    Even if you get this wrong, the library will detect that there are more
871
 *                    transparent fragments than it has space for and readjust its internal buffers,
872
 *                    but only after a few frames during which one will probably see missing objects.
873
 */
874
  public void setOrderIndependentTransparency(boolean oit, float initialSize)
875
    {
876
    if( DistortedLibrary.getGLSL()>=310 )
877
      {
878
      mRenderWayOIT = oit;
879

    
880
      if( initialSize>0.0f && initialSize<10.0f )
881
        {
882
        DistortedLibrary.setSSBOSize(initialSize);
883
        }
884
      }
885
    }
886

    
887
///////////////////////////////////////////////////////////////////////////////////////////////////
888
/**
889
 * Adds a new child to the last position in the list of our Surface's children.
890
 * <p>
891
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
892
 * InternalMaster (by calling doWork())
893
 *
894
 * @param node The new Node to add.
895
 */
896
  public void attach(DistortedNode node)
897
    {
898
    mChildren.attach(node);
899
    }
900

    
901
///////////////////////////////////////////////////////////////////////////////////////////////////
902
/**
903
 * Adds a new child to the last position in the list of our Surface's children.
904
 * <p>
905
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
906
 * InternalMaster (by calling doWork())
907
 *
908
 * @param surface InputSurface to initialize our child Node with.
909
 * @param effects DistortedEffects to initialize our child Node with.
910
 * @param mesh MeshBase to initialize our child Node with.
911
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
912
 */
913
  public DistortedNode attach(InternalSurface surface, DistortedEffects effects, MeshBase mesh)
914
    {
915
    return mChildren.attach(surface,effects,mesh);
916
    }
917

    
918
///////////////////////////////////////////////////////////////////////////////////////////////////
919
/**
920
 * Removes the first occurrence of a specified child from the list of children of our Surface.
921
 * <p>
922
 * A bit questionable method as there can be many different Nodes attached as children, some
923
 * of them having the same Effects but - for instance - different Mesh. Use with care.
924
 * <p>
925
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
926
 * InternalMaster (by calling doWork())
927
 *
928
 * @param effects DistortedEffects to remove.
929
 */
930
  public void detach(DistortedEffects effects)
931
    {
932
    mChildren.detach(effects);
933
    }
934

    
935
///////////////////////////////////////////////////////////////////////////////////////////////////
936
/**
937
 * Removes the first occurrence of a specified child from the list of children of our Surface.
938
 * <p>
939
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
940
 * InternalMaster (by calling doWork())
941
 *
942
 * @param node The Node to remove.
943
 */
944
  public void detach(DistortedNode node)
945
    {
946
    mChildren.detach(node);
947
    }
948

    
949
///////////////////////////////////////////////////////////////////////////////////////////////////
950
/**
951
 * Removes all children Nodes.
952
 * <p>
953
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
954
 * InternalMaster (by calling doWork())
955
 */
956
  public void detachAll()
957
    {
958
    mChildren.detachAll();
959
    }
960

    
961
///////////////////////////////////////////////////////////////////////////////////////////////////
962
/**
963
 * Return the width of this Surface.
964
 *
965
 * @return width of the Object, in pixels.
966
 */
967
  public int getWidth()
968
    {
969
    return mWidth;
970
    }
971

    
972
///////////////////////////////////////////////////////////////////////////////////////////////////
973
/**
974
 * Return the height of this Surface.
975
 *
976
 * @return height of the Object, in pixels.
977
 */
978
  public int getHeight()
979
    {
980
    return mHeight;
981
    }
982
}
(12-12/17)