Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedOutputSurface.java @ d5b709df

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
///////////////////////////////////////////////////////////////////////////////////////////////////
29
/**
30
 * This is not really part of the public API.
31
 *
32
 * @y.exclude
33
 */
34
public abstract class DistortedOutputSurface extends DistortedSurface implements DistortedChildrenList.Parent
35
{
36
  public static final int NO_DEPTH_NO_STENCIL = 0;
37
  public static final int DEPTH_NO_STENCIL    = 1;
38
  public static final int BOTH_DEPTH_STENCIL  = 2;
39

    
40
  float mFOV, mDistance, mNear;
41
  float[] mProjectionMatrix;
42

    
43
  int mDepthStencilCreated;
44
  int mDepthStencil;
45
  int[] mDepthStencilH;
46
  int[] mFBOH;
47

    
48
  float mMipmap;
49

    
50
  int mRealWidth;   // the Surface can be backed up with a texture that is
51
  int mRealHeight;  // larger than the viewport we have to it.
52
                    // mWidth,mHeight are the sizes of the Viewport, those -
53
                    // sizes of the backing up texture.
54

    
55
  int mCurrFBO;     // internal current FBO (see Distorted.FBO_QUEUE_SIZE)
56

    
57
  private static DistortedFramebuffer[] mBuffer=null; // Global buffers used for postprocessing.
58
  private long[] mTime;
59
  private float mClearR, mClearG, mClearB, mClearA, mClearDepth;
60
  private int mClear, mClearStencil;
61
  private boolean mRenderWayOIT;
62
  private DistortedChildrenList mChildren;
63

    
64
///////////////////////////////////////////////////////////////////////////////////////////////////
65

    
66
  DistortedOutputSurface(int width, int height, int createColor, int numfbos, int numcolors, int depthStencil, int fbo, int type)
67
    {
68
    super(width,height,createColor,numfbos,numcolors,type);
69

    
70
    mRenderWayOIT = false;
71
    mCurrFBO      = 0;
72

    
73
    mDepthStencilH = new int[numfbos];
74
    mFBOH          = new int[numfbos];
75

    
76
    mTime = new long[numfbos];
77
    for(int i=0; i<mNumFBOs;i++) mTime[i]=0;
78

    
79
    mRealWidth = width;
80
    mRealHeight= height;
81

    
82
    mProjectionMatrix = new float[16];
83

    
84
    mFOV = 60.0f;
85
    mNear=  0.5f;
86

    
87
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
88
    mDepthStencil = depthStencil;
89

    
90
    mFBOH[0]         = fbo;
91
    mDepthStencilH[0]= 0;
92

    
93
    mClearR = 0.0f;
94
    mClearG = 0.0f;
95
    mClearB = 0.0f;
96
    mClearA = 0.0f;
97

    
98
    mClearDepth = 1.0f;
99
    mClearStencil = 0;
100
    mClear = GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_COLOR_BUFFER_BIT;
101

    
102
    mMipmap = 1.0f;
103

    
104
    mChildren = new DistortedChildrenList(this);
105

    
106
    createProjection();
107
    }
108

    
109
///////////////////////////////////////////////////////////////////////////////////////////////////
110

    
111
  private void createProjection()
112
    {
113
    if( mWidth>0 && mHeight>1 )
114
      {
115
      if( mFOV>0.0f )  // perspective projection
116
        {
117
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
118
        float q = mWidth*mNear;
119
        float c = mHeight*mNear;
120

    
121
        float left   = -q/2;
122
        float right  = +q/2;
123
        float bottom = -c/2;
124
        float top    = +c/2;
125
        float near   =  c/a;
126

    
127
        mDistance    = mHeight/a;
128
        float far    = 2*mDistance-near;
129

    
130
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
131
        }
132
      else             // parallel projection
133
        {
134
        float left   = -mWidth/2.0f;
135
        float right  = +mWidth/2.0f;
136
        float bottom = -mHeight/2.0f;
137
        float top    = +mHeight/2.0f;
138
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
139
        mDistance    = mWidth+mHeight;
140
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
141

    
142
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
143
        }
144
      }
145
    }
146

    
147
///////////////////////////////////////////////////////////////////////////////////////////////////
148

    
149
  private static void createPostprocessingBuffers(int width, int height, float near)
150
    {
151
    final float CLEAR_R = 1.0f;
152
    final float CLEAR_G = 1.0f;
153
    final float CLEAR_B = 1.0f;
154
    final float CLEAR_A = 0.0f;
155
    final float CLEAR_D = 1.0f;
156
    final int   CLEAR_S = 0;
157

    
158
    mBuffer = new DistortedFramebuffer[EffectQuality.LENGTH];
159
    float mipmap=1.0f;
160

    
161
    for (int j=0; j<EffectQuality.LENGTH; j++)
162
      {
163
      mBuffer[j] = new DistortedFramebuffer(Distorted.FBO_QUEUE_SIZE,2,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(width*mipmap), (int)(height*mipmap) );
164
      mBuffer[j].mMipmap = mipmap;
165
      mBuffer[j].mNear = near;  // copy mNear as well (for blitting- see PostprocessEffect.apply() )
166
      mBuffer[j].glClearColor(CLEAR_R, CLEAR_G, CLEAR_B, CLEAR_A);
167

    
168
      mipmap *= EffectQuality.MULTIPLIER;
169
      }
170

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

    
173
    DistortedRenderState.colorDepthStencilOn();
174
    GLES31.glClearColor(CLEAR_R, CLEAR_G, CLEAR_B, CLEAR_A);
175
    GLES31.glClearDepthf(CLEAR_D);
176
    GLES31.glClearStencil(CLEAR_S);
177

    
178
    for (int j=0; j<EffectQuality.LENGTH; j++)
179
      {
180
      for(int k=0; k<Distorted.FBO_QUEUE_SIZE; k++)
181
        {
182
        GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mBuffer[j].mFBOH[k]);
183
        GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[2*k+1], 0);
184
        GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT | GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_STENCIL_BUFFER_BIT);
185
        GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[2*k  ], 0);
