Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedOutputSurface.java @ 715e7726

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2016 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// Distorted is free software: you can redistribute it and/or modify                             //
7
// it under the terms of the GNU General Public License as published by                          //
8
// the Free Software Foundation, either version 2 of the License, or                             //
9
// (at your option) any later version.                                                           //
10
//                                                                                               //
11
// Distorted is distributed in the hope that it will be useful,                                  //
12
// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
13
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
14
// GNU General Public License for more details.                                                  //
15
//                                                                                               //
16
// You should have received a copy of the GNU General Public License                             //
17
// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
18
///////////////////////////////////////////////////////////////////////////////////////////////////
19

    
20
package org.distorted.library.main;
21

    
22
import android.opengl.GLES31;
23
import android.opengl.Matrix;
24

    
25
import org.distorted.library.effect.EffectQuality;
26
import org.distorted.library.mesh.MeshBase;
27

    
28
import java.util.ArrayList;
29

    
30
///////////////////////////////////////////////////////////////////////////////////////////////////
31
/**
32
 * This is not really part of the public API.
33
 *
34
 * @y.exclude
35
 */
36
public abstract class DistortedOutputSurface extends DistortedSurface implements DistortedMaster.Slave
37
{
38
/**
39
 * Do not create DEPTH or STENCIL attachment
40
 */
41
  public static final int NO_DEPTH_NO_STENCIL = 0;
42
/**
43
 * Create DEPTH, but not STENCIL
44
 */
45
  public static final int DEPTH_NO_STENCIL    = 1;
46
/**
47
 * Create both DEPTH and STENCIL
48
 */
49
  public static final int BOTH_DEPTH_STENCIL  = 2;
50

    
51
  private static final int ATTACH = 0;
52
  private static final int DETACH = 1;
53
  private static final int DETALL = 2;
54
  private static final int SORT   = 3;
55

    
56
  private ArrayList<DistortedNode> mChildren;
57
  private int mNumChildren;   // ==mChildren.length(), but we only create mChildren if the first one gets added
58
  private boolean mRenderWayOIT;
59

    
60
  private class Job
61
    {
62
    int type;
63
    DistortedNode node;
64

    
65
    Job(int t, DistortedNode n)
66
      {
67
      type = t;
68
      node = n;
69
      }
70
    }
71

    
72
  private ArrayList<Job> mJobs = new ArrayList<>();
73

    
74
  // Global buffers used for postprocessing.
75
  private static DistortedFramebuffer[] mBuffer=null;
76

    
77
  float mFOV;
78
  float mDistance, mNear;
79
  float[] mProjectionMatrix;
80

    
81
  int mDepthStencilCreated;
82
  int mDepthStencil;
83
  int[] mDepthStencilH;
84
  int[] mFBOH;
85
  private long[] mTime;
86

    
87
  private float mClearR, mClearG, mClearB, mClearA;
88
  private float mClearDepth;
89
  private int mClearStencil;
90
  private int mClear;
91
  float mMipmap;
92

    
93
  int mRealWidth;   // the Surface can be backed up with a texture that is
94
  int mRealHeight;  // larger than the viewport we have to it.
95
                    // mWidth,mHeight are the sizes of the Viewport, those -
96
                    // sizes of the backing up texture.
97

    
98
  int mCurrFBO;     // internal current FBO (see Distorted.FBO_QUEUE_SIZE)
99

    
100
///////////////////////////////////////////////////////////////////////////////////////////////////
101

    
102
  DistortedOutputSurface(int width, int height, int createColor, int numfbos, int numcolors, int depthStencil, int fbo, int type)
103
    {
104
    super(width,height,createColor,numfbos,numcolors,type);
105

    
106
    mRenderWayOIT = false;
107
    mCurrFBO      = 0;
108

    
109
    mDepthStencilH = new int[numfbos];
110
    mFBOH          = new int[numfbos];
111

    
112
    mTime = new long[numfbos];
113
    for(int i=0; i<mNumFBOs;i++) mTime[i]=0;
114

    
115
    mRealWidth = width;
116
    mRealHeight= height;
117

    
118
    mProjectionMatrix = new float[16];
119

    
120
    mFOV = 60.0f;
121
    mNear=  0.5f;
122

    
123
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
124
    mDepthStencil = depthStencil;
125

    
126
    mFBOH[0]         = fbo;
127
    mDepthStencilH[0]= 0;
128

    
129
    mClearR = 0.0f;
130
    mClearG = 0.0f;
131
    mClearB = 0.0f;
132
    mClearA = 0.0f;
133

    
134
    mClearDepth = 1.0f;
135
    mClearStencil = 0;
136
    mClear = GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_COLOR_BUFFER_BIT;
137

    
138
    mMipmap = 1.0f;
139

    
140
    createProjection();
141
    }
142

    
143
///////////////////////////////////////////////////////////////////////////////////////////////////
144

    
145
  private void createProjection()
146
    {
147
    if( mWidth>0 && mHeight>1 )
148
      {
149
      if( mFOV>0.0f )  // perspective projection
150
        {
151
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
152
        float q = mWidth*mNear;
153
        float c = mHeight*mNear;
154

    
155
        float left   = -q/2;
156
        float right  = +q/2;
157
        float bottom = -c/2;
158
        float top    = +c/2;
159
        float near   =  c/a;
160

    
161
        mDistance    = mHeight/a;
162
        float far    = 2*mDistance-near;
163

    
164
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
165
        }
166
      else             // parallel projection
167
        {
168
        float left   = -mWidth/2.0f;
169
        float right  = +mWidth/2.0f;
170
        float bottom = -mHeight/2.0f;
171
        float top    = +mHeight/2.0f;
172
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
173
        mDistance    = mWidth+mHeight;
174
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
175

    
176
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
177
        }
178
      }
179
    }
180

    
181
///////////////////////////////////////////////////////////////////////////////////////////////////
182

    
183
  private static void createPostprocessingBuffers(int width, int height, float near)
184
    {
185
    mBuffer = new DistortedFramebuffer[EffectQuality.LENGTH];
186
    float mipmap=1.0f;
187

    
188
    for (int j=0; j<EffectQuality.LENGTH; j++)
189
      {
190
      mBuffer[j] = new DistortedFramebuffer(Distorted.FBO_QUEUE_SIZE,2,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(width*mipmap), (int)(height*mipmap) );
191
      mBuffer[j].mMipmap = mipmap;
192
      mBuffer[j].mNear = near;  // copy mNear as well (for blitting- see PostprocessEffect.apply() )
193
      mBuffer[j].glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
194

    
195
      mipmap *= EffectQuality.MULTIPLIER;
196
      }
197

    
198
    DistortedObject.toDo(); // create the FBOs immediately. This is safe as we must be holding the OpenGL context now.
199

    
200
    GLES31.glStencilMask(0xff);
201
    GLES31.glDepthMask(true);
202
    GLES31.glColorMask(true, true, true, true);
203
    GLES31.glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
204
    GLES31.glClearDepthf(1.0f);
205
    GLES31.glClearStencil(0);
206

    
207
    for (int j=0; j<EffectQuality.LENGTH; j++)
208
      {
209
      for(int k=0; k<Distorted.FBO_QUEUE_SIZE; k++)
210
        {
211
        GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mBuffer[j].mFBOH[k]);
212
        GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[2*k+1], 0);
213
        GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT | GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_STENCIL_BUFFER_BIT);
214
        GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[2*k  ], 0);
