Project

General

Profile

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

library / src / main / java / org / distorted / library / main / InternalOutputSurface.java @ b7074bc6

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.GLES30;
23
import android.opengl.GLES31;
24
import android.opengl.Matrix;
25

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

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

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

    
45
  private float mFOV;
46

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

    
53
  // Global buffers used for postprocessing
54
  private static DistortedFramebuffer[] mBuffer= new DistortedFramebuffer[EffectQuality.LENGTH];
55

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

    
65
///////////////////////////////////////////////////////////////////////////////////////////////////
66

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

    
71
    mRenderWayOIT = false;
72
    mCurrFBO      = 0;
73

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

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

    
80
    mRealWidth = mWidth = width;
81
    mRealHeight= mHeight= height;
82

    
83
    mProjectionMatrix = new float[16];
84

    
85
    mFOV = DEFAULT_FOV;
86
    mNear= DEFAULT_NEAR;
87

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

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

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

    
99
    mClearDepth = 1.0f;
100
    mClearStencil = 0;
101
    mClear = GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT;
102

    
103
    mMipmap = 1.0f;
104

    
105
    mChildren = new InternalChildrenList(this);
106

    
107
    createProjection();
108
    }
109

    
110
///////////////////////////////////////////////////////////////////////////////////////////////////
111

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

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

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

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

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

    
148
///////////////////////////////////////////////////////////////////////////////////////////////////
149

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

    
159
    float mipmap=1.0f;
160

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

    
163
    mBuffer[quality] = new DistortedFramebuffer(DistortedLibrary.FBO_QUEUE_SIZE,2,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(width*mipmap), (int)(height*mipmap) );
164
    mBuffer[quality].mMipmap = mipmap;
165
    mBuffer[quality].mNear = near;  // copy mNear as well (for blitting- see PostprocessEffect.apply() )
166
    mBuffer[quality].glClearColor(CLEAR_R, CLEAR_G, CLEAR_B, CLEAR_A);
167

    
168
    InternalObject.toDo(); // create the FBOs immediately. This is safe as we must be holding the OpenGL context now.
169

    
170
    InternalRenderState.colorDepthStencilOn();
171
    GLES30.glClearColor(CLEAR_R, CLEAR_G, CLEAR_B, CLEAR_A);
172
    GLES30.glClearDepthf(CLEAR_D);
173
    GLES30.glClearStencil(CLEAR_S);
174

    
175
    for(int k = 0; k< DistortedLibrary.FBO_QUEUE_SIZE; k++)
176
      {
177
      GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mBuffer[quality].mFBOH[k]);
178
      GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mBuffer[quality].mColorH[2*k+1], 0);
179
      GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT | GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_STENCIL_BUFFER_BIT);
180
      GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mBuffer[quality].mColorH[2*k  ], 0);
181
      GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
182
      }
183

    
184
    InternalRenderState.colorDepthStencilRestore();
185

    
186
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0);
187
    }
188

    
189
///////////////////////////////////////////////////////////////////////////////////////////////////
190

    
191
  static synchronized void onDestroy()
192
    {
193
    for (int j=0; j<EffectQuality.LENGTH; j++)
194
      if( mBuffer[j]!=null )
195
        {
196
        mBuffer[j].markForDeletion();
197
        mBuffer[j] = null;
198
        }
199
    }
200

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

    
210
  private static void clonePostprocessingViewportAndProjection(InternalOutputSurface surface, InternalOutputSurface from)
211
    {
212
    if( surface.mWidth != from.mWidth || surface.mHeight != from.mHeight ||
213
        surface.mFOV   != from.mFOV   || surface.mNear   != from.mNear    )
214
      {
215
      surface.mWidth  = (int)(from.mWidth *surface.mMipmap);
216
      surface.mHeight = (int)(from.mHeight*surface.mMipmap);
217
      surface.mFOV    = from.mFOV;
218
      surface.mNear   = from.mNear;  // Near plane is independent of the mipmap level
219

    
220
      surface.createProjection();
221

    
222
      int maxw = Math.max(surface.mWidth , surface.mRealWidth );
223
      int maxh = Math.max(surface.mHeight, surface.mRealHeight);
224

    
225
      if (maxw > surface.mRealWidth || maxh > surface.mRealHeight)
226
        {
227
        surface.mRealWidth = maxw;
228
        surface.mRealHeight = maxh;
229

    
230
        surface.recreate();
231
        surface.create();
232
        }
233
      }
234
    }
