Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedOutputSurface.java @ 8b7b2398

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
    final float CLEAR_R = 1.0f;
186
    final float CLEAR_G = 1.0f;
187
    final float CLEAR_B = 1.0f;
188
    final float CLEAR_A = 0.0f;
189
    final float CLEAR_D = 1.0f;
190
    final int   CLEAR_S = 0;
191

    
192
    mBuffer = new DistortedFramebuffer[EffectQuality.LENGTH];
193
    float mipmap=1.0f;
194

    
195
    for (int j=0; j<EffectQuality.LENGTH; j++)
196
      {
197
      mBuffer[j] = new DistortedFramebuffer(Distorted.FBO_QUEUE_SIZE,2,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(width*mipmap), (int)(height*mipmap) );
198
      mBuffer[j].mMipmap = mipmap;
199
      mBuffer[j].mNear = near;  // copy mNear as well (for blitting- see PostprocessEffect.apply() )
200
      mBuffer[j].glClearColor(CLEAR_R, CLEAR_G, CLEAR_B, CLEAR_A);
201

    
202
      mipmap *= EffectQuality.MULTIPLIER;
203
      }
204

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

    
207
    DistortedRenderState.colorDepthStencilOn();
208
    GLES31.glClearColor(CLEAR_R, CLEAR_G, CLEAR_B, CLEAR_A);
209
    GLES31.glClearDepthf(CLEAR_D);
210
    GLES31.glClearStencil(CLEAR_S);
211

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

    
224
    DistortedRenderState.colorDepthStencilRestore();
225

    
226
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, 0);
227
    }
228

    
229
///////////////////////////////////////////////////////////////////////////////////////////////////
230

    
231
  static synchronized void onDestroy()
232
    {
233
    if( mBuffer!=null )
234
      {
235
      for (int j = 0; j < EffectQuality.LENGTH; j++)
236
        {
237
        mBuffer[j] = null;
238
        }
239

    
240
      mBuffer = null;
241
      }
242
    }
243

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

    
253
  private static void clonePostprocessingViewportAndProjection(DistortedOutputSurface from)
254
    {
255
    if( mBuffer[0].mWidth != from.mWidth || mBuffer[0].mHeight != from.mHeight ||
256
        mBuffer[0].mFOV   != from.mFOV   || mBuffer[0].mNear   != from.mNear    )
257
      {
258
      DistortedOutputSurface surface;
259

    
260
      for(int i=0; i<EffectQuality.LENGTH; i++)
261
        {
262
        surface = mBuffer[i];
263

    
264
        surface.mWidth  = (int)(from.mWidth *surface.mMipmap);
265
        surface.mHeight = (int)(from.mHeight*surface.mMipmap);
266
        surface.mFOV    = from.mFOV;
267
        surface.mNear   = from.mNear;  // Near plane is independent of the mipmap level
268

    
269
        surface.createProjection();
270

    
271
        int maxw = surface.mWidth  > surface.mRealWidth  ? surface.mWidth  : surface.mRealWidth;
272
        int maxh = surface.mHeight > surface.mRealHeight ? surface.mHeight : surface.mRealHeight;
273

    
274
        if (maxw > surface.mRealWidth || maxh > surface.mRealHeight)
275
          {
276
          surface.mRealWidth = maxw;
277
          surface.mRealHeight = maxh;
278

    
279
          surface.recreate();
280
          surface.create();
281
          }
282
        }
283
      }
284
    }
285

    
286
///////////////////////////////////////////////////////////////////////////////////////////////////
287

    
288
  private int blitWithDepth(long currTime, DistortedOutputSurface buffer,int fbo)