215
        GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
216
        }
217
      }
218

    
219
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, 0);
220
    }
221

    
222
///////////////////////////////////////////////////////////////////////////////////////////////////
223

    
224
  static synchronized void onDestroy()
225
    {
226
    if( mBuffer!=null )
227
      {
228
      for (int j = 0; j < EffectQuality.LENGTH; j++)
229
        {
230
        mBuffer[j] = null;
231
        }
232

    
233
      mBuffer = null;
234
      }
235
    }
236

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

    
246
  private static void clonePostprocessingViewportAndProjection(DistortedOutputSurface from)
247
    {
248
    if( mBuffer[0].mWidth != from.mWidth || mBuffer[0].mHeight != from.mHeight ||
249
        mBuffer[0].mFOV   != from.mFOV   || mBuffer[0].mNear   != from.mNear    )
250
      {
251
      DistortedOutputSurface surface;
252

    
253
      for(int i=0; i<EffectQuality.LENGTH; i++)
254
        {
255
        surface = mBuffer[i];
256

    
257
        surface.mWidth  = (int)(from.mWidth *surface.mMipmap);
258
        surface.mHeight = (int)(from.mHeight*surface.mMipmap);
259
        surface.mFOV    = from.mFOV;
260
        surface.mNear   = from.mNear;  // Near plane is independent of the mipmap level
261

    
262
        surface.createProjection();
263

    
264
        int maxw = surface.mWidth  > surface.mRealWidth  ? surface.mWidth  : surface.mRealWidth;
265
        int maxh = surface.mHeight > surface.mRealHeight ? surface.mHeight : surface.mRealHeight;
266

    
267
        if (maxw > surface.mRealWidth || maxh > surface.mRealHeight)
268
          {
269
          surface.mRealWidth = maxw;
270
          surface.mRealHeight = maxh;
271

    
272
          surface.recreate();
273
          surface.create();
274
          }
275
        }
276
      }
277
    }