235

    
236
///////////////////////////////////////////////////////////////////////////////////////////////////
237

    
238
  private int blitWithDepth(long currTime, InternalOutputSurface buffer, int fbo)
239
    {
240
    GLES30.glViewport(0, 0, mWidth, mHeight);
241
    setAsOutput(currTime);
242
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
243
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
244
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
245
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
246

    
247
    GLES30.glDisable(GLES30.GL_STENCIL_TEST);
248
    GLES30.glStencilMask(0x00);
249

    
250
    DistortedLibrary.blitDepthPriv(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
251
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
252
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
253
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
254
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
255

    
256
    // clear buffers
257
    GLES30.glStencilMask(0xff);
258
    GLES30.glDepthMask(true);
259
    GLES30.glColorMask(true,true,true,true);
260
    GLES30.glClearColor(buffer.mClearR,buffer.mClearG,buffer.mClearB,buffer.mClearA);
261
    GLES30.glClearDepthf(buffer.mClearDepth);
262
    GLES30.glClearStencil(buffer.mClearStencil);
263

    
264
    buffer.setAsOutput();
265
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, buffer.mColorH[2*fbo+1], 0);
266
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT|GLES30.GL_DEPTH_BUFFER_BIT|GLES30.GL_STENCIL_BUFFER_BIT);
267
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, buffer.mColorH[2*fbo  ], 0);
268
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
269

    
270
    return 1;
271
    }
272

    
273
///////////////////////////////////////////////////////////////////////////////////////////////////
274

    
275
  private static void oitClear(InternalOutputSurface buffer)
276
    {
277
    int counter = DistortedLibrary.zeroOutAtomic();
278
    DistortedLibrary.oitClear(buffer,counter);
279
    GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT|GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
280
    }
281

    
282
///////////////////////////////////////////////////////////////////////////////////////////////////
283

    
284
  private int oitBuild(long time, InternalOutputSurface buffer, int fbo)
285
    {
286
    GLES30.glViewport(0, 0, mWidth, mHeight);
287
    setAsOutput(time);
288
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
289
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mColorH[2*fbo]);
290
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
291
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mDepthStencilH[fbo]);
292

    
293
    InternalRenderState.colorDepthStencilOn();
294
    InternalRenderState.enableDepthTest();
295

    
296
    DistortedLibrary.oitBuild(this, buffer.getWidthCorrection(), buffer.getHeightCorrection() );
297
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
298
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
299
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
300
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
301

    
302
    InternalRenderState.colorDepthStencilRestore();
303
    InternalRenderState.restoreDepthTest();
304

    
305
    return 1;
306
    }
307

    
308
///////////////////////////////////////////////////////////////////////////////////////////////////
309
// two phases: 1. collapse the SSBO 2. blend the ssbo's color
310

    
311
  private int oitRender(long currTime, int fbo)
312
    {
313
    float corrW = getWidthCorrection();
314
    float corrH = getHeightCorrection();
315

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

    
319
    if( mDepthStencilH[fbo] != 0 )
320
      {
321
      GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, 0);
322
      GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
323
      GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, mDepthStencilH[fbo]);
324
      InternalRenderState.switchOffColorDepthStencil();
325
      DistortedLibrary.oitCollapse(this, corrW, corrH);
326
      GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
327
      }
328

    
329
    setAsOutput(currTime);
330
    InternalRenderState.switchColorDepthOnStencilOff();
331
    DistortedLibrary.oitRender(this, corrW, corrH);
332
    InternalRenderState.restoreColorDepthStencil();
333

    
334
    return 1;
335
    }
336

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

    
339
  private void clear()
340
    {
341
    InternalRenderState.colorDepthStencilOn();
342
    GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
343
    GLES30.glClearDepthf(mClearDepth);
344
    GLES30.glClearStencil(mClearStencil);
345
    GLES30.glClear(mClear);
346
    InternalRenderState.colorDepthStencilRestore();
347
    }
348

    
349
///////////////////////////////////////////////////////////////////////////////////////////////////
350

    
351
  void setCurrFBO(int fbo)
352
    {
353
    mCurrFBO = fbo;
354
    }
355

    
356
///////////////////////////////////////////////////////////////////////////////////////////////////
357
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
358
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
359
// to a whole buffer (lastQueue.postprocess) and merge it (this.oitBuild or blitWithDepth - depending
360
// on the type of rendering)
361

    
362
  int renderChildren(long time, int numChildren, InternalChildrenList children, int fbo, boolean oit)