186
        GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
187
        }
188
      }
189

    
190
    DistortedRenderState.colorDepthStencilRestore();
191

    
192
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, 0);
193
    }
194

    
195
///////////////////////////////////////////////////////////////////////////////////////////////////
196

    
197
  static synchronized void onDestroy()
198
    {
199
    if( mBuffer!=null )
200
      {
201
      for (int j = 0; j < EffectQuality.LENGTH; j++)
202
        {
203
        mBuffer[j] = null;
204
        }
205

    
206
      mBuffer = null;
207
      }
208
    }
209

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

    
219
  private static void clonePostprocessingViewportAndProjection(DistortedOutputSurface from)
220
    {
221
    if( mBuffer[0].mWidth != from.mWidth || mBuffer[0].mHeight != from.mHeight ||
222
        mBuffer[0].mFOV   != from.mFOV   || mBuffer[0].mNear   != from.mNear    )
223
      {
224
      DistortedOutputSurface surface;
225

    
226
      for(int i=0; i<EffectQuality.LENGTH; i++)
227
        {
228
        surface = mBuffer[i];
229

    
230
        surface.mWidth  = (int)(from.mWidth *surface.mMipmap);
231
        surface.mHeight = (int)(from.mHeight*surface.mMipmap);
232
        surface.mFOV    = from.mFOV;
233
        surface.mNear   = from.mNear;  // Near plane is independent of the mipmap level
234

    
235
        surface.createProjection();
236

    
237
        int maxw = surface.mWidth  > surface.mRealWidth  ? surface.mWidth  : surface.mRealWidth;
238
        int maxh = surface.mHeight > surface.mRealHeight ? surface.mHeight : surface.mRealHeight;
239

    
240
        if (maxw > surface.mRealWidth || maxh > surface.mRealHeight)
241
          {
242
          surface.mRealWidth = maxw;
243
          surface.mRealHeight = maxh;
244

    
245
          surface.recreate();
246
          surface.create();
247
          }
248
        }
249
      }
250
    }
251

    
252
///////////////////////////////////////////////////////////////////////////////////////////////////
253

    
254
  private int blitWithDepth(long currTime, DistortedOutputSurface buffer,int fbo)