278

    
279
///////////////////////////////////////////////////////////////////////////////////////////////////
280

    
281
  private int blitWithDepth(long currTime, DistortedOutputSurface buffer,int fbo)
282
    {
283
    GLES31.glViewport(0, 0, mWidth, mHeight);
284
    setAsOutput(currTime);
285
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
286
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
287
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
288
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
289

    
290
    GLES31.glDisable(GLES31.GL_STENCIL_TEST);
291
    GLES31.glStencilMask(0x00);
292

    
293
    DistortedEffects.blitDepthPriv(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
294
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
295
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
296
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
297
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
298

    
299
    // clear buffers
300
    GLES31.glStencilMask(0xff);
301
    GLES31.glDepthMask(true);
302
    GLES31.glColorMask(true,true,true,true);
303
    GLES31.glClearColor(0.0f,0.0f,0.0f,0.0f);
304
    GLES31.glClearDepthf(1.0f);
305
    GLES31.glClearStencil(0);
306

    
307
    buffer.setAsOutput();
308
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo+1], 0);
309
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
310
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo  ], 0);
311
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
312

    
313
    return 1;
314
    }
315

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

    
318
  private static void oitClear(DistortedOutputSurface buffer)
319
    {
320
    int counter = DistortedEffects.zeroOutAtomic();
321
    DistortedEffects.oitClear(buffer,counter);
322
    GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT|GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
323
    }
324

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

    
327
  private int oitBuild(long time, DistortedOutputSurface buffer, int fbo)
328
    {
329
    GLES31.glViewport(0, 0, mWidth, mHeight);
330
    setAsOutput(time);
331
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
332
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
333
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
334
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
335

    
336
    DistortedRenderState.colorDepthStencilOn();
337
    DistortedRenderState.enableDepthTest();
338

    
339
    DistortedEffects.oitBuild(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
340
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
341
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
342
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
343
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
344

    
345
    DistortedRenderState.colorDepthStencilRestore();
346
    DistortedRenderState.restoreDepthTest();
347

    
348
    return 1;
349
    }
350

    
351
///////////////////////////////////////////////////////////////////////////////////////////////////
352
// two phases: 1. collapse the SSBO 2. blend the ssbo's color
353

    
354
  private int oitRender(long currTime, int fbo)
355
    {
356
    float corrW = getWidthCorrection();
357
    float corrH = getHeightCorrection();
358

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

    
362
    if( mDepthStencilH[fbo] != 0 )
363
      {
364
      GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, 0);
365
      GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
366
      GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, mDepthStencilH[fbo]);
367
      DistortedRenderState.switchOffColorDepthStencil();
368
      DistortedEffects.oitCollapse(this, corrW, corrH);
369
      GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
370
      }
371

    
372
    setAsOutput(currTime);
373
    DistortedRenderState.switchColorDepthOnStencilOff();
374
    DistortedEffects.oitRender(this, corrW, corrH);
375
    DistortedRenderState.restoreColorDepthStencil();
376

    
377
    return 1;
378
    }
379

    
380
///////////////////////////////////////////////////////////////////////////////////////////////////
381

    
382
  void clear()
383
    {
384
    DistortedRenderState.colorDepthStencilOn();
385
    GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
386
    GLES31.glClearDepthf(mClearDepth);
387
    GLES31.glClearStencil(mClearStencil);
388
    GLES31.glClear(mClear);
389
    DistortedRenderState.colorDepthStencilRestore();
390
    }
391

    
392
///////////////////////////////////////////////////////////////////////////////////////////////////
393

    
394
  void setCurrFBO(int fbo)
395
    {
396
    mCurrFBO = fbo;
397
    }
