Project

General

Profile

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

library / src / main / java / org / distorted / library / main / DistortedOutputSurface.java @ 3521c6fe

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.Matrix;
24

    
25
import org.distorted.library.effect.EffectQuality;
26

    
27
import java.util.ArrayList;
28

    
29
///////////////////////////////////////////////////////////////////////////////////////////////////
30

    
31
abstract class DistortedOutputSurface extends DistortedSurface implements DistortedSlave
32
{
33
//////////// DEBUG FLAGS /////////////////////////////////////////////
34
/**
35
 * When rendering a Screen, show FPS in the upper-left corner?
36
 */
37
public static final int DEBUG_FPS = 1;
38
//////////// END DEBUG FLAGS /////////////////////////////////////////
39

    
40
/**
41
 * Do not create DEPTH or STENCIL attachment
42
 */
43
  public static final int NO_DEPTH_NO_STENCIL = 0;
44
/**
45
 * Create DEPTH, but not STENCIL
46
 */
47
  public static final int DEPTH_NO_STENCIL    = 1;
48
/**
49
 * Create both DEPTH and STENCIL
50
 */
51
  public static final int BOTH_DEPTH_STENCIL  = 2;
52

    
53
  private static final int ATTACH = 0;
54
  private static final int DETACH = 1;
55
  private static final int DETALL = 2;
56
  private static final int SORT   = 3;
57

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

    
61
  private class Job
62
    {
63
    int type;
64
    DistortedNode node;
65

    
66
    Job(int t, DistortedNode n)
67
      {
68
      type = t;
69
      node = n;
70
      }
71
    }
72

    
73
  private ArrayList<Job> mJobs = new ArrayList<>();
74

    
75
  DistortedFramebuffer[] mBuffer;
76

    
77
  private long mTime;
78
  private float mFOV;
79
  float mDistance, mNear;
80
  float[] mProjectionMatrix;
81

    
82
  int mDepthStencilCreated;
83
  int mDepthStencil;
84
  int[] mDepthStencilH = new int[1];
85
  int[] mFBOH          = new int[1];
86

    
87
  private float mClearR, mClearG, mClearB, mClearA;
88
  private float mClearDepth;
89
  private int mClearStencil;
90
  private int mClear;
91
  float mMipmap;
92

    
93
  private int mDebugLevel;
94

    
95
private String sLast="", sCurr="";
96

    
97
///////////////////////////////////////////////////////////////////////////////////////////////////
98

    
99
  abstract void prepareDebug(long time);
100
  abstract void renderDebug(long time);
101

    
102
///////////////////////////////////////////////////////////////////////////////////////////////////
103

    
104
  DistortedOutputSurface(int width, int height, int createColor, int numcolors, int depthStencil, int fbo, int type)
105
    {
106
    super(width,height,createColor,numcolors,type);
107

    
108
    mProjectionMatrix = new float[16];
109

    
110
    mFOV = 60.0f;
111
    mNear=  0.5f;
112

    
113
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
114
    mDepthStencil = depthStencil;
115

    
116
    mFBOH[0]         = fbo;
117
    mDepthStencilH[0]= 0;
118

    
119
    mTime = 0;
120
    mDebugLevel = 0;
121

    
122
    mClearR = 0.0f;
123
    mClearG = 0.0f;
124
    mClearB = 0.0f;
125
    mClearA = 0.0f;
126

    
127
    mClearDepth = 1.0f;
128
    mClearStencil = 0;
129
    mClear = GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT;
130

    
131
    mBuffer = new DistortedFramebuffer[EffectQuality.LENGTH];
132

    
133
    mMipmap = 1.0f;
134

    
135
    createProjection();
136
    }
137

    
138
///////////////////////////////////////////////////////////////////////////////////////////////////
139

    
140
  private void createProjection()
141
    {
142
    if( mWidth>0 && mHeight>1 )
143
      {
144
      if( mFOV>0.0f )  // perspective projection
145
        {
146
        float a = 2.0f*(float)Math.tan(mFOV*Math.PI/360);
147
        float q = mWidth*mNear;
148
        float c = mHeight*mNear;
149

    
150
        float left   = -q/2;
151
        float right  = +q/2;
152
        float bottom = -c/2;
153
        float top    = +c/2;
154
        float near   =  c/a;
155

    
156
        mDistance    = mHeight/a;
157
        float far    = 2*mDistance-near;
158

    
159
        Matrix.frustumM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
160
        }
161
      else             // parallel projection
162
        {
163
        float left   = -mWidth/2.0f;
164
        float right  = +mWidth/2.0f;
165
        float bottom = -mHeight/2.0f;
166
        float top    = +mHeight/2.0f;
167
        float near   = mWidth+mHeight-mHeight*(1.0f-mNear);
168
        mDistance    = mWidth+mHeight;
169
        float far    = mWidth+mHeight+mHeight*(1.0f-mNear);
170

    
171
        Matrix.orthoM(mProjectionMatrix, 0, left, right, bottom, top, near, far);
172
        }
173
      }
174
    }
175

    
176
///////////////////////////////////////////////////////////////////////////////////////////////////
177

    
178
  private void createBuffers()
179
    {
180
    float mipmap=1.0f;
181

    
182
    for(int j=0; j<EffectQuality.LENGTH; j++)
183
      {
184
      mBuffer[j] = new DistortedFramebuffer(2,BOTH_DEPTH_STENCIL,TYPE_SYST, (int)(mWidth*mipmap), (int)(mHeight*mipmap) );
185
      mBuffer[j].mMipmap = mipmap;
186
      mBuffer[j].mNear   = mNear;  // copy mNear as well (for blitting- see PostprocessEffectBlur.apply() )
187
      mipmap *= EffectQuality.MULTIPLIER;
188
      }
189

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

    
192
    GLES30.glStencilMask(0xff);
193
    GLES30.glDepthMask(true);
194
    GLES30.glColorMask(true,true,true,true);
195
    GLES30.glClearColor(0.0f,0.0f,0.0f,0.0f);
196
    GLES30.glClearDepthf(1.0f);
197
    GLES30.glClearStencil(0);
198

    
199
    for(int j=0; j<EffectQuality.LENGTH; j++)
200
      {
201
      mBuffer[j].setAsOutput();
202
      GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mBuffer[j].mColorH[1], 0);
203
      GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT|GLES30.GL_DEPTH_BUFFER_BIT|GLES30.GL_STENCIL_BUFFER_BIT);
204
      GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, mBuffer[j].mColorH[0], 0);