363
    {
364
    int numRenders=0, bucketChange=0;
365
    DistortedNode child;
366
    DistortedFramebuffer buffer=null;
367
    EffectQueuePostprocess lastQueue=null, currQueue;
368
    long lastBucket=0, currBucket;
369
    boolean renderDirectly=false;
370

    
371
    setCurrFBO(fbo);
372

    
373
    if( oit && numChildren>0 )
374
      {
375
      oitClear(this);
376
      }
377

    
378
    for(int i=0; i<numChildren; i++)
379
      {
380
      child = children.getChild(i);
381
      currQueue = (EffectQueuePostprocess)child.getEffects().getQueues()[3];
382
      currBucket= currQueue.getID();
383

    
384
      if( currBucket==0 )
385
        {
386
        setAsOutput(time);
387

    
388
        if( oit )
389
          {
390
          numRenders += child.drawOIT(time, this);
391
          GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
392
          }
393
        else
394
          {
395
          numRenders += child.draw(time, this);
396
          }
397
        }
398
      else
399
        {
400
        int currQuality = currQueue.getQuality();
401

    
402
        if( mBuffer[currQuality]==null ) createPostprocessingBuffers(currQuality, mWidth, mHeight, mNear);
403
        mBuffer[currQuality].setCurrFBO(fbo);
404

    
405
        if( lastBucket!=currBucket )
406
          {
407
          if( lastBucket==0 )
408
            {
409
            clonePostprocessingViewportAndProjection(mBuffer[currQuality],this);
410
            }
411
          else
412
            {
413
            for(int j=bucketChange; j<i; j++)
414
              {
415
              DistortedNode node = children.getChild(j);
416

    
417
              if( node.getSurface().setAsInput() )
418
                {
419
                buffer.setAsOutput();
420
                numRenders += lastQueue.preprocess( buffer, node, buffer.mDistance, buffer.mMipmap, buffer.mProjectionMatrix );
421
                }
422
              }
423
            numRenders += lastQueue.postprocess(buffer);
424

    
425
            if( oit )
426
              {
427
              numRenders += oitBuild(time, buffer, fbo);
428
              GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
429
              }
430
            else
431
              {
432
              numRenders += blitWithDepth(time, buffer, fbo);
433
              }
434
            buffer.clearBuffer(fbo);
435
            }
436

    
437
          buffer= mBuffer[currQuality];
438
          bucketChange= i;
439
          renderDirectly = currQueue.getRender();
440
          }
441

    
442
        if( renderDirectly )
443
          {
444
          setAsOutput(time);
445

    
446
          if( oit )
447
            {
448
            numRenders += child.drawOIT(time, this);
449
            GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
450
            }
451
          else
452
            {
453
            numRenders += child.draw(time, this);
454
            }
455
          }
456
        else
457
          {
458
          buffer.setAsOutput(time);
459
          child.drawNoBlend(time, buffer);
460
          }
461

    
462
        if( i==numChildren-1 )
463
          {
464
          for(int j=bucketChange; j<numChildren; j++)
465
            {
466
            DistortedNode node = children.getChild(j);
467

    
468
            if( node.getSurface().setAsInput() )
469
              {
470
              buffer.setAsOutput();
471
              numRenders += currQueue.preprocess( buffer, node, buffer.mDistance, buffer.mMipmap, buffer.mProjectionMatrix );
472
              }
473
            }
474
          numRenders += currQueue.postprocess(buffer);
475

    
476
          if( oit )
477
            {
478
            numRenders += oitBuild(time, buffer, fbo);
479
            GLES31.glMemoryBarrier(GLES31.GL_SHADER_STORAGE_BARRIER_BIT | GLES31.GL_ATOMIC_COUNTER_BARRIER_BIT);
480
            buffer.clearBuffer(fbo);
481
            }
482
          else
483
            {
484
            numRenders += blitWithDepth(time, buffer,fbo);
485
            }
486
          }
487
        } // end else (postprocessed child)
488

    
489
      lastQueue = currQueue;
490
      lastBucket= currBucket;
491
      } // end main for loop
492

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

    
498
    return numRenders;
499
    }
500

    
501
///////////////////////////////////////////////////////////////////////////////////////////////////
502
/**
503
 * Not part of the public API.
504
 *
505
 * @y.exclude
506
 */