398

    
399
///////////////////////////////////////////////////////////////////////////////////////////////////
400
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
401
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
402
// to a whole buffer (lastQueue.postprocess) and merge it (this.oitBuild).
403

    
404
  int renderChildren(long time, int numChildren, ArrayList<DistortedNode> children, int fbo, boolean oit)
405
    {
406
    int quality=0, numRenders=0, bucketChange=0;
407
    DistortedNode child;
408
    EffectQueuePostprocess lastQueue=null, currQueue;
409
    long lastBucket=0, currBucket;
410
    boolean renderDirectly=false;
411

    
412
    setCurrFBO(fbo);
413

    
414
    if( mBuffer!=null )
415
      {
416
      for (int i=0; i<EffectQuality.LENGTH; i++) mBuffer[i].setCurrFBO(fbo);
417
      }
418

    
419
    if( oit && numChildren>0 )
420
      {
421
      oitClear(this);
422
      }
423

    
424
    for(int i=0; i<numChildren; i++)
425
      {
426
      child = children.get(i);
427
      currQueue = child.getPostprocessQueue();
428
      currBucket= currQueue.getID();
429

    
430
      if( currBucket==0 )
431
        {
432
        setAsOutput(time);
433

    
434
        if( oit )
435
          {
436
          numRenders += child.drawOIT(time, this);
437
          GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
438
          }
439
        else
440
          {
441
          numRenders += child.draw(time, this);
442
          }
443
        }
444
      else
445
        {
446
        if( mBuffer==null )
447
          {
448
          createPostprocessingBuffers(mWidth,mHeight,mNear);
449
          for (int j=0; j<EffectQuality.LENGTH; j++) mBuffer[j].setCurrFBO(fbo);
450
          }
451

    
452
        if( lastBucket!=currBucket )
453
          {
454
          if( lastBucket==0 )
455
            {
456
            clonePostprocessingViewportAndProjection(this);
457
            }
458
          else
459
            {
460
            for(int j=bucketChange; j<i; j++) numRenders += lastQueue.preprocess( mBuffer[quality],children.get(j) );
461
            numRenders += lastQueue.postprocess(mBuffer[quality]);
462

    
463
            if( oit )
464
              {
465
              numRenders += oitBuild(time, mBuffer[quality], fbo);
466
              GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
467
              }
468
            else
469
              {
470
              numRenders += blitWithDepth(time, mBuffer[quality],fbo);
471
              }
472
            mBuffer[quality].clearBuffer(fbo);
473
            }
474

    
475
          quality= currQueue.getQuality();
476
          bucketChange= i;
477
          renderDirectly = currQueue.getRender();
478
          }
479

    
480
        if( renderDirectly )
481
          {
482
          setAsOutput(time);
483

    
484
          if( oit )
485
            {
486
            numRenders += child.drawOIT(time, this);
487
            GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
488
            }
489
          else
490
            {
491
            numRenders += child.draw(time, this);
492
            }
493
          }
494
        else
495
          {
496
          mBuffer[quality].setAsOutput(time);
497
          child.drawNoBlend(time, mBuffer[quality]);
498
          }
499

    
500
        if( i==numChildren-1 )
501
          {
502
          for(int j=bucketChange; j<numChildren; j++) numRenders += currQueue.preprocess( mBuffer[quality],children.get(j) );
503
          numRenders += currQueue.postprocess(mBuffer[quality]);
504

    
505
          if( oit )
506
            {
507
            numRenders += oitBuild(time, mBuffer[quality], fbo);
508
            GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
509
            mBuffer[quality].clearBuffer(fbo);
510
            }
511
          else
512
            {
513
            numRenders += blitWithDepth(time, mBuffer[quality],fbo);
514
            }
515
          }
516
        } // end else (postprocessed child)
517

    
518
      lastQueue = currQueue;
519
      lastBucket= currBucket;
520
      } // end main for loop
521

    
522
    if( oit && numChildren>0 )
523
      {
524
      numRenders += oitRender(time, fbo);  // merge the OIT linked list
525
      }
526

    
527
    return numRenders;
528
    }
529

    
530
///////////////////////////////////////////////////////////////////////////////////////////////////
531

    
532
  ArrayList<DistortedNode> getChildren()
533
    {
534
    return mChildren;
535
    }
536

    
537
///////////////////////////////////////////////////////////////////////////////////////////////////
538
/**
539
 * Not part of the Public API.
540
 *
541
 * @y.exclude
542
 */