205
      GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
206
      }
207
    }
208

    
209
///////////////////////////////////////////////////////////////////////////////////////////////////
210

    
211
  private int blitWithDepth(long currTime, DistortedFramebuffer buffer)
212
    {
213
    GLES30.glViewport(0, 0, mWidth, mHeight);
214
    setAsOutput(currTime);
215
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
216
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mColorH[0]);
217
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
218
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, buffer.mDepthStencilH[0]);
219

    
220
    GLES30.glDisable(GLES30.GL_STENCIL_TEST);
221
    GLES30.glStencilMask(0x00);
222

    
223
    DistortedEffects.blitDepthPriv(this);
224
    GLES30.glActiveTexture(GLES30.GL_TEXTURE0);
225
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
226
    GLES30.glActiveTexture(GLES30.GL_TEXTURE1);
227
    GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, 0);
228

    
229
    // clear buffers
230
    GLES30.glStencilMask(0xff);
231
    GLES30.glDepthMask(true);
232
    GLES30.glColorMask(true,true,true,true);
233
    GLES30.glClearColor(0.0f,0.0f,0.0f,0.0f);
234
    GLES30.glClearDepthf(1.0f);
235
    GLES30.glClearStencil(0);
236

    
237
    buffer.setAsOutput();
238
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, buffer.mColorH[1], 0);
239
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT|GLES30.GL_DEPTH_BUFFER_BIT|GLES30.GL_STENCIL_BUFFER_BIT);
240
    GLES30.glFramebufferTexture2D(GLES30.GL_FRAMEBUFFER, GLES30.GL_COLOR_ATTACHMENT0, GLES30.GL_TEXTURE_2D, buffer.mColorH[0], 0);
241
    GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
242

    
243
    return 1;
244
    }
245

    
246
///////////////////////////////////////////////////////////////////////////////////////////////////
247
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
248
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
249
// to a whole buffer and merge it.
250

    
251
  int renderChildren(long time, int numChildren, ArrayList<DistortedNode> children)