289
    {
290
    GLES31.glViewport(0, 0, mWidth, mHeight);
291
    setAsOutput(currTime);
292
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
293
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
294
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
295
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
296

    
297
    GLES31.glDisable(GLES31.GL_STENCIL_TEST);
298
    GLES31.glStencilMask(0x00);
299

    
300
    DistortedEffects.blitDepthPriv(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
301
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
302
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
303
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
304
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
305

    
306
    // clear buffers
307
    GLES31.glStencilMask(0xff);
308
    GLES31.glDepthMask(true);
309
    GLES31.glColorMask(true,true,true,true);
310
    GLES31.glClearColor(buffer.mClearR,buffer.mClearG,buffer.mClearB,buffer.mClearA);
311
    GLES31.glClearDepthf(buffer.mClearDepth);
312
    GLES31.glClearStencil(buffer.mClearStencil);
313

    
314
    buffer.setAsOutput();
315
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo+1], 0);
316
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
317
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo  ], 0);
318
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
319

    
320
    return 1;
321
    }
322

    
323
///////////////////////////////////////////////////////////////////////////////////////////////////
324

    
325
  private static void oitClear(DistortedOutputSurface buffer)
326
    {
327
    int counter = DistortedEffects.zeroOutAtomic();
328
    DistortedEffects.oitClear(buffer,counter);
329
    GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT|GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
330
    }
331

    
332
///////////////////////////////////////////////////////////////////////////////////////////////////
333

    
334
  private int oitBuild(long time, DistortedOutputSurface buffer, int fbo)
335
    {
336
    GLES31.glViewport(0, 0, mWidth, mHeight);
337
    setAsOutput(time);
338
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
339
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
340
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
341
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
342

    
343
    DistortedRenderState.colorDepthStencilOn();
344
    DistortedRenderState.enableDepthTest();
345

    
346
    DistortedEffects.oitBuild(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
347
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
348
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
349
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
350
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
351

    
352
    DistortedRenderState.colorDepthStencilRestore();
353
    DistortedRenderState.restoreDepthTest();
354

    
355
    return 1;
356
    }
357

    
358
///////////////////////////////////////////////////////////////////////////////////////////////////
359
// two phases: 1. collapse the SSBO 2. blend the ssbo's color
360

    
361
  private int oitRender(long currTime, int fbo)
362
    {
363
    float corrW = getWidthCorrection();
364
    float corrH = getHeightCorrection();
365

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

    
369
    if( mDepthStencilH[fbo] != 0 )
370
      {
371
      GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, 0);
372
      GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
373
      GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, mDepthStencilH[fbo]);
374
      DistortedRenderState.switchOffColorDepthStencil();
375
      DistortedEffects.oitCollapse(this, corrW, corrH);
376
      GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
377
      }
378

    
379
    setAsOutput(currTime);
380
    DistortedRenderState.switchColorDepthOnStencilOff();
381
    DistortedEffects.oitRender(this, corrW, corrH);
382
    DistortedRenderState.restoreColorDepthStencil();
383

    
384
    return 1;
385
    }
386

    
387
///////////////////////////////////////////////////////////////////////////////////////////////////
388

    
389
  void clear()
390
    {
391
    DistortedRenderState.colorDepthStencilOn();
392
    GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
393
    GLES31.glClearDepthf(mClearDepth);
394
    GLES31.glClearStencil(mClearStencil);
395
    GLES31.glClear(mClear);
396
    DistortedRenderState.colorDepthStencilRestore();
397
    }
398

    
399
///////////////////////////////////////////////////////////////////////////////////////////////////
400

    
401
  void setCurrFBO(int fbo)
402
    {
403
    mCurrFBO = fbo;
404
    }
405

    
406
///////////////////////////////////////////////////////////////////////////////////////////////////
407
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
408
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
409
// to a whole buffer (lastQueue.postprocess) and merge it (this.oitBuild or blitWithDepth - depending
410
// on the type of rendering)
411

    
412
  int renderChildren(long time, int numChildren, ArrayList<DistortedNode> children, int fbo, boolean oit)