543
  public float getWidthCorrection()
544
    {
545
    return (float)mWidth/mRealWidth;
546
    }
547

    
548
///////////////////////////////////////////////////////////////////////////////////////////////////
549
/**
550
 * Not part of the Public API.
551
 *
552
 * @y.exclude
553
 */
554
  public float getHeightCorrection()
555
    {
556
    return (float)mHeight/mRealHeight;
557
    }
558

    
559
///////////////////////////////////////////////////////////////////////////////////////////////////
560

    
561
  void clearBuffer(int fbo)
562
    {
563
    DistortedRenderState.colorDepthStencilOn();
564

    
565
    GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
566
    GLES31.glClearDepthf(mClearDepth);
567
    GLES31.glClearStencil(mClearStencil);
568

    
569
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[fbo]);
570
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mColorH[2*fbo+1], 0);
571
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
572
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mColorH[2*fbo  ], 0);
573
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
574

    
575
    DistortedRenderState.colorDepthStencilRestore();
576
    }
577

    
578
///////////////////////////////////////////////////////////////////////////////////////////////////
579
// PUBLIC API
580
///////////////////////////////////////////////////////////////////////////////////////////////////
581
/**
582
 * Draws all the attached children to this OutputSurface's 0th FBO.
583
 * <p>
584
 * Must be called from a thread holding OpenGL Context.
585
 *
586
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
587
 * @return Number of objects rendered.
588
 */
589
  public int render(long time)
590
    {
591
    return render(time,0);
592
    }
593

    
594
///////////////////////////////////////////////////////////////////////////////////////////////////
595
/**
596
 * Draws all the attached children to this OutputSurface.
597
 * <p>
598
 * Must be called from a thread holding OpenGL Context.
599
 *
600
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
601
 * @param fbo The surface can have many FBOs backing it up - render this to FBO number 'fbo'.
602
 * @return Number of objects rendered.
603
 */
604
  public int render(long time, int fbo)
605
    {
606
    // change tree topology (attach and detach children)
607
/*
608
    boolean changed1 =
609
*/
610
    DistortedMaster.toDo();
611
/*
612
    if( changed1 )
613
      {
614
      for(int i=0; i<mNumChildren; i++)
615
        {
616
        mChildren.get(i).debug(0);
617
        }
618

    
619
      DistortedNode.debugMap();
620
      }
621
*/
622
    // create and delete all underlying OpenGL resources
623
    // Watch out: FIRST change topology, only then deal
624
    // with OpenGL resources. That's because changing Tree
625
    // can result in additional Framebuffers that would need
626
    // to be created immediately, before the calls to drawRecursive()
627
/*
628
    boolean changed2 =
629
*/
630
    toDo();
631
/*
632
    if( changed2 )
633
      {
634
      DistortedObject.debugLists();
635
      }
636
*/
637
    // mark OpenGL state as unknown
638
    DistortedRenderState.reset();
639

    
640
    int numRenders=0;
641

    
642
    for(int i=0; i<mNumChildren; i++)
643
      {
644
      numRenders += mChildren.get(i).renderRecursive(time);
645
      }
646

    
647
    numRenders += renderChildren(time,mNumChildren,mChildren,fbo, mRenderWayOIT);
648

    
649
    return numRenders;
650
    }
651

    
652
///////////////////////////////////////////////////////////////////////////////////////////////////
653
/**
654
 * Bind this Surface as a Framebuffer we can render to.
655
 *
656
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
657
 *             out if this is the first time during present frame that this FBO is being set as output.
658
 *             If so, the library, in addition to binding the Surface for output, also clears the
659
 *             Surface's color and depth attachments.
660
 */
661
  public void setAsOutput(long time)
662
    {
663
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[mCurrFBO]);
664

    
665
    if( mTime[mCurrFBO]!=time )
666
      {
667
      mTime[mCurrFBO] = time;
668
      clear();
669
      }
670
    }
671

    
672
///////////////////////////////////////////////////////////////////////////////////////////////////
673
/**
674
 * Bind this Surface as a Framebuffer we can render to.
675
 * <p>
676
 * This version does not attempt to clear anything.
677
 */
678
  public void setAsOutput()
679
    {
680
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[mCurrFBO]);
681
    }