252
    {
253
    int quality=0, numRenders = 0, bucketChange = 0;
254
    DistortedNode child1, child2;
255
    DistortedEffects lastEffects=null, currEffects;
256
    long lastBucket=0, currBucket;
257

    
258
sCurr = "";
259

    
260
    for(int i=0; i<numChildren; i++)
261
      {
262
      child1 = children.get(i);
263
      currEffects = child1.getEffects();
264
      currBucket  = currEffects.getBucket();
265

    
266
sCurr += (" "+currBucket);
267

    
268
      if( currBucket==0 ) numRenders += child1.draw(time,this);
269
      else
270
        {
271
        if( mBuffer[0]==null ) createBuffers();
272

    
273
        if( lastBucket!=currBucket )
274
          {
275
          if( lastBucket!=0 )
276
            {
277
            for(int j=bucketChange; j<i; j++)
278
              {
279
              child2 = children.get(j);
280
              numRenders += child2.markStencilAndDepth(time,mBuffer[quality],lastEffects);
281
              }
282

    
283
            numRenders += lastEffects.postprocess(this);
284
            numRenders += blitWithDepth(time, mBuffer[quality]);
285
            }
286

    
287
          quality = currEffects.getQuality();
288
          bucketChange = i;
289
          }
290

    
291
        numRenders += child1.draw(time,mBuffer[quality]);
292

    
293
        if( i==numChildren-1 )
294
          {
295
          for(int j=bucketChange; j<numChildren; j++)
296
            {
297
            child2 = children.get(j);
298
            numRenders += child2.markStencilAndDepth(time,mBuffer[quality],currEffects);
299
            }
300

    
301
          numRenders += currEffects.postprocess(this);
302
          numRenders += blitWithDepth(time,mBuffer[quality]);
303
          }
304
        }
305

    
306
      lastEffects = currEffects;
307
      lastBucket  = currBucket;
308
      }
309

    
310
if( !sLast.equals(sCurr) ) android.util.Log.e("surface", "rendering: "+sCurr);
311
sLast = sCurr;
312

    
313
    return numRenders;
314
    }
315

    
316
///////////////////////////////////////////////////////////////////////////////////////////////////
317

    
318
  ArrayList<DistortedNode> getChildren()
319
    {
320
    return mChildren;
321
    }
322

    
323
///////////////////////////////////////////////////////////////////////////////////////////////////
324
// PUBLIC API
325
///////////////////////////////////////////////////////////////////////////////////////////////////
326
/**
327
 * Make the library show various debugging information.
328
 * <p>
329
 * Currently only DEBUG_FPS - show FPS in the upper-left corner of every Screen - is defined.
330
 *
331
 * @param bitmask 0, or a bitmask of DEBUG_** flags to enable (currently only DEBUG_FPS defined)
332
 */
333
  public void setDebug(int bitmask)
334
    {
335
    if( this instanceof DistortedScreen )
336
      mDebugLevel = bitmask;
337
    }
338

    
339
///////////////////////////////////////////////////////////////////////////////////////////////////
340

    
341
/**
342
 * Draws all the attached children to this OutputSurface.
343
 * <p>
344
 * Must be called from a thread holding OpenGL Context.
345
 *
346
 * @param time Current time, in milliseconds. This will be passed to all the Effects stored in the children Nodes.
347
 * @return Number of objects rendered.
348
 */
349
  public int render(long time)
350
    {
351
    if( mDebugLevel!=0 ) prepareDebug(time);
352

    
353
    // change tree topology (attach and detach children)
354
/*
355
    boolean changed1 =
356
*/
357
    DistortedMaster.toDo();
358
/*
359
    if( changed1 )
360
      {
361
      for(int i=0; i<mNumChildren; i++)
362
        {
363
        mChildren.get(i).debug(0);
364
        }
365

    
366
      DistortedNode.debugMap();
367
      }
368
*/
369
    // create and delete all underlying OpenGL resources
370
    // Watch out: FIRST change topology, only then deal
371
    // with OpenGL resources. That's because changing Tree
372
    // can result in additional Framebuffers that would need
373
    // to be created immediately, before the calls to drawRecursive()
374
/*
375
    boolean changed2 =
376
*/
377
    toDo();
378
/*
379
    if( changed2 )
380
      {
381
      DistortedObject.debugLists();
382
      }
383
*/
384
    // mark OpenGL state as unknown
385
    DistortedRenderState.reset();
386

    
387
    int numRenders=0;
388

    
389
    for(int i=0; i<mNumChildren; i++)
390
      {
391
      numRenders += mChildren.get(i).renderRecursive(time);
392
      }
393

    
394
    numRenders += renderChildren(time,mNumChildren,mChildren);
395

    
396
    if( mDebugLevel != 0 ) renderDebug(time);
397

    
398
    return numRenders;
399
    }