255
    {
256
    GLES31.glViewport(0, 0, mWidth, mHeight);
257
    setAsOutput(currTime);
258
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
259
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
260
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
261
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
262

    
263
    GLES31.glDisable(GLES31.GL_STENCIL_TEST);
264
    GLES31.glStencilMask(0x00);
265

    
266
    Distorted.blitDepthPriv(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
267
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
268
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
269
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
270
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
271

    
272
    // clear buffers
273
    GLES31.glStencilMask(0xff);
274
    GLES31.glDepthMask(true);
275
    GLES31.glColorMask(true,true,true,true);
276
    GLES31.glClearColor(buffer.mClearR,buffer.mClearG,buffer.mClearB,buffer.mClearA);
277
    GLES31.glClearDepthf(buffer.mClearDepth);
278
    GLES31.glClearStencil(buffer.mClearStencil);
279

    
280
    buffer.setAsOutput();
281
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo+1], 0);
282
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
283
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo  ], 0);
284
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
285

    
286
    return 1;
287
    }
288

    
289
///////////////////////////////////////////////////////////////////////////////////////////////////
290

    
291
  private static void oitClear(DistortedOutputSurface buffer)
292
    {
293
    int counter = Distorted.zeroOutAtomic();
294
    Distorted.oitClear(buffer,counter);
295
    GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT|GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
296
    }
297

    
298
///////////////////////////////////////////////////////////////////////////////////////////////////
299

    
300
  private int oitBuild(long time, DistortedOutputSurface buffer, int fbo)
301
    {
302
    GLES31.glViewport(0, 0, mWidth, mHeight);
303
    setAsOutput(time);
304
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
305
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
306
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
307
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
308

    
309
    DistortedRenderState.colorDepthStencilOn();
310
    DistortedRenderState.enableDepthTest();
311

    
312
    Distorted.oitBuild(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
313
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
314
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
315
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
316
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
317

    
318
    DistortedRenderState.colorDepthStencilRestore();
319
    DistortedRenderState.restoreDepthTest();
320

    
321
    return 1;
322
    }
323

    
324
///////////////////////////////////////////////////////////////////////////////////////////////////
325
// two phases: 1. collapse the SSBO 2. blend the ssbo's color
326

    
327
  private int oitRender(long currTime, int fbo)
328
    {
329
    float corrW = getWidthCorrection();
330
    float corrH = getHeightCorrection();
331

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

    
335
    if( mDepthStencilH[fbo] != 0 )
336
      {
337
      GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, 0);
338
      GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
339
      GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, mDepthStencilH[fbo]);
340
      DistortedRenderState.switchOffColorDepthStencil();
341
      Distorted.oitCollapse(this, corrW, corrH);
342
      GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
343
      }
344

    
345
    setAsOutput(currTime);
346
    DistortedRenderState.switchColorDepthOnStencilOff();
347
    Distorted.oitRender(this, corrW, corrH);
348
    DistortedRenderState.restoreColorDepthStencil();
349

    
350
    return 1;
351
    }
352

    
353
///////////////////////////////////////////////////////////////////////////////////////////////////
354

    
355
  private void clear()
356
    {
357
    DistortedRenderState.colorDepthStencilOn();
358
    GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
359
    GLES31.glClearDepthf(mClearDepth);
360
    GLES31.glClearStencil(mClearStencil);
361
    GLES31.glClear(mClear);
362
    DistortedRenderState.colorDepthStencilRestore();
363
    }
364

    
365
///////////////////////////////////////////////////////////////////////////////////////////////////
366

    
367
  void setCurrFBO(int fbo)
368
    {
369
    mCurrFBO = fbo;
370
    }
371

    
372
///////////////////////////////////////////////////////////////////////////////////////////////////
373
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
374
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
375
// to a whole buffer (lastQueue.postprocess) and merge it (this.oitBuild or blitWithDepth - depending
376
// on the type of rendering)
377

    
378
  int renderChildren(long time, int numChildren, DistortedChildrenList children, int fbo, boolean oit)