682

    
683
///////////////////////////////////////////////////////////////////////////////////////////////////
684
/**
685
 * Return the Near plane of the Projection included in the Surface.
686
 *
687
 * @return the Near plane.
688
 */
689
  public float getNear()
690
    {
691
    return mNear;
692
    }
693

    
694
///////////////////////////////////////////////////////////////////////////////////////////////////
695
/**
696
 * Set mipmap level.
697
 * <p>
698
 * Trick for speeding up your renders - one can create a pyramid of OutputSurface objects, each next
699
 * one some constant FACTOR smaller than the previous (0.5 is the common value), then set the Mipmap
700
 * Level of the i-th object to be FACTOR^i (we start counting from 0). When rendering any scene into
701
 * such prepared OutputSurface, the library will make sure to scale any Effects used so that the end
702
 * scene will end up looking identical no matter which object we render to. Identical, that is, except
703
 * for the loss of quality and gain in speed associated with rendering to a smaller Surface.
704
 * <p>
705
 * Example: if you create two FBOs, one 1000x1000 and another 500x500 in size, and set the second one
706
 * mipmap to 0.5 (the first one's is 1.0 by default), define Effects to be a single move by (100,100),
707
 * and render a skinned Mesh into both FBO, the end result will look proportionally the same, because
708
 * in the second case the move vector (100,100) will be auto-scaled to (50,50).
709
 *
710
 * @param mipmap The mipmap level. Acceptable range: 0&lt;mipmap&lt;infinity, although mipmap&gt;1
711
 *               does not make any sense (that would result in loss of speed and no gain in quality)
712
 */
713
  public void setMipmap(float mipmap)
714
    {
715
    mMipmap = mipmap;
716
    }
717

    
718
///////////////////////////////////////////////////////////////////////////////////////////////////
719
/**
720
 * Set the (R,G,B,A) values of GLES31.glClearColor() to set up color with which to clear
721
 * this Surface at the beginning of each frame.
722
 *
723
 * @param r the Red component. Default: 0.0f
724
 * @param g the Green component. Default: 0.0f
725
 * @param b the Blue component. Default: 0.0f
726
 * @param a the Alpha component. Default: 0.0f
727
 */
728
  public void glClearColor(float r, float g, float b, float a)
729
    {
730
    mClearR = r;
731
    mClearG = g;
732
    mClearB = b;
733
    mClearA = a;
734
    }
735

    
736
///////////////////////////////////////////////////////////////////////////////////////////////////
737
/**
738
 * Uses glClearDepthf() to set up a value with which to clear
739
 * the Depth buffer of our Surface at the beginning of each frame.
740
 *
741
 * @param d the Depth. Default: 1.0f
742
 */
743
  public void glClearDepthf(float d)
744
    {
745
    mClearDepth = d;
746
    }
747

    
748
///////////////////////////////////////////////////////////////////////////////////////////////////
749
/**
750
 * Uses glClearStencil() to set up a value with which to clear the
751
 * Stencil buffer of our Surface at the beginning of each frame.
752
 *
753
 * @param s the Stencil. Default: 0
754
 */
755
  public void glClearStencil(int s)
756
    {
757
    mClearStencil = s;
758
    }
759

    
760
///////////////////////////////////////////////////////////////////////////////////////////////////
761
/**
762
 * Which buffers to Clear at the beginning of each frame?
763
 * <p>
764
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
765
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
766
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
767
 *
768
 * @param mask bitwise OR of BUFFER_BITs to clear.
769
 */
770
  public void glClear(int mask)
771
    {
772
    mClear = mask;
773
    }
774

    
775
///////////////////////////////////////////////////////////////////////////////////////////////////
776
/**
777
 * Create new Projection matrix.
778
 *
779
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
780
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
781
 * @param near Distance between the screen plane and the near plane.
782
 *             Valid vaules: 0<near<1. When near==0 (illegal!), the Near Plane is exactly at the tip of
783
 *             the pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
784
 */
785
  public void setProjection(float fov, float near)
786
    {
787
    if( fov < 180.0f && fov >=0.0f )
788
      {
789
      mFOV = fov;
790
      }
791

    
792
    if( near<   1.0f && near> 0.0f )
793
      {
794
      mNear= near;
795
      }
796
    else if( near<=0.0f )
797
      {
798
      mNear = 0.01f;
799
      }
800
    else if( near>=1.0f )
801
      {
802
      mNear=0.99f;
803
      }
804

    
805
    if( mBuffer!=null )
806
      {
807
      for(int j=0; j<EffectQuality.LENGTH; j++) mBuffer[j].mNear = mNear;
808
      }
809

    
810
    createProjection();
811
    }