413
    {
414
    int quality=0, numRenders=0, bucketChange=0;
415
    DistortedNode child;
416
    EffectQueuePostprocess lastQueue=null, currQueue;
417
    long lastBucket=0, currBucket;
418
    boolean renderDirectly=false;
419

    
420
    setCurrFBO(fbo);
421

    
422
    if( mBuffer!=null )
423
      {
424
      for (int i=0; i<EffectQuality.LENGTH; i++) mBuffer[i].setCurrFBO(fbo);
425
      }
426

    
427
    if( oit && numChildren>0 )
428
      {
429
      oitClear(this);
430
      }
431

    
432
    for(int i=0; i<numChildren; i++)
433
      {
434
      child = children.get(i);
435
      currQueue = child.getPostprocessQueue();
436
      currBucket= currQueue.getID();
437

    
438
      if( currBucket==0 )
439
        {
440
        setAsOutput(time);
441

    
442
        if( oit )
443
          {
444
          numRenders += child.drawOIT(time, this);
445
          GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
446
          }
447
        else
448
          {
449
          numRenders += child.draw(time, this);
450
          }
451
        }
452
      else
453
        {
454
        if( mBuffer==null )
455
          {
456
          createPostprocessingBuffers(mWidth,mHeight,mNear);
457
          for (int j=0; j<EffectQuality.LENGTH; j++) mBuffer[j].setCurrFBO(fbo);
458
          }
459

    
460
        if( lastBucket!=currBucket )
461
          {
462
          if( lastBucket==0 )
463
            {
464
            clonePostprocessingViewportAndProjection(this);
465
            }
466
          else
467
            {
468
            for(int j=bucketChange; j<i; j++) numRenders += lastQueue.preprocess( mBuffer[quality],children.get(j) );
469
            numRenders += lastQueue.postprocess(mBuffer[quality]);
470

    
471
            if( oit )
472
              {
473
              numRenders += oitBuild(time, mBuffer[quality], fbo);
474
              GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
475
              }
476
            else
477
              {
478
              numRenders += blitWithDepth(time, mBuffer[quality],fbo);
479
              }
480
            mBuffer[quality].clearBuffer(fbo);
481
            }
482

    
483
          quality= currQueue.getQuality();
484
          bucketChange= i;
485
          renderDirectly = currQueue.getRender();
486
          }
487

    
488
        if( renderDirectly )
489
          {
490
          setAsOutput(time);
491

    
492
          if( oit )
493
            {
494
            numRenders += child.drawOIT(time, this);
495
            GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
496
            }
497
          else
498
            {
499
            numRenders += child.draw(time, this);
500
            }
501
          }
502
        else
503
          {
504
          mBuffer[quality].setAsOutput(time);
505
          child.drawNoBlend(time, mBuffer[quality]);
506
          }
507

    
508
        if( i==numChildren-1 )
509
          {
510
          for(int j=bucketChange; j<numChildren; j++) numRenders += currQueue.preprocess( mBuffer[quality],children.get(j) );
511
          numRenders += currQueue.postprocess(mBuffer[quality]);
512

    
513
          if( oit )
514
            {
515
            numRenders += oitBuild(time, mBuffer[quality], fbo);
516
            GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
517
            mBuffer[quality].clearBuffer(fbo);
518
            }
519
          else
520
            {
521
            numRenders += blitWithDepth(time, mBuffer[quality],fbo);
522
            }
523
          }
524
        } // end else (postprocessed child)
525

    
526
      lastQueue = currQueue;
527
      lastBucket= currBucket;
528
      } // end main for loop
529

    
530
    if( oit && numChildren>0 )
531
      {
532
      numRenders += oitRender(time, fbo);  // merge the OIT linked list
533
      }
534

    
535
    return numRenders;
536
    }
537

    
538
///////////////////////////////////////////////////////////////////////////////////////////////////
539

    
540
  ArrayList<DistortedNode> getChildren()
541
    {
542
    return mChildren;
543
    }
544

    
545
///////////////////////////////////////////////////////////////////////////////////////////////////
546
/**
547
 * Not part of the Public API.
548
 *
549
 * @y.exclude
550
 */
551
  public float getWidthCorrection()
552
    {
553
    return (float)mWidth/mRealWidth;
554
    }
555

    
556
///////////////////////////////////////////////////////////////////////////////////////////////////
557
/**
558
 * Not part of the Public API.
559
 *
560
 * @y.exclude
561
 */