379
    {
380
    int quality=0, numRenders=0, bucketChange=0;
381
    DistortedNode child;
382
    EffectQueuePostprocess lastQueue=null, currQueue;
383
    long lastBucket=0, currBucket;
384
    boolean renderDirectly=false;
385

    
386
    setCurrFBO(fbo);
387

    
388
    if( mBuffer!=null )
389
      {
390
      for (int i=0; i<EffectQuality.LENGTH; i++) mBuffer[i].setCurrFBO(fbo);
391
      }
392

    
393
    if( oit && numChildren>0 )
394
      {
395
      oitClear(this);
396
      }
397

    
398
    for(int i=0; i<numChildren; i++)
399
      {
400
      child = children.getChild(i);
401
      currQueue = (EffectQueuePostprocess)child.getEffects().getQueues()[3];
402
      currBucket= currQueue.getID();
403

    
404
      if( currBucket==0 )
405
        {
406
        setAsOutput(time);
407

    
408
        if( oit )
409
          {
410
          numRenders += child.drawOIT(time, this);
411
          GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
412
          }
413
        else
414
          {
415
          numRenders += child.draw(time, this);
416
          }
417
        }
418
      else
419
        {
420
        if( mBuffer==null )
421
          {
422
          createPostprocessingBuffers(mWidth,mHeight,mNear);
423
          for (int j=0; j<EffectQuality.LENGTH; j++) mBuffer[j].setCurrFBO(fbo);
424
          }
425

    
426
        if( lastBucket!=currBucket )
427
          {
428
          if( lastBucket==0 )
429
            {
430
            clonePostprocessingViewportAndProjection(this);
431
            }
432
          else
433
            {
434
            for(int j=bucketChange; j<i; j++) numRenders += lastQueue.preprocess( mBuffer[quality],children.getChild(j) );
435
            numRenders += lastQueue.postprocess(mBuffer[quality]);
436

    
437
            if( oit )
438
              {
439
              numRenders += oitBuild(time, mBuffer[quality], fbo);
440
              GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
441
              }
442
            else
443
              {
444
              numRenders += blitWithDepth(time, mBuffer[quality],fbo);
445
              }
446
            mBuffer[quality].clearBuffer(fbo);
447
            }
448

    
449
          quality= currQueue.getQuality();
450
          bucketChange= i;
451
          renderDirectly = currQueue.getRender();
452
          }
453

    
454
        if( renderDirectly )
455
          {
456
          setAsOutput(time);
457

    
458
          if( oit )
459
            {
460
            numRenders += child.drawOIT(time, this);
461
            GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
462
            }
463
          else
464
            {
465
            numRenders += child.draw(time, this);
466
            }
467
          }
468
        else
469
          {
470
          mBuffer[quality].setAsOutput(time);
471
          child.drawNoBlend(time, mBuffer[quality]);
472
          }
473

    
474
        if( i==numChildren-1 )
475
          {
476
          for(int j=bucketChange; j<numChildren; j++) numRenders += currQueue.preprocess( mBuffer[quality],children.getChild(j) );
477
          numRenders += currQueue.postprocess(mBuffer[quality]);
478

    
479
          if( oit )
480
            {
481
            numRenders += oitBuild(time, mBuffer[quality], fbo);
482
            GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
483
            mBuffer[quality].clearBuffer(fbo);
484
            }
485
          else
486
            {
487
            numRenders += blitWithDepth(time, mBuffer[quality],fbo);
488
            }
489
          }
490
        } // end else (postprocessed child)
491

    
492
      lastQueue = currQueue;
493
      lastBucket= currBucket;
494
      } // end main for loop
495

    
496
    if( oit && numChildren>0 )
497
      {
498
      numRenders += oitRender(time, fbo);  // merge the OIT linked list
499
      }
500

    
501
    return numRenders;
502
    }
503

    
504
///////////////////////////////////////////////////////////////////////////////////////////////////
505
/**
506
 * Not part of the public API.
507
 *
508
 * @y.exclude
509
 */
510
  public void adjustIsomorphism() { }
511

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

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

    
534
///////////////////////////////////////////////////////////////////////////////////////////////////
535

    
536
  void clearBuffer(int fbo)