812

    
813
///////////////////////////////////////////////////////////////////////////////////////////////////
814
/**
815
 * Resize the underlying Framebuffer.
816
 * <p>
817
 * This method can be safely called mid-render as it doesn't interfere with rendering.
818
 *
819
 * @param width The new width.
820
 * @param height The new height.
821
 */
822
  public void resize(int width, int height)
823
    {
824
    if( mWidth!=width || mHeight!=height )
825
      {
826
      mWidth = mRealWidth = width;
827
      mHeight= mRealHeight= height;
828

    
829
      createProjection();
830

    
831
      if( mColorCreated==CREATED )
832
        {
833
        markForCreation();
834
        recreate();
835
        }
836
      }
837
    }
838

    
839
///////////////////////////////////////////////////////////////////////////////////////////////////
840
/**
841
 * Return true if the Surface contains a DEPTH attachment.
842
 *
843
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
844
 */
845
  public boolean hasDepth()
846
    {
847
    return mDepthStencilCreated==CREATED;
848
    }
849

    
850
///////////////////////////////////////////////////////////////////////////////////////////////////
851
/**
852
 * Return true if the Surface contains a STENCIL attachment.
853
 *
854
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
855
 */
856
  public boolean hasStencil()
857
    {
858
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
859
    }
860

    
861
///////////////////////////////////////////////////////////////////////////////////////////////////
862
/**
863
 * When rendering this Node, should we use the Order Independent Transparency render more?
864
 * <p>
865
 * There are two modes of rendering: the fast 'normal' way, which however renders transparent
866
 * fragments in different ways depending on which fragments get rendered first, or the slower
867
 * 'oit' way, which renders transparent fragments correctly regardless of their order.
868
 *
869
 * @param oit True if we want to render more slowly, but in a way which accounts for transparency.
870
 */
871
  public void setOrderIndependentTransparency(boolean oit)
872
    {
873
    mRenderWayOIT = oit;
874
    }
875

    
876
///////////////////////////////////////////////////////////////////////////////////////////////////
877
/**
878
 * When rendering this Node, should we use the Order Independent Transparency render more?
879
 * <p>
880
 * There are two modes of rendering: the fast 'normal' way, which however renders transparent
881
 * fragments in different ways depending on which fragments get rendered first, or the slower
882
 * 'oit' way, which renders transparent fragments correctly regardless of their order.
883
 *
884
 * @param oit True if we want to render more slowly, but in a way which accounts for transparency.
885
 * @param initialSize Initial number of transparent fragments we expect, in screenfuls.
886
 *                    I.e '1.0' means 'the scene we are going to render contains about 1 screen
887
 *                    worth of transparent fragments'. Valid values: 0.0 &lt; initialSize &lt; 10.0
888
 *                    Even if you get this wrong, the library will detect that there are more
889
 *                    transparent fragments than it has space for and readjust its internal buffers,
890
 *                    but only after a few frames during which one will probably see missing objects.
891
 */
892
public void setOrderIndependentTransparency(boolean oit, float initialSize)
893
  {
894
  mRenderWayOIT = oit;
895

    
896
  if( initialSize>0.0f && initialSize<10.0f )
897
    DistortedEffects.setSSBOSize(initialSize);
898
  }
899

    
900
///////////////////////////////////////////////////////////////////////////////////////////////////
901
/**
902
 * Adds a new child to the last position in the list of our Surface's children.
903
 * <p>
904
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
905
 * DistortedMaster (by calling doWork())
906
 *
907
 * @param node The new Node to add.
908
 */
909
  public void attach(DistortedNode node)
910
    {
911
    mJobs.add(new Job(ATTACH,node));
912
    DistortedMaster.newSlave(this);
913
    }
914

    
915
///////////////////////////////////////////////////////////////////////////////////////////////////
916
/**
917
 * Adds a new child to the last position in the list of our Surface's children.
918
 * <p>
919
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
920
 * DistortedMaster (by calling doWork())
921
 *
922
 * @param surface InputSurface to initialize our child Node with.
923
 * @param effects DistortedEffects to initialize our child Node with.
924
 * @param mesh MeshBase to initialize our child Node with.
925
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
926
 */
