Project

General

Profile

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

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

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2016 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// Distorted is free software: you can redistribute it and/or modify                             //
7
// it under the terms of the GNU General Public License as published by                          //
8
// the Free Software Foundation, either version 2 of the License, or                             //
9
// (at your option) any later version.                                                           //
10
//                                                                                               //
11
// Distorted is distributed in the hope that it will be useful,                                  //
12
// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
13
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
14
// GNU General Public License for more details.                                                  //
15
//                                                                                               //
16
// You should have received a copy of the GNU General Public License                             //
17
// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
18
///////////////////////////////////////////////////////////////////////////////////////////////////
19

    
20
package org.distorted.library.main;
21

    
22
import android.opengl.GLES31;
23
import android.opengl.Matrix;
24

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

    
27
import java.util.ArrayList;
28

    
29
///////////////////////////////////////////////////////////////////////////////////////////////////
30
/**
31
 * This is not really part of the public API.
32
 *
33
 * @y.exclude
34
 */
35
public abstract class DistortedOutputSurface extends DistortedSurface implements DistortedMaster.Slave
36
{
37
//////////// DEBUG FLAGS /////////////////////////////////////////////
38
/**
39
 * When rendering a Screen, show FPS in the upper-left corner?
40
 */
41
public static final int DEBUG_FPS = 1;
42
//////////// END DEBUG FLAGS /////////////////////////////////////////
43

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

    
57
  private static final int ATTACH = 0;
58
  private static final int DETACH = 1;
59
  private static final int DETALL = 2;
60
  private static final int SORT   = 3;
61

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

    
65
  private class Job
66
    {
67
    int type;
68
    DistortedNode node;
69

    
70
    Job(int t, DistortedNode n)
71
      {
72
      type = t;
73
      node = n;
74
      }
75
    }
76

    
77
  private ArrayList<Job> mJobs = new ArrayList<>();
78

    
79
  DistortedOutputSurface[] mBuffer;
80

    
81
  private long mTime;
82
  private float mFOV;
83
  float mDistance, mNear;
84
  float[] mProjectionMatrix;
85

    
86
  int mDepthStencilCreated;
87
  int mDepthStencil;
88
  int[] mDepthStencilH = new int[1];
89
  int[] mFBOH          = new int[1];
90

    
91
  private float mClearR, mClearG, mClearB, mClearA;
92
  private float mClearDepth;
93
  private int mClearStencil;
94
  private int mClear;
95
  float mMipmap;
96

    
97
  private int mDebugLevel;
98

    
99
///////////////////////////////////////////////////////////////////////////////////////////////////
100

    
101
  abstract void prepareDebug(long time);
102
  abstract void renderDebug(long time);
103

    
104
///////////////////////////////////////////////////////////////////////////////////////////////////
105

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

    
110
    mProjectionMatrix = new float[16];
111

    
112
    mFOV = 60.0f;
113
    mNear=  0.5f;
114

    
115
    mDepthStencilCreated= (depthStencil== NO_DEPTH_NO_STENCIL ? DONT_CREATE:NOT_CREATED_YET);
116
    mDepthStencil = depthStencil;
117

    
118
    mFBOH[0]         = fbo;
119
    mDepthStencilH[0]= 0;
120

    
121
    mTime = 0;
122
    mDebugLevel = 0;
123

    
124
    mClearR = 0.0f;
125
    mClearG = 0.0f;
126
    mClearB = 0.0f;
127
    mClearA = 0.0f;
128

    
129
    mClearDepth = 1.0f;
130
    mClearStencil = 0;
131
    mClear = GLES31.GL_DEPTH_BUFFER_BIT | GLES31.GL_COLOR_BUFFER_BIT;
132

    
133
    mBuffer = new DistortedOutputSurface[1+EffectQuality.LENGTH];
134

    
135
    mMipmap = 1.0f;
136

    
137
    createProjection();
138
    }
139

    
140
///////////////////////////////////////////////////////////////////////////////////////////////////
141

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

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

    
158
        mDistance    = mHeight/a;
159
        float far    = 2*mDistance-near;
160

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

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

    
178
///////////////////////////////////////////////////////////////////////////////////////////////////
179

    
180
  private void createBuffers()