562
  public float getHeightCorrection()
563
    {
564
    return (float)mHeight/mRealHeight;
565
    }
566

    
567
///////////////////////////////////////////////////////////////////////////////////////////////////
568

    
569
  void clearBuffer(int fbo)
570
    {
571
    DistortedRenderState.colorDepthStencilOn();
572

    
573
    GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
574
    GLES31.glClearDepthf(mClearDepth);
575
    GLES31.glClearStencil(mClearStencil);
576

    
577
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[fbo]);
578
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mColorH[2*fbo+1], 0);
579
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
580
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mColorH[2*fbo  ], 0);
581
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
582

    
583
    DistortedRenderState.colorDepthStencilRestore();
584
    }
585

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

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

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

    
648
    int numRenders=0;
649

    
650
    for(int i=0; i<mNumChildren; i++)
651
      {
652
      numRenders += mChildren.get(i).renderRecursive(time);
653
      }
654

    
655
    numRenders += renderChildren(time,mNumChildren,mChildren,fbo, mRenderWayOIT);
656

    
657
    return numRenders;
658
    }
659

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

    
673
    if( mTime[mCurrFBO]!=time )
674
      {
675
      mTime[mCurrFBO] = time;
676
      clear();
677
      }
678
    }
679

    
680
///////////////////////////////////////////////////////////////////////////////////////////////////
681
/**
682
 * Bind this Surface as a Framebuffer we can render to.
683
 * <p>
684
 * This version does not attempt to clear anything.
685
 */
686
  public void setAsOutput()
687
    {
688
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[mCurrFBO]);
689
    }
690

    
691
///////////////////////////////////////////////////////////////////////////////////////////////////
692
/**
693
 * Return the Near plane of the Projection included in the Surface.
694
 *
695
 * @return the Near plane.
696
 */
697
  public float getNear()
698
    {
699
    return mNear;
700
    }
701

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

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

    
744
///////////////////////////////////////////////////////////////////////////////////////////////////
745
/**
746
 * Uses glClearDepthf() to set up a value with which to clear
747
 * the Depth buffer of our Surface at the beginning of each frame.
748
 *
749
 * @param d the Depth. Default: 1.0f
750
 */
751
  public void glClearDepthf(float d)
752
    {
753
    mClearDepth = d;
754
    }
755

    
756
///////////////////////////////////////////////////////////////////////////////////////////////////
757
/**
758
 * Uses glClearStencil() to set up a value with which to clear the
759
 * Stencil buffer of our Surface at the beginning of each frame.
760
 *
761
 * @param s the Stencil. Default: 0
762
 */
763
  public void glClearStencil(int s)
764
    {
765
    mClearStencil = s;
766
    }
767

    
768
///////////////////////////////////////////////////////////////////////////////////////////////////
769
/**
770
 * Which buffers to Clear at the beginning of each frame?
771
 * <p>
772
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
773
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
774
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
775
 *
776
 * @param mask bitwise OR of BUFFER_BITs to clear.
777
 */
778
  public void glClear(int mask)
779
    {
780
    mClear = mask;
781
    }
782

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

    
800
    if( near<   1.0f && near> 0.0f )
801
      {
802
      mNear= near;
803
      }
804
    else if( near<=0.0f )
805
      {
806
      mNear = 0.01f;
807
      }
808
    else if( near>=1.0f )
809
      {
810
      mNear=0.99f;
811
      }
812

    
813
    if( mBuffer!=null )
814
      {
815
      for(int j=0; j<EffectQuality.LENGTH; j++) mBuffer[j].mNear = mNear;
816
      }
817

    
818
    createProjection();
819
    }
820

    
821
///////////////////////////////////////////////////////////////////////////////////////////////////
822
/**
823
 * Resize the underlying Framebuffer.
824
 * <p>
825
 * This method can be safely called mid-render as it doesn't interfere with rendering.
826
 *
827
 * @param width The new width.
828
 * @param height The new height.
829
 */
830
  public void resize(int width, int height)