537
    {
538
    DistortedRenderState.colorDepthStencilOn();
539

    
540
    GLES31.glClearColor(mClearR, mClearG, mClearB, mClearA);
541
    GLES31.glClearDepthf(mClearDepth);
542
    GLES31.glClearStencil(mClearStencil);
543

    
544
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[fbo]);
545
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mColorH[2*fbo+1], 0);
546
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
547
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mColorH[2*fbo  ], 0);
548
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
549

    
550
    DistortedRenderState.colorDepthStencilRestore();
551
    }
552

    
553
///////////////////////////////////////////////////////////////////////////////////////////////////
554
// PUBLIC API
555
///////////////////////////////////////////////////////////////////////////////////////////////////
556
/**
557
 * Draws all the attached children to this OutputSurface's 0th FBO.
558
 * <p>
559
 * Must be called from a thread holding OpenGL Context.
560
 *
561
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
562
 * @return Number of objects rendered.
563
 */
564
  public int render(long time)
565
    {
566
    return render(time,0);
567
    }
568

    
569
///////////////////////////////////////////////////////////////////////////////////////////////////
570
/**
571
 * Draws all the attached children to this OutputSurface.
572
 * <p>
573
 * Must be called from a thread holding OpenGL Context.
574
 *
575
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
576
 * @param fbo The surface can have many FBOs backing it up - render this to FBO number 'fbo'.
577
 * @return Number of objects rendered.
578
 */
579
  public int render(long time, int fbo)
580
    {
581
    DistortedMaster.toDo();
582
    toDo();
583
    DistortedRenderState.reset();
584

    
585
    int numRenders=0, numChildren = mChildren.getNumChildren();
586
    DistortedNode node;
587
    long oldBucket=0, newBucket;
588

    
589
    for(int i=0; i<numChildren; i++)
590
      {
591
      node = mChildren.getChild(i);
592
      newBucket = node.getBucket();
593
      numRenders += node.renderRecursive(time);
594
      if( newBucket<oldBucket ) mChildren.rearrangeByBuckets(i,newBucket);
595
      else oldBucket=newBucket;
596
      }
597

    
598
    numRenders += renderChildren(time,numChildren,mChildren,fbo, mRenderWayOIT);
599

    
600
    return numRenders;
601
    }
602

    
603
///////////////////////////////////////////////////////////////////////////////////////////////////
604
/**
605
 * Bind this Surface as a Framebuffer we can render to.
606
 *
607
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
608
 *             out if this is the first time during present frame that this FBO is being set as output.
609
 *             If so, the library, in addition to binding the Surface for output, also clears the
610
 *             Surface's color and depth attachments.
611
 */
612
  public void setAsOutput(long time)
613
    {
614
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[mCurrFBO]);
615

    
616
    if( mTime[mCurrFBO]!=time )
617
      {
618
      mTime[mCurrFBO] = time;
619
      clear();
620
      }
621
    }
622

    
623
///////////////////////////////////////////////////////////////////////////////////////////////////
624
/**
625
 * Bind this Surface as a Framebuffer we can render to.
626
 * <p>
627
 * This version does not attempt to clear anything.
628
 */
629
  public void setAsOutput()
630
    {
631
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[mCurrFBO]);
632
    }
633

    
634
///////////////////////////////////////////////////////////////////////////////////////////////////
635
/**
636
 * Return the Near plane of the Projection included in the Surface.
637
 *
638
 * @return the Near plane.
639
 */
640
  public float getNear()
641
    {
642
    return mNear;
643
    }
644

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

    
669
///////////////////////////////////////////////////////////////////////////////////////////////////
670
/**
671
 * Set the (R,G,B,A) values of GLES31.glClearColor() to set up color with which to clear
672
 * this Surface at the beginning of each frame.
673
 *
674
 * @param r the Red component. Default: 0.0f
675
 * @param g the Green component. Default: 0.0f
676
 * @param b the Blue component. Default: 0.0f
677
 * @param a the Alpha component. Default: 0.0f
678
 */
679
  public void glClearColor(float r, float g, float b, float a)
680
    {
681
    mClearR = r;
682
    mClearG = g;
683
    mClearB = b;
684
    mClearA = a;
685
    }