181
    {
182
    float mipmap=1.0f;
183

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

    
193
    mBuffer[EffectQuality.LENGTH] = this;
194

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

    
197
    GLES31.glStencilMask(0xff);
198
    GLES31.glDepthMask(true);
199
    GLES31.glColorMask(true,true,true,true);
200
    GLES31.glClearColor(0.0f,0.0f,0.0f,0.0f);
201
    GLES31.glClearDepthf(1.0f);
202
    GLES31.glClearStencil(0);
203

    
204
    for(int j=0; j<EffectQuality.LENGTH; j++)
205
      {
206
      mBuffer[j].setAsOutput();
207
      GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[1], 0);
208
      GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
209
      GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, mBuffer[j].mColorH[0], 0);
210
      GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
211
      }
212
    }
213

    
214
///////////////////////////////////////////////////////////////////////////////////////////////////
215

    
216
  private int blitWithDepth(long currTime, DistortedOutputSurface buffer)
217
    {
218
    GLES31.glViewport(0, 0, mWidth, mHeight);
219
    setAsOutput(currTime);
220
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
221
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mColorH[0]);
222
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
223
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, buffer.mDepthStencilH[0]);
224

    
225
    GLES31.glDisable(GLES31.GL_STENCIL_TEST);
226
    GLES31.glStencilMask(0x00);
227

    
228
    DistortedEffects.blitDepthPriv(this);
229
    GLES31.glActiveTexture(GLES31.GL_TEXTURE0);
230
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
231
    GLES31.glActiveTexture(GLES31.GL_TEXTURE1);
232
    GLES31.glBindTexture(GLES31.GL_TEXTURE_2D, 0);
233

    
234
    // clear buffers
235
    GLES31.glStencilMask(0xff);
236
    GLES31.glDepthMask(true);
237
    GLES31.glColorMask(true,true,true,true);
238
    GLES31.glClearColor(0.0f,0.0f,0.0f,0.0f);
239
    GLES31.glClearDepthf(1.0f);
240
    GLES31.glClearStencil(0);
241

    
242
    buffer.setAsOutput();
243
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[1], 0);
244
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT|GLES31.GL_DEPTH_BUFFER_BIT|GLES31.GL_STENCIL_BUFFER_BIT);
245
    GLES31.glFramebufferTexture2D(GLES31.GL_FRAMEBUFFER, GLES31.GL_COLOR_ATTACHMENT0, GLES31.GL_TEXTURE_2D, buffer.mColorH[0], 0);
246
    GLES31.glClear(GLES31.GL_COLOR_BUFFER_BIT);
247

    
248
    return 1;
249
    }
250

    
251
///////////////////////////////////////////////////////////////////////////////////////////////////
252
// Render all children, one by one. If there are no postprocessing effects, just render to THIS.
253
// Otherwise, render to a buffer and on each change of Postprocessing Bucket, apply the postprocessing
254
// to a whole buffer and merge it.
255

    
256
  int renderChildren(long time, int numChildren, ArrayList<DistortedNode> children)
257
    {
258
    int quality=0, internalQuality = 0, numRenders = 0, bucketChange = 0;
259
    DistortedNode child1, child2;
260
    EffectQueuePostprocess lastQueue=null, currQueue;
261
    long lastBucket=0, currBucket;
262

    
263
    for(int i=0; i<numChildren; i++)
264
      {
265
      child1 = children.get(i);
266
      currQueue = child1.getPostprocessQueue();
267
      currBucket= currQueue.getID();
268

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

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

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

    
288
          internalQuality = currQueue.getInternalQuality();
289
          quality         = currQueue.getQuality();
290
          bucketChange    = i;
291
          }
292

    
293
        child1.draw(time,mBuffer[quality]);
294
        //numRenders += currQueue.draw(child1,time,mBuffer);
295

    
296
        if( i==numChildren-1 )
297
          {
298
          for(int j=bucketChange; j<numChildren; j++)
299
            {
300
            child2 = children.get(j);
301
            numRenders += child2.markStencilAndDepth(time,mBuffer[internalQuality],currQueue);
302
            }
303

    
304
          numRenders += currQueue.postprocess(this);
305
          numRenders += blitWithDepth(time, mBuffer[quality]);
306
          }
307
        }
308

    
309
      lastQueue = currQueue;
310
      lastBucket= currBucket;
311
      }
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
    setAsOutput(time);
395
    numRenders += renderChildren(time,mNumChildren,mChildren);
396

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

    
399
    return numRenders;
400
    }
401

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

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

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

    
434
  public void setAsOutput()
435
    {
436
    GLES31.glBindFramebuffer(GLES31.GL_FRAMEBUFFER, mFBOH[0]);
437
    }
438

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

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

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

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

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

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

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

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

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

    
566
    createProjection();
567
    }
568

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

    
585
      createProjection();
586

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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