400

    
401
///////////////////////////////////////////////////////////////////////////////////////////////////
402
/**
403
 * Bind this Surface as a Framebuffer we can render to.
404
 *
405
 * @param time Present time, in milliseconds. The point: looking at this param the library can figure
406
 *             out if this is the first time during present frame that this FBO is being set as output.
407
 *             If so, the library, in addition to binding the Surface for output, also clears the
408
 *             Surface's color and depth attachments.
409
 */
410
  public void setAsOutput(long time)
411
    {
412
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
413

    
414
    if( mTime!=time )
415
      {
416
      mTime = time;
417
      DistortedRenderState.colorDepthStencilOn();
418
      GLES30.glClearColor(mClearR, mClearG, mClearB, mClearA);
419
      GLES30.glClearDepthf(mClearDepth);
420
      GLES30.glClearStencil(mClearStencil);
421
      GLES30.glClear(mClear);
422
      }
423
    }
424

    
425
///////////////////////////////////////////////////////////////////////////////////////////////////
426
/**
427
 * Bind this Surface as a Framebuffer we can render to.
428
 * <p>
429
 * This version does not attempt to clear anything.
430
 */
431

    
432
  public void setAsOutput()
433
    {
434
    GLES30.glBindFramebuffer(GLES30.GL_FRAMEBUFFER, mFBOH[0]);
435
    }
436

    
437
///////////////////////////////////////////////////////////////////////////////////////////////////
438
/**
439
 * Return the Near plane of the Projection included in the Surface.
440
 *
441
 * @return the Near plane.
442
 */
443
  public float getNear()
444
    {
445
    return mNear;
446
    }
447

    
448
///////////////////////////////////////////////////////////////////////////////////////////////////
449
/**
450
 * Set mipmap level.
451
 * <p>
452
 * Trick for speeding up your renders - one can create a pyramid of OutputSurface objects, each next
453
 * one some constant FACTOR smaller than the previous (0.5 is the common value), then set the Mipmap
454
 * Level of the i-th object to be FACTOR^i (we start counting from 0). When rendering any scene into
455
 * such prepared OutputSurface, the library will make sure to scale any Effects used so that the end
456
 * scene will end up looking identical no matter which object we render to. Identical, that is, except
457
 * for the loss of quality and gain in speed associated with rendering to a smaller Surface.
458
 * <p>
459
 * Example: if you create two FBOs, one 1000x1000 and another 500x500 in size, and set the second one
460
 * mipmap to 0.5 (the first one's is 1.0 by default), define Effects to be a single move by (100,100),
461
 * and render a skinned Mesh into both FBO, the end result will look proportionally the same, because
462
 * in the second case the move vector (100,100) will be auto-scaled to (50,50).
463
 *
464
 * @param mipmap The mipmap level. Acceptable range: 0&lt;mipmap&lt;infinity, although mipmap&gt;1
465
 *               does not make any sense (that would result in loss of speed and no gain in quality)
466
 */
467
  public void setMipmap(float mipmap)
468
    {
469
    mMipmap = mipmap;
470
    }
471

    
472
///////////////////////////////////////////////////////////////////////////////////////////////////
473
/**
474
 * Set the (R,G,B,A) values of GLES30.glClearColor() to set up color with which to clear
475
 * this Surface at the beginning of each frame.
476
 *
477
 * @param r the Red component. Default: 0.0f
478
 * @param g the Green component. Default: 0.0f
479
 * @param b the Blue component. Default: 0.0f
480
 * @param a the Alpha component. Default: 0.0f
481
 */
482
  public void glClearColor(float r, float g, float b, float a)
483
    {
484
    mClearR = r;
485
    mClearG = g;
486
    mClearB = b;
487
    mClearA = a;
488
    }
489

    
490
///////////////////////////////////////////////////////////////////////////////////////////////////
491
/**
492
 * Uses glClearDepthf() to set up a value with which to clear
493
 * the Depth buffer of our Surface at the beginning of each frame.
494
 *
495
 * @param d the Depth. Default: 1.0f
496
 */
497
  public void glClearDepthf(float d)
498
    {
499
    mClearDepth = d;
500
    }