686

    
687
///////////////////////////////////////////////////////////////////////////////////////////////////
688
/**
689
 * Uses glClearDepthf() to set up a value with which to clear
690
 * the Depth buffer of our Surface at the beginning of each frame.
691
 *
692
 * @param d the Depth. Default: 1.0f
693
 */
694
  public void glClearDepthf(float d)
695
    {
696
    mClearDepth = d;
697
    }
698

    
699
///////////////////////////////////////////////////////////////////////////////////////////////////
700
/**
701
 * Uses glClearStencil() to set up a value with which to clear the
702
 * Stencil buffer of our Surface at the beginning of each frame.
703
 *
704
 * @param s the Stencil. Default: 0
705
 */
706
  public void glClearStencil(int s)
707
    {
708
    mClearStencil = s;
709
    }
710

    
711
///////////////////////////////////////////////////////////////////////////////////////////////////
712
/**
713
 * Which buffers to Clear at the beginning of each frame?
714
 * <p>
715
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
716
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
717
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
718
 *
719
 * @param mask bitwise OR of BUFFER_BITs to clear.
720
 */
721
  public void glClear(int mask)
722
    {
723
    mClear = mask;
724
    }
725

    
726
///////////////////////////////////////////////////////////////////////////////////////////////////
727
/**
728
 * Create new Projection matrix.
729
 *
730
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
731
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
732
 * @param near Distance between the screen plane and the near plane.
733
 *             Valid vaules: 0<near<1. When near==0 (illegal!), the Near Plane is exactly at the tip of
734
 *             the pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
735
 */
736
  public void setProjection(float fov, float near)
737
    {
738
    if( fov < 180.0f && fov >=0.0f )
739
      {
740
      mFOV = fov;
741
      }
742

    
743
    if( near<   1.0f && near> 0.0f )
744
      {
745
      mNear= near;
746
      }
747
    else if( near<=0.0f )
748
      {
749
      mNear = 0.01f;
750
      }
751
    else if( near>=1.0f )
752
      {
753
      mNear=0.99f;
754
      }
755

    
756
    if( mBuffer!=null )
757
      {
758
      for(int j=0; j<EffectQuality.LENGTH; j++) mBuffer[j].mNear = mNear;
759
      }
760

    
761
    createProjection();
762
    }
763

    
764
///////////////////////////////////////////////////////////////////////////////////////////////////
765
/**
766
 * Return the vertical field of view angle.
767
 *
768
 * @return Vertival Field of View Angle, in degrees.
769
 */
770
  public float getFOV()
771
    {
772
    return mFOV;
773
    }
774

    
775
///////////////////////////////////////////////////////////////////////////////////////////////////
776
/**
777
 * Resize the underlying Framebuffer.
778
 * <p>
779
 * This method can be safely called mid-render as it doesn't interfere with rendering.
780
 *
781
 * @param width The new width.
782
 * @param height The new height.
783
 */
784
  public void resize(int width, int height)
785
    {
786
    if( mWidth!=width || mHeight!=height )
787
      {
788
      mWidth = mRealWidth = width;
789
      mHeight= mRealHeight= height;
790

    
791
      createProjection();
792

    
793
      if( mColorCreated==CREATED )
794
        {
795
        markForCreation();
796
        recreate();
797
        }
798
      }
799
    }
800

    
801
///////////////////////////////////////////////////////////////////////////////////////////////////
802
/**
803
 * Return true if the Surface contains a DEPTH attachment.
804
 *
805
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
806
 */
807
  public boolean hasDepth()
808
    {
809
    return mDepthStencilCreated==CREATED;
810
    }
811

    
812
///////////////////////////////////////////////////////////////////////////////////////////////////
813
/**
814
 * Return true if the Surface contains a STENCIL attachment.
815
 *
816
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
817
 */
818
  public boolean hasStencil()
819
    {
820
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
821
    }
