Project

General

Profile

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

library / src / main / java / org / distorted / library / DistortedOutputSurface.java @ 78db8663

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
  private static final int NUM_MIPMAP = 4;
31
          static final int CUR_MIPMAP = 0;
32

    
33
  private static final int ATTACH = 0;
34
  private static final int DETACH = 1;
35
  private static final int DETALL = 2;
36
  private static final int SORT   = 3;
37

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

    
41
  private class Job
42
    {
43
    int type;
44
    DistortedNode node;
45
    DistortedEffectsPostprocess dep;
46

    
47
    Job(int t, DistortedNode n, DistortedEffectsPostprocess d)
48
      {
49
      type = t;
50
      node = n;
51
      dep  = d;
52
      }
53
    }
54

    
55
  private ArrayList<Job> mJobs = new ArrayList<>();
56

    
57
  DistortedFramebuffer[] mBuffer1, mBuffer2;
58

    
59
  private long mTime;
60
  private float mFOV;
61
  float mDistance, mNear;
62
  float[] mProjectionMatrix;
63

    
64
  int mDepthCreated;
65
  int[] mDepthH = new int[1];
66
  int[] mFBOH   = new int[1];
67

    
68
  private float mClearR, mClearG, mClearB, mClearA;
69
  private float mClearDepth;
70

    
71
//private String sNew="", sOld="";
72

    
73
  float mMipmap;
74

    
75
///////////////////////////////////////////////////////////////////////////////////////////////////
76

    
77
  DistortedOutputSurface(int width, int height, int createColor, int createDepth, int fbo, int type)