501

    
502
///////////////////////////////////////////////////////////////////////////////////////////////////
503
/**
504
 * Uses glClearStencil() to set up a value with which to clear the
505
 * Stencil buffer of our Surface at the beginning of each frame.
506
 *
507
 * @param s the Stencil. Default: 0
508
 */
509
  public void glClearStencil(int s)
510
    {
511
    mClearStencil = s;
512
    }
513

    
514
///////////////////////////////////////////////////////////////////////////////////////////////////
515
/**
516
 * Which buffers to Clear at the beginning of each frame?
517
 * <p>
518
 * Valid values: 0, or bitwise OR of one or more values from the set GL_COLOR_BUFFER_BIT,
519
 *               GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
520
 * Default: GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT.
521
 *
522
 * @param mask bitwise OR of BUFFER_BITs to clear.
523
 */
524
  public void glClear(int mask)
525
    {
526
    mClear = mask;
527
    }
528

    
529
///////////////////////////////////////////////////////////////////////////////////////////////////
530
/**
531
 * Create new Projection matrix.
532
 *
533
 * @param fov Vertical 'field of view' of the Projection frustrum (in degrees).
534
 *            Valid values: 0<=fov<180. FOV==0 means 'parallel projection'.
535
 * @param near Distance between the screen plane and the near plane.
536
 *             Valid vaules: 0<near<1. When near==0, the Near Plane is exactly at the tip of the
537
 *             pyramid. When near==1 (illegal!) the near plane is equivalent to the screen plane.
538
 */
539
  public void setProjection(float fov, float near)
540
    {
541
    if( fov < 180.0f && fov >=0.0f )
542
      {
543
      mFOV = fov;
544
      }
545

    
546
    if( near<   1.0f && near> 0.0f )
547
      {
548
      mNear= near;
549
      }
550
    else if( near<=0.0f )
551
      {
552
      mNear = 0.01f;
553
      }
554
    else if( near>=1.0f )
555
      {
556
      mNear=0.99f;
557
      }
558

    
559
    if( mBuffer[0]!=null )
560
      {
561
      for(int j=0; j<EffectQuality.LENGTH; j++) mBuffer[j].mNear = mNear;
562
      }
563

    
564
    createProjection();
565
    }
566

    
567
///////////////////////////////////////////////////////////////////////////////////////////////////
568
/**
569
 * Resize the underlying Framebuffer.
570
 * <p>
571
 * This method can be safely called mid-render as it doesn't interfere with rendering.
572
 *
573
 * @param width The new width.
574
 * @param height The new height.
575
 */
576
  public void resize(int width, int height)
577
    {
578
    if( mWidth!=width || mHeight!=height )
579
      {
580
      mWidth = width;
581
      mHeight= height;
582

    
583
      createProjection();
584

    
585
      if( mColorCreated==CREATED )
586
        {
587
        markForCreation();
588
        recreate();
589
        }
590
      }
591
    }
592

    
593
///////////////////////////////////////////////////////////////////////////////////////////////////
594
/**
595
 * Return true if the Surface contains a DEPTH attachment.
596
 *
597
 * @return <bold>true</bold> if the Surface contains a DEPTH attachment.
598
 */
599
  public boolean hasDepth()
600
    {
601
    return mDepthStencilCreated==CREATED;
602
    }
603

    
604
///////////////////////////////////////////////////////////////////////////////////////////////////
605
/**
606
 * Return true if the Surface contains a STENCIL attachment.
607
 *
608
 * @return <bold>true</bold> if the Surface contains a STENCIL attachment.
609
 */
610
  public boolean hasStencil()
611
    {
612
    return (mDepthStencilCreated==CREATED && mDepthStencil==BOTH_DEPTH_STENCIL);
613
    }
614

    
615
///////////////////////////////////////////////////////////////////////////////////////////////////
616
/**
617
 * Adds a new child to the last position in the list of our Surface's children.
618
 * <p>
619
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
620
 * DistortedMaster (by calling doWork())
621
 *
622
 * @param node The new Node to add.
623
 */
624
  public void attach(DistortedNode node)
625
    {
626
    mJobs.add(new Job(ATTACH,node));
627
    DistortedMaster.newSlave(this);
628
    }
629

    
630
///////////////////////////////////////////////////////////////////////////////////////////////////
631
/**
632
 * Adds a new child to the last position in the list of our Surface's children.
633
 * <p>
634
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
635
 * DistortedMaster (by calling doWork())
636
 *
637
 * @param surface InputSurface to initialize our child Node with.
638
 * @param effects DistortedEffects to initialize our child Node with.
639
 * @param mesh MeshObject to initialize our child Node with.
640
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
641
 */