507
  public void adjustIsomorphism() { }
508

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

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

    
531
///////////////////////////////////////////////////////////////////////////////////////////////////
532

    
533
  void clearBuffer(int fbo)
534
    {
535
    InternalRenderState.colorDepthStencilOn();
536

    
537
    GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
538
    GLES30.glClearDepthf(mClearDepth);
539
    GLES30.glClearStencil(mClearStencil);
540

    
541
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[fbo]);
542
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mColorH[2*fbo+1], 0);
543
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT|GLES30.GL_DEPTH_BUFFER_BIT|GLES30.GL_STENCIL_BUFFER_BIT);
544
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mColorH[2*fbo  ], 0);
545
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
546

    
547
    InternalRenderState.colorDepthStencilRestore();
548
    }
549

    
550
///////////////////////////////////////////////////////////////////////////////////////////////////
551

    
552
  void setAsOutput(long time)
553
    {
554
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[mCurrFBO]);
555

    
556
    if( mTime[mCurrFBO]!=time )
557
      {
558
      mTime[mCurrFBO] = time;
559
      clear();
560
      }
561
    }
562

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

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

    
595
    int numRenders=0, numChildren = mChildren.getNumChildren();
596
    DistortedNode node;
597
    long oldBucket=0, newBucket;
598

    
599
    for(int i=0; i<numChildren; i++)
600
      {
601
      node = mChildren.getChild(i);
602
      newBucket = node.getBucket();
603
      numRenders += node.renderRecursive(time);
604
      if( newBucket<oldBucket ) mChildren.rearrangeByBuckets(i,newBucket);
605
      else oldBucket=newBucket;
606
      }
607

    
608
    numRenders += renderChildren(time,numChildren,mChildren,fbo, mRenderWayOIT);
609

    
610
    return numRenders;
611
    }
612

    
613
///////////////////////////////////////////////////////////////////////////////////////////////////
614
/**
615
 * Bind this Surface as a Framebuffer we can render to.
616
 * <p>
617
 * This version does not attempt to clear anything.
618
 */
619
  public void setAsOutput()
620
    {
621
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[mCurrFBO]);
622
    }
623

    
624
///////////////////////////////////////////////////////////////////////////////////////////////////
625
/**
626
 * Return the Near plane of the Projection included in the Surface.
627
 *
628
 * @return the Near plane.
629
 */
630
  public float getNear()
631
    {
632
    return mNear;
633
    }
634

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

    
659
///////////////////////////////////////////////////////////////////////////////////////////////////
660
/**
661
 * Set the (R,G,B,A) values of GLES31.glClearColor() to set up color with which to clear
662
 * this Surface at the beginning of each frame.
663
 *
664
 * @param r the Red component. Default: 0.0f
665
 * @param g the Green component. Default: 0.0f
666
 * @param b the Blue component. Default: 0.0f
667
 * @param a the Alpha component. Default: 0.0f
668
 */
669
  public void glClearColor(float r, float g, float b, float a)
670
    {
671
    mClearR = r;
672
    mClearG = g;
673
    mClearB = b;
674
    mClearA = a;
675
    }
676

    
677
///////////////////////////////////////////////////////////////////////////////////////////////////
678
/**
679
 * Uses glClearDepthf() to set up a value with which to clear
680
 * the Depth buffer of our Surface at the beginning of each frame.
681
 *
682
 * @param d the Depth. Default: 1.0f
683
 */
684
  public void glClearDepthf(float d)
685
    {
686
    mClearDepth = d;
687
    }
688

    
689
///////////////////////////////////////////////////////////////////////////////////////////////////
690
/**
691
 * Uses glClearStencil() to set up a value with which to clear the
692
 * Stencil buffer of our Surface at the beginning of each frame.
693
 *
694
 * @param s the Stencil. Default: 0
695
 */
696
  public void glClearStencil(int s)
697
    {
698
    mClearStencil = s;
699
    }
700

    
701
///////////////////////////////////////////////////////////////////////////////////////////////////
702
/**
703
 * Which buffers to Clear at the beginning of each frame?
704
 * <p>
705
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
706
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
707
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
708
 *
709
 * @param mask bitwise OR of BUFFER_BITs to clear.
710
 */
711
  public void glClear(int mask)
712
    {
713
    mClear = mask;
714
    }