822

    
823
///////////////////////////////////////////////////////////////////////////////////////////////////
824
/**
825
 * When rendering this Node, should we use the Order Independent Transparency render more?
826
 * <p>
827
 * There are two modes of rendering: the fast 'normal' way, which however renders transparent
828
 * fragments in different ways depending on which fragments get rendered first, or the slower
829
 * 'oit' way, which renders transparent fragments correctly regardless of their order.
830
 *
831
 * @param oit True if we want to render more slowly, but in a way which accounts for transparency.
832
 */
833
  public void setOrderIndependentTransparency(boolean oit)
834
    {
835
    mRenderWayOIT = oit;
836
    }
837

    
838
///////////////////////////////////////////////////////////////////////////////////////////////////
839
/**
840
 * When rendering this Node, should we use the Order Independent Transparency render more?
841
 * <p>
842
 * There are two modes of rendering: the fast 'normal' way, which however renders transparent
843
 * fragments in different ways depending on which fragments get rendered first, or the slower
844
 * 'oit' way, which renders transparent fragments correctly regardless of their order.
845
 *
846
 * @param oit True if we want to render more slowly, but in a way which accounts for transparency.
847
 * @param initialSize Initial number of transparent fragments we expect, in screenfuls.
848
 *                    I.e '1.0' means 'the scene we are going to render contains about 1 screen
849
 *                    worth of transparent fragments'. Valid values: 0.0 &lt; initialSize &lt; 10.0
850
 *                    Even if you get this wrong, the library will detect that there are more
851
 *                    transparent fragments than it has space for and readjust its internal buffers,
852
 *                    but only after a few frames during which one will probably see missing objects.
853
 */
854
public void setOrderIndependentTransparency(boolean oit, float initialSize)
855
  {
856
  mRenderWayOIT = oit;
857

    
858
  if( initialSize>0.0f && initialSize<10.0f )
859
    Distorted.setSSBOSize(initialSize);
860
  }
861

    
862
///////////////////////////////////////////////////////////////////////////////////////////////////
863
/**
864
 * Adds a new child to the last position in the list of our Surface's children.
865
 * <p>
866
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
867
 * DistortedMaster (by calling doWork())
868
 *
869
 * @param node The new Node to add.
870
 */
871
  public void attach(DistortedNode node)
872
    {
873
    mChildren.attach(node);
874
    }
875

    
876
///////////////////////////////////////////////////////////////////////////////////////////////////
877
/**
878
 * Adds a new child to the last position in the list of our Surface's children.
879
 * <p>
880
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
881
 * DistortedMaster (by calling doWork())
882
 *
883
 * @param surface InputSurface to initialize our child Node with.
884
 * @param effects DistortedEffects to initialize our child Node with.
885
 * @param mesh MeshBase to initialize our child Node with.
886
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
887
 */
888
  public DistortedNode attach(DistortedSurface surface, DistortedEffects effects, MeshBase mesh)
889
    {
890
    return mChildren.attach(surface,effects,mesh);
891
    }
892

    
893
///////////////////////////////////////////////////////////////////////////////////////////////////
894
/**
895
 * Removes the first occurrence of a specified child from the list of children of our Surface.
896
 * <p>
897
 * A bit questionable method as there can be many different Nodes attached as children, some
898
 * of them having the same Effects but - for instance - different Mesh. Use with care.
899
 * <p>
900
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
901
 * DistortedMaster (by calling doWork())
902
 *
903
 * @param effects DistortedEffects to remove.
904
 */
905
  public void detach(DistortedEffects effects)
906
    {
907
    mChildren.detach(effects);
908
    }
909

    
910
///////////////////////////////////////////////////////////////////////////////////////////////////
911
/**
912
 * Removes the first occurrence of a specified child from the list of children of our Surface.
913
 * <p>
914
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
915
 * DistortedMaster (by calling doWork())
916
 *
917
 * @param node The Node to remove.
918
 */
919
  public void detach(DistortedNode node)
920
    {
921
    mChildren.detach(node);
922
    }
923

    
924
///////////////////////////////////////////////////////////////////////////////////////////////////
925
/**
926
 * Removes all children Nodes.
927
 * <p>
928
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
929
 * DistortedMaster (by calling doWork())
930
 */
931
  public void detachAll()
932
    {
933
    mChildren.detachAll();
934
    }
935
}
(10-10/19)