78
    {
79
    super(width,height,createColor,type);
80

    
81
    mProjectionMatrix = new float[16];
82

    
83
    mWidth = width;
84
    mHeight= height;
85

    
86
    mFOV = 60.0f;
87
    mNear=  0.5f;
88

    
89
    mDepthCreated= createDepth;
90
    mFBOH[0]     = fbo;
91
    mDepthH[0]   = 0;
92

    
93
    mTime = 0;
94

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

    
100
    mClearDepth = 1.0f;
101

    
102
    mBuffer1 = new DistortedFramebuffer[NUM_MIPMAP];
103
    mBuffer2 = new DistortedFramebuffer[NUM_MIPMAP];
104
    mMipmap = 1.0f;
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
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
149
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
150
// to a whole buffer and merge it.
151

    
152
  int renderChildren(long time, int num, ArrayList<DistortedNode> children)
153
    {
154
    int numRenders = 0;
155
    DistortedNode child;
156
    DistortedEffectsPostprocess lastP=null, currP;
157
    long lastB=0, currB;
158

    
159
//sNew = "";
160

    
161
    for(int i=0; i<num; i++)
162
      {
163
      child = children.get(i);
164
      currP = child.getEffectsPostprocess();
165
      currB = currP==null ? 0 : currP.getBucket();
166

    
167
//sNew += currB;
168

    
169
      if( lastB!=currB && lastB!=0 )
170
        {
171
        numRenders += lastP.postprocess(time,this);
172
        }
173

    
174
      if( currB==0 )
175
        {
176
        numRenders += child.draw(time,this);
177
        }
178
      else
179
        {
180
        if( mBuffer1[0]==null )
181
          {
182
          float mipmap=1.0f;
183

    
184
          for(int j=0; j<NUM_MIPMAP; j++)
185
            {
186
            mBuffer1[j] = new DistortedFramebuffer( mDepthCreated!=DONT_CREATE, DistortedSurface.TYPE_SYST,
187
                                                    (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
188
            mBuffer2[j] = new DistortedFramebuffer(false                     , DistortedSurface.TYPE_SYST,
189
                                                    (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
190
            mBuffer1[j].mMipmap = mipmap;
191
            mipmap *= 0.5f;
192
            }
193
          DistortedSurface.toDo();  // create immediately
194
          }
195

    
196
        numRenders += child.draw(time,mBuffer1[CUR_MIPMAP]);
197
        if( i==num-1 )
198
          {
199
          numRenders += currP.postprocess(time,this);
200
          }
201
        }
202

    
203
      lastP = currP;
204
      lastB = currB;
205
      }
206
/*
207
if( !sNew.equals(sOld) )
208
  {
209
  sOld = sNew;
210
  android.util.Log.e("surface", "Surface"+getID()+": "+sOld);
211
  }
212
*/
213
    return numRenders;
214
    }
215

    
216
///////////////////////////////////////////////////////////////////////////////////////////////////
217

    
218
  void newJob(int t, DistortedNode n, DistortedEffectsPostprocess d)
219
    {
220
    mJobs.add(new Job(t,n,d));
221
    }
222

    
223
///////////////////////////////////////////////////////////////////////////////////////////////////
224
// PUBLIC API
225
///////////////////////////////////////////////////////////////////////////////////////////////////
226
/**
227
 * Draws all the attached children to this OutputSurface.
228
 * <p>
229
 * Must be called from a thread holding OpenGL Context.
230
 *
231
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
232
 * @return Number of objects rendered.
233
 */
234
  public int render(long time)
235
    {
236
    // change tree topology (attach and detach children)
237
/*
238
    boolean changed =
239
*/
240
    DistortedMaster.toDo();
241
/*
242
    // debugging only
243
    if( changed )
244
      {
245
      for(int i=0; i<mNumChildren; i++)
246
        {
247
        mChildren.get(i).debug(0);
248
        }
249

    
250
      DistortedNode.debugMap();
251
      }
252
*/
253
    // create and delete all underlying OpenGL resources
254
    // Watch out: FIRST change topology, only then deal
255
    // with OpenGL resources. That's because changing Tree
256
    // can result in additional Framebuffers that would need
257
    // to be created immediately, before the calls to drawRecursive()
258
    toDo();
259
/*
260
    // debugging only
261
    if( changed )
262
      {
263
      DistortedSurface.debugLists();
264
      }
265
*/
266
    // mark OpenGL state as unknown
267
    DistortedRenderState.reset();
268

    
269
    int numRenders=0;
270

    
271
    for(int i=0; i<mNumChildren; i++)
272
      {
273
      numRenders += mChildren.get(i).renderRecursive(time);
274
      }
275

    
276
    setAsOutput(time);
277
    numRenders += renderChildren(time,mNumChildren,mChildren);
278

    
279
    return numRenders;
280
    }
281

    
282
///////////////////////////////////////////////////////////////////////////////////////////////////
283
/**
284
 * Bind this Surface as a Framebuffer we can render to.
285
 *
286
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
287
 *             out if this is the first time during present frame that this FBO is being set as output.
288
 *             If so, the library, in addition to binding the Surface for output, also clears the
289
 *             Surface's color and depth attachments.
290
 */
291
  public void setAsOutput(long time)
292
    {
293
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
294

    
295
    if( mTime!=time )
296
      {
297
      mTime = time;
298
      DistortedRenderState.colorDepthOn();
299
      GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
300
      GLES30.glClearDepthf(mClearDepth);
301
      GLES30.glClear( GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT);
302
      }
303
    }
304

    
305
///////////////////////////////////////////////////////////////////////////////////////////////////
306
/**
307
 * Set the (R,G,B,A) values of GLES30.glClearColor() to set up color with which to clear
308
 * this Surface before each render.
309
 *
310
 * @param r the Red component. Default: 0.0f
311
 * @param g the Green component. Default: 0.0f
312
 * @param b the Blue component. Default: 0.0f
313
 * @param a the Alpha component. Default: 0.0f
314
 */
315
  public void glClearColor(float r, float g, float b, float a)
316
    {
317
    mClearR = r;
318
    mClearG = g;
319
    mClearB = b;
320
    mClearA = a;
321
    }
322

    
323
///////////////////////////////////////////////////////////////////////////////////////////////////
324
/**
325
 * Set the Depth value of GLES30.glClearDepthf() to set up depth with which to clear
326
 * the Depth buffer of Surface before each render.
327
 *
328
 * @param d the Depth. Default: 1.0f
329
 */
330
  public void glClearDepthf(float d)
331
    {
332
    mClearDepth = d;
333
    }
334

    
335
///////////////////////////////////////////////////////////////////////////////////////////////////
336
/**
337
 * Create new Projection matrix.
338
 *
339
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
340
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
341
 * @param near Distance between the screen plane and the near plane.
342
 *             Valid vaules: 0<near<1. When near==0, the Near Plane is exactly at the tip of the
343
 *             pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
344
 */
345
  public void setProjection(float fov, float near)
346
    {
347
    if( fov < 180.0f && fov >=0.0f )
348
      {
349
      mFOV = fov;
350
      }
351

    
352
    if( near<   1.0f && near> 0.0f )
353
      {
354
      mNear= near;
355
      }
356
    else if( near<=0.0f )
357
      {
358
      mNear = 0.01f;
359
      }
360
    else if( near>=1.0f )
361
      {
362
      mNear=0.99f;
363
      }
364

    
365
    createProjection();
366
    }
367

    
368
///////////////////////////////////////////////////////////////////////////////////////////////////
369
/**
370
 * Resize the underlying Framebuffer.
371
 * <p>
372
 * This method can be safely called mid-render as it doesn't interfere with rendering.
373
 *
374
 * @param width The new width.
375
 * @param height The new height.
376
 */
377
  public void resize(int width, int height)
378
    {
379
    if( mWidth!=width || mHeight!=height )
380
      {
381
      mWidth = width;
382
      mHeight= height;
383

    
384
      createProjection();
385

    
386
      if( mColorCreated==CREATED )
387
        {
388
        markForCreation();
389
        recreate();
390
        }
391
      }
392
    }
393

    
394
///////////////////////////////////////////////////////////////////////////////////////////////////
395
/**
396
 * Create a new DEPTH buffer and attach it or (param=false) detach an existing DEPTH attachment and recreate it.
397
 *
398
 * @param enable <bold>true</bold> if we want to attach a new DEPTH buffer to the FBO.<br>
399
 *               <bold>false</bold> if we want to detach the DEPTH attachment.
400
 */
401
  public void enableDepth(boolean enable)
402
    {
403
    if( enable && mDepthCreated==DONT_CREATE )
404
      {
405
      mDepthCreated = NOT_CREATED_YET;
406
      markForCreation();
407
      }
408
    if( !enable && mDepthCreated!=DONT_CREATE )
409
      {
410
      mDepthCreated = DONT_CREATE;
411
      markForCreation();
412
      }
413
    }
414

    
415
///////////////////////////////////////////////////////////////////////////////////////////////////
416
/**
417
 * Return true if the Surface contains a DEPTH attachment.
418
 *
419
 * @return <bold>true</bold> if the FBO contains a DEPTH attachment.
420
 */
421
  public boolean hasDepth()
422
    {
423
    return mDepthCreated==CREATED;
424
    }
425

    
426
///////////////////////////////////////////////////////////////////////////////////////////////////
427
/**
428
 * Adds a new child to the last position in the list of our Surface's children.
429
 * <p>
430
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
431
 * DistortedMaster (by calling doWork())
432
 *
433
 * @param node The new Node to add.
434
 */
435
  public void attach(DistortedNode node)
436
    {
437
    mJobs.add(new Job(ATTACH,node,null));
438
    DistortedMaster.newSlave(this);
439
    }
440

    
441
///////////////////////////////////////////////////////////////////////////////////////////////////
442
/**
443
 * Adds a new child to the last position in the list of our Surface's children.
444
 * <p>
445
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
446
 * DistortedMaster (by calling doWork())
447
 *
448
 * @param surface InputSurface to initialize our child Node with.
449
 * @param effects DistortedEffects to initialize our child Node with.
450
 * @param mesh MeshObject to initialize our child Node with.
451
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
452
 */
453
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
454
    {
455
    DistortedNode node = new DistortedNode(surface,effects,mesh);
456
    mJobs.add(new Job(ATTACH,node,null));
457
    DistortedMaster.newSlave(this);
458
    return node;
459
    }
460

    
461
///////////////////////////////////////////////////////////////////////////////////////////////////
462
/**
463
 * Removes the first occurrence of a specified child from the list of children of our Surface.
464
 * <p>
465
 * A bit questionable method as there can be many different Nodes attached as children, some
466
 * of them having the same Effects but - for instance - different Mesh. Use with care.
467
 * <p>
468
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
469
 * DistortedMaster (by calling doWork())
470
 *
471
 * @param effects DistortedEffects to remove.
472
 */
473
  public void detach(DistortedEffects effects)
474
    {
475
    long id = effects.getID();
476
    DistortedNode node;
477
    boolean detached = false;
478

    
479
    for(int i=0; i<mNumChildren; i++)
480
      {
481
      node = mChildren.get(i);
482

    
483
      if( node.getEffects().getID()==id )
484
        {
485
        detached = true;
486
        mJobs.add(new Job(DETACH,node,null));
487
        DistortedMaster.newSlave(this);
488
        break;
489
        }
490
      }
491

    
492
    if( !detached )
493
      {
494
      // if we failed to detach any, it still might be the case that
495
      // there's an ATTACH job that we need to cancel.
496
      int num = mJobs.size();
497
      Job job;
498

    
499
      for(int i=0; i<num; i++)
500
        {
501
        job = mJobs.get(i);
502

    
503
        if( job.type==ATTACH && job.node.getEffects()==effects )
504
          {
505
          mJobs.remove(i);
506
          break;
507
          }
508
        }
509
      }
510
    }
511

    
512
///////////////////////////////////////////////////////////////////////////////////////////////////
513
/**
514
 * Removes the first occurrence of a specified child from the list of children of our Surface.
515
 * <p>
516
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
517
 * DistortedMaster (by calling doWork())
518
 *
519
 * @param node The Node to remove.
520
 */
521
  public void detach(DistortedNode node)
522
    {
523
    mJobs.add(new Job(DETACH,node,null));
524
    DistortedMaster.newSlave(this);
525
    }
526

    
527
///////////////////////////////////////////////////////////////////////////////////////////////////
528
/**
529
 * Removes all children Nodes.
530
 * <p>
531
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
532
 * DistortedMaster (by calling doWork())
533
 */
534
  public void detachAll()
535
    {
536
    mJobs.add(new Job(DETALL,null,null));
537
    DistortedMaster.newSlave(this);
538
    }
539

    
540
///////////////////////////////////////////////////////////////////////////////////////////////////
541
/**
542
 * This is not really part of the public API. Has to be public only because it is a part of the
543
 * DistortedSlave interface, which should really be a class that we extend here instead but
544
 * Java has no multiple inheritance.
545
 *
546
 * @y.exclude
547
 */
548
  public void doWork()
549
    {
550
    int num = mJobs.size();
551
    Job job;
552

    
553
    for(int i=0; i<num; i++)
554
      {
555
      job = mJobs.remove(0);
556

    
557
      switch(job.type)
558
        {
559
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
560
                     job.node.setSurfaceParent(this);
561
                     DistortedMaster.addSorted(mChildren,job.node);
562
                     mNumChildren++;
563
                     break;
564
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
565
                       {
566
                       job.node.setSurfaceParent(null);
567
                       mNumChildren--;
568
                       }
569
                     break;
570
        case DETALL: if( mNumChildren>0 )
571
                       {
572
                       DistortedNode tmp;
573

    
574
                       for(int j=mNumChildren-1; j>=0; j--)
575
                         {
576
                         tmp = mChildren.remove(j);
577
                         tmp.setSurfaceParent(null);
578
                         }
579

    
580
                       mNumChildren = 0;
581
                       }
582
                     break;
583
        case SORT  : job.node.setPost(job.dep);
584
                     mChildren.remove(job.node);
585
                     DistortedMaster.addSorted(mChildren,job.node);
586
                     break;
587
        }
588
      }
589
    }
590
}
(8-8/24)