927
  public DistortedNode attach(DistortedSurface surface, DistortedEffects effects, MeshBase mesh)
928
    {
929
    DistortedNode node = new DistortedNode(surface,effects,mesh);
930
    mJobs.add(new Job(ATTACH,node));
931
    DistortedMaster.newSlave(this);
932
    return node;
933
    }
934

    
935
///////////////////////////////////////////////////////////////////////////////////////////////////
936
/**
937
 * Removes the first occurrence of a specified child from the list of children of our Surface.
938
 * <p>
939
 * A bit questionable method as there can be many different Nodes attached as children, some
940
 * of them having the same Effects but - for instance - different Mesh. Use with care.
941
 * <p>
942
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
943
 * DistortedMaster (by calling doWork())
944
 *
945
 * @param effects DistortedEffects to remove.
946
 */
947
  public void detach(DistortedEffects effects)
948
    {
949
    long id = effects.getID();
950
    DistortedNode node;
951
    boolean detached = false;
952

    
953
    for(int i=0; i<mNumChildren; i++)
954
      {
955
      node = mChildren.get(i);
956

    
957
      if( node.getEffects().getID()==id )
958
        {
959
        detached = true;
960
        mJobs.add(new Job(DETACH,node));
961
        DistortedMaster.newSlave(this);
962
        break;
963
        }
964
      }
965

    
966
    if( !detached )
967
      {
968
      // if we failed to detach any, it still might be the case that
969
      // there's an ATTACH job that we need to cancel.
970
      int num = mJobs.size();
971
      Job job;
972

    
973
      for(int i=0; i<num; i++)
974
        {
975
        job = mJobs.get(i);
976

    
977
        if( job.type==ATTACH && job.node.getEffects()==effects )
978
          {
979
          mJobs.remove(i);
980
          break;
981
          }
982
        }
983
      }
984
    }
985

    
986
///////////////////////////////////////////////////////////////////////////////////////////////////
987
/**
988
 * Removes the first occurrence of a specified child from the list of children of our Surface.
989
 * <p>
990
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
991
 * DistortedMaster (by calling doWork())
992
 *
993
 * @param node The Node to remove.
994
 */
995
  public void detach(DistortedNode node)
996
    {
997
    mJobs.add(new Job(DETACH,node));
998
    DistortedMaster.newSlave(this);
999
    }
1000

    
1001
///////////////////////////////////////////////////////////////////////////////////////////////////
1002
/**
1003
 * Removes all children Nodes.
1004
 * <p>
1005
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
1006
 * DistortedMaster (by calling doWork())
1007
 */
1008
  public void detachAll()
1009
    {
1010
    mJobs.add(new Job(DETALL,null));
1011
    DistortedMaster.newSlave(this);
1012
    }
1013

    
1014
///////////////////////////////////////////////////////////////////////////////////////////////////
1015
/**
1016
 * This is not really part of the public API. Has to be public only because it is a part of the
1017
 * DistortedSlave interface, which should really be a class that we extend here instead but
1018
 * Java has no multiple inheritance.
1019
 *
1020
 * @y.exclude
1021
 */
1022
  public void doWork()
1023
    {
1024
    int num = mJobs.size();
1025
    Job job;
1026

    
1027
    for(int i=0; i<num; i++)
1028
      {
1029
      job = mJobs.remove(0);
1030

    
1031
      switch(job.type)
1032
        {
1033
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
1034
                     job.node.setSurfaceParent(this);
1035
                     DistortedMaster.addSortingByBuckets(mChildren,job.node);
1036
                     mNumChildren++;
1037
                     break;
1038
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
1039
                       {
1040
                       job.node.setSurfaceParent(null);
1041
                       mNumChildren--;
1042
                       }
1043
                     break;
1044
        case DETALL: if( mNumChildren>0 )
1045
                       {
1046
                       DistortedNode tmp;
1047

    
1048
                       for(int j=mNumChildren-1; j>=0; j--)
1049
                         {
1050
                         tmp = mChildren.remove(j);
1051
                         tmp.setSurfaceParent(null);
1052
                         }
1053

    
1054
                       mNumChildren = 0;
1055
                       }
1056
                     break;
1057
        case SORT  : mChildren.remove(job.node);
1058
                     DistortedMaster.addSortingByBuckets(mChildren,job.node);
1059
                     break;
1060
        }
1061
      }
1062
    }
1063
}
(8-8/18)