715

    
716
///////////////////////////////////////////////////////////////////////////////////////////////////
717
/**
718
 * Create new Projection matrix.
719
 *
720
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
721
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
722
 * @param near The Near plane.
723
 */
724
  public void setProjection(float fov, float near)
725
    {
726
    if( fov < 180.0f && fov >=0.0f )
727
      {
728
      mFOV = fov;
729
      }
730

    
731
    if( near<   1.0f && near> 0.0f )
732
      {
733
      mNear= near;
734
      }
735
    else if( near<=0.0f )
736
      {
737
      mNear = 0.01f;
738
      }
739
    else if( near>=1.0f )
740
      {
741
      mNear=0.99f;
742
      }
743

    
744
    for(int j=0; j<EffectQuality.LENGTH; j++)
745
      {
746
      if( mBuffer[j]!=null ) mBuffer[j].mNear = mNear;
747
      }
748

    
749
    createProjection();
750
    }
751

    
752
///////////////////////////////////////////////////////////////////////////////////////////////////
753
/**
754
 * Return the vertical field of view angle.
755
 *
756
 * @return Vertival Field of View Angle, in degrees.
757
 */
758
  public float getFOV()
759
    {
760
    return mFOV;
761
    }
762

    
763
///////////////////////////////////////////////////////////////////////////////////////////////////
764
/**
765
 * Resize the underlying Framebuffer.
766
 * <p>
767
 * This method can be safely called mid-render as it doesn't interfere with rendering.
768
 *
769
 * @param width The new width.
770
 * @param height The new height.
771
 */
772
  public void resize(int width, int height)
773
    {
774
    if( mWidth!=width || mHeight!=height )
775
      {
776
      mWidth = mRealWidth = width;
777
      mHeight= mRealHeight= height;
778

    
779
      createProjection();
780

    
781
      if( mColorCreated==CREATED )
782
        {
783
        markForCreation();
784
        recreate();
785
        }
786
      }
787
    }
788

    
789
///////////////////////////////////////////////////////////////////////////////////////////////////
790
/**
791
 * Return true if the Surface contains a DEPTH attachment.
792
 *
793
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
794
 */
795
  public boolean hasDepth()
796
    {
797
    return mDepthStencilCreated==CREATED;
798
    }
799

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

    
811
///////////////////////////////////////////////////////////////////////////////////////////////////
812
/**
813
 * When rendering this Node, should we use the Order Independent Transparency render mode?
814
 * <p>
815
 * This feature requires OpenGL ES 3.1. If we are running on OpenGL 3.0, this will do nothing.
816
 * Also, if you are running on a buggy driver ( Imagination GE8100/8300 driver build 1.8@4490469 )
817
 * then do nothing.
818
 *
819
 * There are two modes of rendering: the fast 'normal' way, which however renders transparent
820
 * fragments in different ways depending on which fragments get rendered first, or the slower
821
 * 'oit' way, which renders transparent fragments correctly regardless of their order.
822
 *
823
 * @param oit True if we want to render more slowly, but in a way which accounts for transparency.
824
 */
825
  public void setOrderIndependentTransparency(boolean oit)
826
    {
827
    if( DistortedLibrary.getGLSL()>=310 && DistortedLibrary.OITCompilationSuccessful() )
828
      {
829
      mRenderWayOIT = oit;
830
      }
831
    }
832

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

    
859
      if( initialSize>0.0f && initialSize<10.0f )
860
        {
861
        DistortedLibrary.setSSBOSize(initialSize);
862
        }
863
      }
864
    }
865

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

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

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

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

    
928
///////////////////////////////////////////////////////////////////////////////////////////////////
929
/**
930
 * Removes all children Nodes.
931
 * <p>
932
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
933
 * InternalMaster (by calling doWork())
934
 */
935
  public void detachAll()
936
    {
937
    mChildren.detachAll();
938
    }
939

    
940
///////////////////////////////////////////////////////////////////////////////////////////////////
941
/**
942
 * Return the width of this Surface.
943
 *
944
 * @return width of the Object, in pixels.
945
 */
946
  public int getWidth()
947
    {
948
    return mWidth;
949
    }
950

    
951
///////////////////////////////////////////////////////////////////////////////////////////////////
952
/**
953
 * Return the height of this Surface.
954
 *
955
 * @return height of the Object, in pixels.
956
 */
957
  public int getHeight()
958
    {
959
    return mHeight;
960
    }
961
}
(12-12/14)