642
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
643
    {
644
    DistortedNode node = new DistortedNode(surface,effects,mesh);
645
    mJobs.add(new Job(ATTACH,node));
646
    DistortedMaster.newSlave(this);
647
    return node;
648
    }
649

    
650
///////////////////////////////////////////////////////////////////////////////////////////////////
651
/**
652
 * Removes the first occurrence of a specified child from the list of children of our Surface.
653
 * <p>
654
 * A bit questionable method as there can be many different Nodes attached as children, some
655
 * of them having the same Effects but - for instance - different Mesh. Use with care.
656
 * <p>
657
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
658
 * DistortedMaster (by calling doWork())
659
 *
660
 * @param effects DistortedEffects to remove.
661
 */
662
  public void detach(DistortedEffects effects)
663
    {
664
    long id = effects.getID();
665
    DistortedNode node;
666
    boolean detached = false;
667

    
668
    for(int i=0; i<mNumChildren; i++)
669
      {
670
      node = mChildren.get(i);
671

    
672
      if( node.getEffects().getID()==id )
673
        {
674
        detached = true;
675
        mJobs.add(new Job(DETACH,node));
676
        DistortedMaster.newSlave(this);
677
        break;
678
        }
679
      }
680

    
681
    if( !detached )
682
      {
683
      // if we failed to detach any, it still might be the case that
684
      // there's an ATTACH job that we need to cancel.
685
      int num = mJobs.size();
686
      Job job;
687

    
688
      for(int i=0; i<num; i++)
689
        {
690
        job = mJobs.get(i);
691

    
692
        if( job.type==ATTACH && job.node.getEffects()==effects )
693
          {
694
          mJobs.remove(i);
695
          break;
696
          }
697
        }
698
      }
699
    }
700

    
701
///////////////////////////////////////////////////////////////////////////////////////////////////
702
/**
703
 * Removes the first occurrence of a specified child from the list of children of our Surface.
704
 * <p>
705
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
706
 * DistortedMaster (by calling doWork())
707
 *
708
 * @param node The Node to remove.
709
 */
710
  public void detach(DistortedNode node)
711
    {
712
    mJobs.add(new Job(DETACH,node));
713
    DistortedMaster.newSlave(this);
714
    }
715

    
716
///////////////////////////////////////////////////////////////////////////////////////////////////
717
/**
718
 * Removes all children Nodes.
719
 * <p>
720
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
721
 * DistortedMaster (by calling doWork())
722
 */
723
  public void detachAll()
724
    {
725
    mJobs.add(new Job(DETALL,null));
726
    DistortedMaster.newSlave(this);
727
    }
728

    
729
///////////////////////////////////////////////////////////////////////////////////////////////////
730
/**
731
 * This is not really part of the public API. Has to be public only because it is a part of the
732
 * DistortedSlave interface, which should really be a class that we extend here instead but
733
 * Java has no multiple inheritance.
734
 *
735
 * @y.exclude
736
 */
737
  public void doWork()
738
    {
739
    int num = mJobs.size();
740
    Job job;
741

    
742
    for(int i=0; i<num; i++)
743
      {
744
      job = mJobs.remove(0);
745

    
746
      switch(job.type)
747
        {
748
        case ATTACH: if( mChildren==null ) mChildren = new ArrayList<>(2);
749
                     job.node.setSurfaceParent(this);
750
                     DistortedMaster.addSorted(mChildren,job.node);
751
                     mNumChildren++;
752
                     break;
753
        case DETACH: if( mNumChildren>0 && mChildren.remove(job.node) )
754
                       {
755
                       job.node.setSurfaceParent(null);
756
                       mNumChildren--;
757
                       }
758
                     break;
759
        case DETALL: if( mNumChildren>0 )
760
                       {
761
                       DistortedNode tmp;
762

    
763
                       for(int j=mNumChildren-1; j>=0; j--)
764
                         {
765
                         tmp = mChildren.remove(j);
766
                         tmp.setSurfaceParent(null);
767
                         }
768

    
769
                       mNumChildren = 0;
770
                       }
771
                     break;
772
        case SORT  : mChildren.remove(job.node);
773
                     DistortedMaster.addSorted(mChildren,job.node);
774
                     break;
775
        }
776
      }
777
    }
778
}
(8-8/22)