831
    {
832
    if( mWidth!=width || mHeight!=height )
833
      {
834
      mWidth = mRealWidth = width;
835
      mHeight= mRealHeight= height;
836

    
837
      createProjection();
838

    
839
      if( mColorCreated==CREATED )
840
        {
841
        markForCreation();
842
        recreate();
843
        }
844
      }
845
    }
846

    
847
///////////////////////////////////////////////////////////////////////////////////////////////////
848
/**
849
 * Return true if the Surface contains a DEPTH attachment.
850
 *
851
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
852
 */
853
  public boolean hasDepth()
854
    {
855
    return mDepthStencilCreated==CREATED;
856
    }
857

    
858
///////////////////////////////////////////////////////////////////////////////////////////////////
859
/**
860
 * Return true if the Surface contains a STENCIL attachment.
861
 *
862
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
863
 */
864
  public boolean hasStencil()
865
    {
866
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
867
    }
868

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

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

    
904
  if( initialSize>0.0f && initialSize<10.0f )
905
    DistortedEffects.setSSBOSize(initialSize);
906
  }
907

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

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

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

    
961
    for(int i=0; i<mNumChildren; i++)
962
      {
963
      node = mChildren.get(i);
964

    
965
      if( node.getEffects().getID()==id )
966
        {
967
        detached = true;
968
        mJobs.add(new Job(DETACH,node));
969
        DistortedMaster.newSlave(this);
970
        break;
971
        }
972
      }
973

    
974
    if( !detached )
975
      {
976
      // if we failed to detach any, it still might be the case that
977
      // there's an ATTACH job that we need to cancel.
978
      int num = mJobs.size();
979
      Job job;
980

    
981
      for(int i=0; i<num; i++)
982
        {
983
        job = mJobs.get(i);
984

    
985
        if( job.type==ATTACH && job.node.getEffects()==effects )
986
          {
987
          mJobs.remove(i);
988
          break;
989
          }
990
        }
991
      }
992
    }
993

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

    
1009
///////////////////////////////////////////////////////////////////////////////////////////////////
1010
/**
1011
 * Removes all children Nodes.
1012
 * <p>
1013
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
1014
 * DistortedMaster (by calling doWork())
1015
 */
1016
  public void detachAll()
1017
    {
1018
    mJobs.add(new Job(DETALL,null));
1019
    DistortedMaster.newSlave(this);
1020
    }
1021

    
1022
///////////////////////////////////////////////////////////////////////////////////////////////////
1023
/**
1024
 * This is not really part of the public API. Has to be public only because it is a part of the
1025
 * DistortedSlave interface, which should really be a class that we extend here instead but
1026
 * Java has no multiple inheritance.
1027
 *
1028
 * @y.exclude
1029
 */
1030
  public void doWork()
1031
    {
1032
    int num = mJobs.size();
1033
    Job job;
1034

    
1035
    for(int i=0; i<num; i++)
1036
      {
1037
      job = mJobs.remove(0);
1038

    
1039
      switch(job.type)
1040
        {
1041
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
1042
                     job.node.setSurfaceParent(this);
1043
                     DistortedMaster.addSortingByBuckets(mChildren,job.node);
1044
                     mNumChildren++;
1045
                     break;
1046
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
1047
                       {
1048
                       job.node.setSurfaceParent(null);
1049
                       mNumChildren--;
1050
                       }
1051
                     break;
1052
        case DETALL: if( mNumChildren>0 )
1053
                       {
1054
                       DistortedNode tmp;
1055

    
1056
                       for(int j=mNumChildren-1; j>=0; j--)
1057
                         {
1058
                         tmp = mChildren.remove(j);
1059
                         tmp.setSurfaceParent(null);
1060
                         }
1061

    
1062
                       mNumChildren = 0;
1063
                       }
1064
                     break;
1065
        case SORT  : mChildren.remove(job.node);
1066
                     DistortedMaster.addSortingByBuckets(mChildren,job.node);
1067
                     break;
1068
        }
1069
      }
1070
    }
1071
}
(8-8/17)