Project

General

Profile

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

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

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;
21

    
22
import android.opengl.GLES30;
23
import android.opengl.Matrix;
24
import java.util.ArrayList;
25

    
26
///////////////////////////////////////////////////////////////////////////////////////////////////
27

    
28
abstract class DistortedOutputSurface extends DistortedSurface implements DistortedSlave
29
{
30
/**
31
 * Do not create DEPTH or STENCIL attachment
32
 */
33
  public static final int NO_DEPTH_NO_STENCIL = 0;
34
/**
35
 * Create DEPTH, but not STENCIL
36
 */
37
  public static final int DEPTH_NO_STENCIL    = 1;
38
/**
39
 * Create both DEPTH and STENCIL
40
 */
41
  public static final int BOTH_DEPTH_STENCIL  = 2;
42

    
43
  private static final int ATTACH = 0;
44
  private static final int DETACH = 1;
45
  private static final int DETALL = 2;
46
  private static final int SORT   = 3;
47

    
48
  private ArrayList<DistortedNode> mChildren;
49
  private int mNumChildren;   // ==mChildren.length(), but we only create mChildren if the first one gets added
50

    
51
  private class Job
52
    {
53
    int type;
54
    DistortedNode node;
55
    DistortedEffectsPostprocess dep;
56

    
57
    Job(int t, DistortedNode n, DistortedEffectsPostprocess d)
58
      {
59
      type = t;
60
      node = n;
61
      dep  = d;
62
      }
63
    }
64

    
65
  private ArrayList<Job> mJobs = new ArrayList<>();
66

    
67
  DistortedFramebuffer[] mBuffer1, mBuffer2;
68

    
69
  private long mTime;
70
  private float mFOV;
71
  float mDistance, mNear;
72
  float[] mProjectionMatrix;
73

    
74
  int mDepthStencilCreated;
75
  int mDepthStencil;
76
  int[] mDepthStencilH = new int[1];
77
  int[] mFBOH          = new int[1];
78

    
79
  private float mClearR, mClearG, mClearB, mClearA;
80
  private float mClearDepth;
81
  private int mClearStencil;
82
  private int mClear;
83

    
84
//private String sNew="", sOld="";
85

    
86
  float mMipmap;
87

    
88
///////////////////////////////////////////////////////////////////////////////////////////////////
89

    
90
  DistortedOutputSurface(int width, int height, int createColor, int depthStencil, int fbo, int type)
91
    {
92
    super(width,height,createColor,type);
93

    
94
    mProjectionMatrix = new float[16];
95

    
96
    mFOV = 60.0f;
97
    mNear=  0.5f;
98

    
99
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
100
    mDepthStencil = depthStencil;
101

    
102
    mFBOH[0]         = fbo;
103
    mDepthStencilH[0]= 0;
104

    
105
    mTime = 0;
106

    
107
    mClearR = 0.0f;
108
    mClearG = 0.0f;
109
    mClearB = 0.0f;
110
    mClearA = 0.0f;
111

    
112
    mClearDepth = 1.0f;
113
    mClearStencil = 0;
114
    mClear = GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT;
115

    
116
    mBuffer1 = new DistortedFramebuffer[EffectQuality.LENGTH];
117
    mBuffer2 = new DistortedFramebuffer[EffectQuality.LENGTH];
118

    
119
    mMipmap = 1.0f;
120

    
121
    createProjection();
122
    }
123

    
124
///////////////////////////////////////////////////////////////////////////////////////////////////
125

    
126
  private void createProjection()
127
    {
128
    if( mWidth>0 && mHeight>1 )
129
      {
130
      if( mFOV>0.0f )  // perspective projection
131
        {
132
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
133
        float q = mWidth*mNear;
134
        float c = mHeight*mNear;
135

    
136
        float left   = -q/2;
137
        float right  = +q/2;
138
        float bottom = -c/2;
139
        float top    = +c/2;
140
        float near   =  c/a;
141

    
142
        mDistance    = mHeight/a;
143
        float far    = 2*mDistance-near;
144

    
145
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
146
        }
147
      else             // parallel projection
148
        {
149
        float left   = -mWidth/2.0f;
150
        float right  = +mWidth/2.0f;
151
        float bottom = -mHeight/2.0f;
152
        float top    = +mHeight/2.0f;
153
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
154
        mDistance    = mWidth+mHeight;
155
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
156

    
157
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
158
        }
159
      }
160
    }
161

    
162
///////////////////////////////////////////////////////////////////////////////////////////////////
163
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
164
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
165
// to a whole buffer and merge it.
166

    
167
  int renderChildren(long time, int num, ArrayList<DistortedNode> children)
168
    {
169
    int numRenders = 0;
170
    DistortedNode child;
171
    DistortedEffectsPostprocess lastP=null, currP;
172
    long lastB=0, currB;
173

    
174
//sNew = "";
175

    
176
    for(int i=0; i<num; i++)
177
      {
178
      child = children.get(i);
179
      currP = child.getEffectsPostprocess();
180
      currB = currP==null ? 0 : currP.getBucket();
181

    
182
//sNew += currB;
183

    
184
      if( lastB!=currB && lastB!=0 )
185
        {
186
        numRenders += lastP.postprocess(time,this);
187
        }
188

    
189
      if( currB==0 )
190
        {
191
        numRenders += child.draw(time,this);
192
        }
193
      else
194
        {
195
        if( mBuffer1[0]==null )
196
          {
197
          float mipmap=1.0f;
198

    
199
          for(int j=0; j<EffectQuality.LENGTH; j++)
200
            {
201
            mBuffer1[j] = new DistortedFramebuffer(mDepthStencil      ,TYPE_SYST, (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
202
            mBuffer2[j] = new DistortedFramebuffer(NO_DEPTH_NO_STENCIL,TYPE_SYST, (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
203
            mBuffer1[j].mMipmap = mipmap;
204
            mBuffer1[j].glClear(GLES30.GL_COLOR_BUFFER_BIT|GLES30.GL_DEPTH_BUFFER_BIT|GLES30.GL_STENCIL_BUFFER_BIT);
205
            mipmap *= EffectQuality.MULTIPLIER;
206
            }
207
          DistortedObject.toDo();  // create immediately
208
          }
209

    
210
        numRenders += child.draw(time,mBuffer1[currP.getQuality()]);
211

    
212
        if( i==num-1 )
213
          {
214
          numRenders += currP.postprocess(time,this);
215
          }
216
        }
217

    
218
      lastP = currP;
219
      lastB = currB;
220
      }
221
/*
222
if( !sNew.equals(sOld) )
223
  {
224
  sOld = sNew;
225
  android.util.Log.e("surface", "Surface"+getID()+": "+sOld);
226
  }
227
*/
228
    return numRenders;
229
    }
230

    
231
///////////////////////////////////////////////////////////////////////////////////////////////////
232

    
233
  void newJob(int t, DistortedNode n, DistortedEffectsPostprocess d)
234
    {
235
    mJobs.add(new Job(t,n,d));
236
    }
237

    
238
///////////////////////////////////////////////////////////////////////////////////////////////////
239
// PUBLIC API
240
///////////////////////////////////////////////////////////////////////////////////////////////////
241
/**
242
 * Draws all the attached children to this OutputSurface.
243
 * <p>
244
 * Must be called from a thread holding OpenGL Context.
245
 *
246
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
247
 * @return Number of objects rendered.
248
 */
249
  public int render(long time)
250
    {
251
    // change tree topology (attach and detach children)
252
/*
253
    boolean changed1 =
254
*/
255
    DistortedMaster.toDo();
256
/*
257
    if( changed1 )
258
      {
259
      for(int i=0; i<mNumChildren; i++)
260
        {
261
        mChildren.get(i).debug(0);
262
        }
263

    
264
      DistortedNode.debugMap();
265
      }
266
*/
267
    // create and delete all underlying OpenGL resources
268
    // Watch out: FIRST change topology, only then deal
269
    // with OpenGL resources. That's because changing Tree
270
    // can result in additional Framebuffers that would need
271
    // to be created immediately, before the calls to drawRecursive()
272
/*
273
    boolean changed2 =
274
*/
275
    toDo();
276
/*
277
    if( changed2 )
278
      {
279
      DistortedObject.debugLists();
280
      }
281
*/
282
    // mark OpenGL state as unknown
283
    DistortedRenderState.reset();
284

    
285
    int numRenders=0;
286

    
287
    for(int i=0; i<mNumChildren; i++)
288
      {
289
      numRenders += mChildren.get(i).renderRecursive(time);
290
      }
291

    
292
    setAsOutput(time);
293
    numRenders += renderChildren(time,mNumChildren,mChildren);
294

    
295
    return numRenders;
296
    }
297

    
298
///////////////////////////////////////////////////////////////////////////////////////////////////
299
/**
300
 * Bind this Surface as a Framebuffer we can render to.
301
 *
302
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
303
 *             out if this is the first time during present frame that this FBO is being set as output.
304
 *             If so, the library, in addition to binding the Surface for output, also clears the
305
 *             Surface's color and depth attachments.
306
 */
307
  public void setAsOutput(long time)
308
    {
309
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
310

    
311
    if( mTime!=time )
312
      {
313
      mTime = time;
314
      DistortedRenderState.colorDepthStencilOn();
315
      GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
316
      GLES30.glClearDepthf(mClearDepth);
317
      GLES30.glClearStencil(mClearStencil);
318
      GLES30.glClear(mClear);
319
      }
320
    }
321

    
322
///////////////////////////////////////////////////////////////////////////////////////////////////
323
/**
324
 * Set mipmap level.
325
 * <p>
326
 * Trick for speeding up your renders - one can create a pyramid of OutputSurface objects, each next
327
 * one some constant FACTOR smaller than the previous (0.5 is the common value), then set the Mipmap
328
 * Level of the i-th object to be FACTOR^i (we start counting from 0). When rendering any scene into
329
 * such prepared OutputSurface, the library will make sure to scale any Effects used so that the end
330
 * scene will end up looking identical no matter which object we render to. Identical, that is, except
331
 * for the loss of quality and gain in speed associated with rendering to a smaller Surface.
332
 * <p>
333
 * Example: if you create two FBOs, one 1000x1000 and another 500x500 in size, and set the second one
334
 * mipmap to 0.5 (the first one's is 1.0 by default), define Effects to be a single move by (100,100),
335
 * and render a skinned Mesh into both FBO, the end result will look proportionally the same, because
336
 * in the second case the move vector (100,100) will be auto-scaled to (50,50).
337
 *
338
 * @param mipmap The mipmap level. Acceptable range: 0&lt;mipmap&lt;infinity, although mipmap&gt;1
339
 *               does not make any sense (that would result in loss of speed and no gain in quality)
340
 */
341
  public void setMipmap(float mipmap)
342
    {
343
    mMipmap = mipmap;
344
    }
345

    
346
///////////////////////////////////////////////////////////////////////////////////////////////////
347
/**
348
 * Set the (R,G,B,A) values of GLES30.glClearColor() to set up color with which to clear
349
 * this Surface at the beginning of each frame.
350
 *
351
 * @param r the Red component. Default: 0.0f
352
 * @param g the Green component. Default: 0.0f
353
 * @param b the Blue component. Default: 0.0f
354
 * @param a the Alpha component. Default: 0.0f
355
 */
356
  public void glClearColor(float r, float g, float b, float a)
357
    {
358
    mClearR = r;
359
    mClearG = g;
360
    mClearB = b;
361
    mClearA = a;
362
    }
363

    
364
///////////////////////////////////////////////////////////////////////////////////////////////////
365
/**
366
 * Uses glClearDepthf() to set up a value with which to clear
367
 * the Depth buffer of our Surface at the beginning of each frame.
368
 *
369
 * @param d the Depth. Default: 1.0f
370
 */
371
  public void glClearDepthf(float d)
372
    {
373
    mClearDepth = d;
374
    }
375

    
376
///////////////////////////////////////////////////////////////////////////////////////////////////
377
/**
378
 * Uses glClearStencil() to set up a value with which to clear the
379
 * Stencil buffer of our Surface at the beginning of each frame.
380
 *
381
 * @param s the Stencil. Default: 0
382
 */
383
  public void glClearStencil(int s)
384
    {
385
    mClearStencil = s;
386
    }
387

    
388
///////////////////////////////////////////////////////////////////////////////////////////////////
389
/**
390
 * Which buffers to Clear at the beginning of each frame?
391
 * <p>
392
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
393
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
394
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
395
 *
396
 * @param mask bitwise OR of BUFFER_BITs to clear.
397
 */
398
  public void glClear(int mask)
399
    {
400
    mClear = mask;
401
    }
402

    
403
///////////////////////////////////////////////////////////////////////////////////////////////////
404
/**
405
 * Create new Projection matrix.
406
 *
407
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
408
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
409
 * @param near Distance between the screen plane and the near plane.
410
 *             Valid vaules: 0<near<1. When near==0, the Near Plane is exactly at the tip of the
411
 *             pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
412
 */
413
  public void setProjection(float fov, float near)
414
    {
415
    if( fov < 180.0f && fov >=0.0f )
416
      {
417
      mFOV = fov;
418
      }
419

    
420
    if( near<   1.0f && near> 0.0f )
421
      {
422
      mNear= near;
423
      }
424
    else if( near<=0.0f )
425
      {
426
      mNear = 0.01f;
427
      }
428
    else if( near>=1.0f )
429
      {
430
      mNear=0.99f;
431
      }
432

    
433
    createProjection();
434
    }
435

    
436
///////////////////////////////////////////////////////////////////////////////////////////////////
437
/**
438
 * Resize the underlying Framebuffer.
439
 * <p>
440
 * This method can be safely called mid-render as it doesn't interfere with rendering.
441
 *
442
 * @param width The new width.
443
 * @param height The new height.
444
 */
445
  public void resize(int width, int height)
446
    {
447
    if( mWidth!=width || mHeight!=height )
448
      {
449
      mWidth = width;
450
      mHeight= height;
451

    
452
      createProjection();
453

    
454
      if( mColorCreated==CREATED )
455
        {
456
        markForCreation();
457
        recreate();
458
        }
459
      }
460
    }
461

    
462
///////////////////////////////////////////////////////////////////////////////////////////////////
463
/**
464
 * Return true if the Surface contains a DEPTH attachment.
465
 *
466
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
467
 */
468
  public boolean hasDepth()
469
    {
470
    return mDepthStencilCreated==CREATED;
471
    }
472

    
473
///////////////////////////////////////////////////////////////////////////////////////////////////
474
/**
475
 * Return true if the Surface contains a STENCIL attachment.
476
 *
477
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
478
 */
479
  public boolean hasStencil()
480
    {
481
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
482
    }
483

    
484
///////////////////////////////////////////////////////////////////////////////////////////////////
485
/**
486
 * Adds a new child to the last position in the list of our Surface's children.
487
 * <p>
488
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
489
 * DistortedMaster (by calling doWork())
490
 *
491
 * @param node The new Node to add.
492
 */
493
  public void attach(DistortedNode node)
494
    {
495
    mJobs.add(new Job(ATTACH,node,null));
496
    DistortedMaster.newSlave(this);
497
    }
498

    
499
///////////////////////////////////////////////////////////////////////////////////////////////////
500
/**
501
 * Adds a new child to the last position in the list of our Surface's children.
502
 * <p>
503
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
504
 * DistortedMaster (by calling doWork())
505
 *
506
 * @param surface InputSurface to initialize our child Node with.
507
 * @param effects DistortedEffects to initialize our child Node with.
508
 * @param mesh MeshObject to initialize our child Node with.
509
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
510
 */
511
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
512
    {
513
    DistortedNode node = new DistortedNode(surface,effects,mesh);
514
    mJobs.add(new Job(ATTACH,node,null));
515
    DistortedMaster.newSlave(this);
516
    return node;
517
    }
518

    
519
///////////////////////////////////////////////////////////////////////////////////////////////////
520
/**
521
 * Removes the first occurrence of a specified child from the list of children of our Surface.
522
 * <p>
523
 * A bit questionable method as there can be many different Nodes attached as children, some
524
 * of them having the same Effects but - for instance - different Mesh. Use with care.
525
 * <p>
526
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
527
 * DistortedMaster (by calling doWork())
528
 *
529
 * @param effects DistortedEffects to remove.
530
 */
531
  public void detach(DistortedEffects effects)
532
    {
533
    long id = effects.getID();
534
    DistortedNode node;
535
    boolean detached = false;
536

    
537
    for(int i=0; i<mNumChildren; i++)
538
      {
539
      node = mChildren.get(i);
540

    
541
      if( node.getEffects().getID()==id )
542
        {
543
        detached = true;
544
        mJobs.add(new Job(DETACH,node,null));
545
        DistortedMaster.newSlave(this);
546
        break;
547
        }
548
      }
549

    
550
    if( !detached )
551
      {
552
      // if we failed to detach any, it still might be the case that
553
      // there's an ATTACH job that we need to cancel.
554
      int num = mJobs.size();
555
      Job job;
556

    
557
      for(int i=0; i<num; i++)
558
        {
559
        job = mJobs.get(i);
560

    
561
        if( job.type==ATTACH && job.node.getEffects()==effects )
562
          {
563
          mJobs.remove(i);
564
          break;
565
          }
566
        }
567
      }
568
    }
569

    
570
///////////////////////////////////////////////////////////////////////////////////////////////////
571
/**
572
 * Removes the first occurrence of a specified child from the list of children of our Surface.
573
 * <p>
574
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
575
 * DistortedMaster (by calling doWork())
576
 *
577
 * @param node The Node to remove.
578
 */
579
  public void detach(DistortedNode node)
580
    {
581
    mJobs.add(new Job(DETACH,node,null));
582
    DistortedMaster.newSlave(this);
583
    }
584

    
585
///////////////////////////////////////////////////////////////////////////////////////////////////
586
/**
587
 * Removes all children Nodes.
588
 * <p>
589
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
590
 * DistortedMaster (by calling doWork())
591
 */
592
  public void detachAll()
593
    {
594
    mJobs.add(new Job(DETALL,null,null));
595
    DistortedMaster.newSlave(this);
596
    }
597

    
598
///////////////////////////////////////////////////////////////////////////////////////////////////
599
/**
600
 * This is not really part of the public API. Has to be public only because it is a part of the
601
 * DistortedSlave interface, which should really be a class that we extend here instead but
602
 * Java has no multiple inheritance.
603
 *
604
 * @y.exclude
605
 */
606
  public void doWork()
607
    {
608
    int num = mJobs.size();
609
    Job job;
610

    
611
    for(int i=0; i<num; i++)
612
      {
613
      job = mJobs.remove(0);
614

    
615
      switch(job.type)
616
        {
617
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
618
                     job.node.setSurfaceParent(this);
619
                     DistortedMaster.addSorted(mChildren,job.node);
620
                     mNumChildren++;
621
                     break;
622
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
623
                       {
624
                       job.node.setSurfaceParent(null);
625
                       mNumChildren--;
626
                       }
627
                     break;
628
        case DETALL: if( mNumChildren>0 )
629
                       {
630
                       DistortedNode tmp;
631

    
632
                       for(int j=mNumChildren-1; j>=0; j--)
633
                         {
634
                         tmp = mChildren.remove(j);
635
                         tmp.setSurfaceParent(null);
636
                         }
637

    
638
                       mNumChildren = 0;
639
                       }
640
                     break;
641
        case SORT  : job.node.setPost(job.dep);
642
                     mChildren.remove(job.node);
643
                     DistortedMaster.addSorted(mChildren,job.node);
644
                     break;
645
        }
646
      }
647
    }
648
}
(9-9/26)