Project

General

Profile

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

library / src / main / java / org / distorted / library / DistortedNode.java @ c834348d

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 java.util.ArrayList;
23
import java.util.HashMap;
24

    
25
import android.opengl.GLES30;
26

    
27
///////////////////////////////////////////////////////////////////////////////////////////////////
28
/**
29
 * Class which represents a Node in a Tree of (InputSurface,Mesh,Effects) triplets.
30
 * <p>
31
 * Having organized such sets into a Tree, we can then render any Node to any OutputSurface.
32
 * That recursively renders the set held in the Node and all its children.
33
 * <p>
34
 * The class takes special care to only render identical sub-trees once. Each Node holds a reference
35
 * to sub-class 'NodeData'. Two identical sub-trees attached at different points of the main tree
36
 * will point to the same NodeData; only the first of this is rendered (mData.numRender!).
37
 */
38
public class DistortedNode implements DistortedAttacheable
39
  {
40
  private static HashMap<ArrayList<Long>,NodeData> mMapNodeID = new HashMap<>();
41
  private static long mNextNodeID =0;
42

    
43
  private DistortedNode mParent;
44
  private MeshObject mMesh;
45
  private DistortedEffects mEffects;
46
  private DistortedInputSurface mSurface;
47
  private DistortedRenderState mState;
48
  private NodeData mData;
49

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

    
53
  private class NodeData
54
    {
55
    long ID;
56
    int numPointingNodes;
57
    int numRender;
58
    ArrayList<Long> key;
59
    DistortedFramebuffer mFBO;
60

    
61
    NodeData(long id, ArrayList<Long> k)
62
      {
63
      ID              = id;
64
      key             = k;
65
      numPointingNodes= 1;
66
      numRender       =-1;
67
      mFBO            = null;
68
      }
69
    }
70
 
71
///////////////////////////////////////////////////////////////////////////////////////////////////
72

    
73
  static synchronized void onDestroy()
74
    {
75
    mNextNodeID = 0;
76
    mMapNodeID.clear();
77
    }
78

    
79
///////////////////////////////////////////////////////////////////////////////////////////////////
80

    
81
  private ArrayList<Long> generateIDList()
82
    {
83
    ArrayList<Long> ret = new ArrayList<>();
84
     
85
    ret.add( mSurface.getID() );
86

    
87
    if( mNumChildren[0]==0 )
88
      {
89
      ret.add(-mEffects.getID());
90
      }
91

    
92
    DistortedNode node;
93
   
94
    for(int i=0; i<mNumChildren[0]; i++)
95
      {
96
      node = mChildren.get(i);
97
      ret.add(node.mData.ID);
98
      }
99
   
100
    return ret;
101
    }
102

    
103
///////////////////////////////////////////////////////////////////////////////////////////////////
104
// Debug - print all the Node IDs
105

    
106
  @SuppressWarnings("unused")
107
  void debug(int depth)
108
    {
109
    String tmp="";
110
    int i;
111

    
112
    for(i=0; i<depth; i++) tmp +="   ";
113
    tmp += ("NodeID="+mData.ID+" nodes pointing: "+mData.numPointingNodes+" surfaceID="+
114
            mSurface.getID()+" FBO="+(mData.mFBO==null ? "null":mData.mFBO.getID()))+
115
            " parent sID="+(mParent==null ? "null": (mParent.mSurface.getID()));
116

    
117
    android.util.Log.e("NODE", tmp);
118

    
119
    for(i=0; i<mNumChildren[0]; i++)
120
      mChildren.get(i).debug(depth+1);
121
    }
122

    
123
///////////////////////////////////////////////////////////////////////////////////////////////////
124
// Debug - print contents of the HashMap
125

    
126
  @SuppressWarnings("unused")
127
  static void debugMap()
128
    {
129
    NodeData tmp;
130

    
131
    for(ArrayList<Long> key: mMapNodeID.keySet())
132
      {
133
      tmp = mMapNodeID.get(key);
134
      android.util.Log.e("NODE", "NodeID: "+tmp.ID+" <-- "+key);
135
      }
136
    }
137

    
138
///////////////////////////////////////////////////////////////////////////////////////////////////
139
// tree isomorphism algorithm
140

    
141
  private void adjustIsomorphism()
142
    {
143
    ArrayList<Long> newList = generateIDList();
144
    NodeData newData = mMapNodeID.get(newList);
145

    
146
    if( newData!=null )
147
      {
148
      newData.numPointingNodes++;
149
      }
150
    else
151
      {
152
      newData = new NodeData(++mNextNodeID,newList);
153
      mMapNodeID.put(newList,newData);
154
      }
155

    
156
    boolean deleteOldFBO = false;
157
    boolean createNewFBO = false;
158

    
159
    if( --mData.numPointingNodes==0 )
160
      {
161
      mMapNodeID.remove(mData.key);
162
      if( mData.mFBO!=null ) deleteOldFBO=true;
163
      }
164
    if( mNumChildren[0]>0 && newData.mFBO==null )
165
      {
166
      createNewFBO = true;
167
      }
168
    if( mNumChildren[0]==0 && newData.mFBO!=null )
169
      {
170
      newData.mFBO.markForDeletion();
171
      android.util.Log.d("NODE", "ERROR!! this NodeData cannot possibly contain a non-null FBO!! "+newData.mFBO.getID() );
172
      newData.mFBO = null;
173
      }
174

    
175
    if( deleteOldFBO && createNewFBO )
176
      {
177
      newData.mFBO = mData.mFBO;  // just copy over
178
      //android.util.Log.d("NODE", "copying over FBOs "+mData.mFBO.getID() );
179
      }
180
    else if( deleteOldFBO )
181
      {
182
      mData.mFBO.markForDeletion();
183
      //android.util.Log.d("NODE", "deleting old FBO "+mData.mFBO.getID() );
184
      mData.mFBO = null;
185
      }
186
    else if( createNewFBO )
187
      {
188
      newData.mFBO = new DistortedFramebuffer(true, DistortedSurface.TYPE_TREE, mSurface.getWidth(),mSurface.getHeight());
189
      //android.util.Log.d("NODE", "creating new FBO "+newData.mFBO.getID() );
190
      }
191

    
192
    mData = newData;
193

    
194
    if( mParent!=null ) mParent.adjustIsomorphism();
195
    }
196

    
197
///////////////////////////////////////////////////////////////////////////////////////////////////
198
// return the total number of render calls issued
199

    
200
  int drawRecursive(int renderNum, long currTime, DistortedOutputSurface surface)
201
    {
202
    int ret = 0;
203
    float halfX = mSurface.getWidth()/2.0f;
204
    float halfY = mSurface.getHeight()/2.0f;
205

    
206
    if( mNumChildren[0]>0 && mData.numRender!=renderNum )
207
      {
208
      mData.numRender = renderNum;
209
      mData.mFBO.setAsOutput();
210

    
211
      GLES30.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
212
      GLES30.glClear( GLES30.GL_DEPTH_BUFFER_BIT | GLES30.GL_COLOR_BUFFER_BIT);
213

    
214
      if( mSurface.setAsInput() )
215
        {
216
        ret++;
217
        DistortedEffects.drawNoEffectsPriv(halfX, halfY, mMesh, mData.mFBO);
218
        }
219

    
220
      for(int i=0; i<mNumChildren[0]; i++)
221
        {
222
        ret += mChildren.get(i).drawRecursive(renderNum, currTime, mData.mFBO);
223
        }
224
      }
225

    
226
    DistortedInputSurface input = mNumChildren[0]==0 ? mSurface : mData.mFBO;
227

    
228
    if( input.setAsInput() )
229
      {
230
      ret++;
231
      mState.apply();
232
      mEffects.drawPriv(halfX, halfY, mMesh, surface, currTime);
233
      }
234

    
235
    return ret;
236
    }
237

    
238
///////////////////////////////////////////////////////////////////////////////////////////////////
239
// PUBLIC API
240
///////////////////////////////////////////////////////////////////////////////////////////////////
241
/**
242
 * Constructs new Node.
243
 *     
244
 * @param surface InputSurface to put into the new Node.
245
 * @param effects DistortedEffects to put into the new Node.
246
 * @param mesh MeshObject to put into the new Node.
247
 */
248
  public DistortedNode(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
249
    {
250
    mSurface       = surface;
251
    mEffects       = effects;
252
    mMesh          = mesh;
253
    mState         = new DistortedRenderState();
254
    mChildren      = null;
255
    mNumChildren   = new int[1];
256
    mNumChildren[0]= 0;
257
    mParent        = null;
258

    
259
    ArrayList<Long> list = new ArrayList<>();
260
    list.add(mSurface.getID());
261
    list.add(-mEffects.getID());
262

    
263
    mData = mMapNodeID.get(list);
264
   
265
    if( mData!=null )
266
      {
267
      mData.numPointingNodes++;
268
      }
269
    else
270
      {
271
      mData = new NodeData(++mNextNodeID,list);
272
      mMapNodeID.put(list, mData);
273
      }
274
    }
275

    
276
///////////////////////////////////////////////////////////////////////////////////////////////////  
277
/**
278
 * Copy-constructs new Node from another Node.
279
 *     
280
 * @param node The DistortedNode to copy data from.
281
 * @param flags bit field composed of a subset of the following:
282
 *        {@link Distorted#CLONE_SURFACE},  {@link Distorted#CLONE_MATRIX}, {@link Distorted#CLONE_VERTEX},
283
 *        {@link Distorted#CLONE_FRAGMENT} and {@link Distorted#CLONE_CHILDREN}.
284
 *        For example flags = CLONE_SURFACE | CLONE_CHILDREN.
285
 */
286
  public DistortedNode(DistortedNode node, int flags)
287
    {
288
    mEffects= new DistortedEffects(node.mEffects,flags);
289
    mMesh   = node.mMesh;
290
    mState  = new DistortedRenderState();
291
    mParent = null;
292

    
293
    if( (flags & Distorted.CLONE_SURFACE) != 0 )
294
      {
295
      mSurface = node.mSurface;
296
      }
297
    else
298
      {
299
      int w = node.mSurface.getWidth();
300
      int h = node.mSurface.getHeight();
301

    
302
      if( node.mSurface instanceof DistortedTexture )
303
        {
304
        mSurface = new DistortedTexture(w,h, DistortedSurface.TYPE_TREE);
305
        }
306
      else if( node.mSurface instanceof DistortedFramebuffer )
307
        {
308
        boolean hasDepth = ((DistortedFramebuffer) node.mSurface).hasDepth();
309
        mSurface = new DistortedFramebuffer(hasDepth,DistortedSurface.TYPE_TREE,w,h);
310
        }
311
      }
312
    if( (flags & Distorted.CLONE_CHILDREN) != 0 )
313
      {
314
      if( node.mChildren==null )     // do NOT copy over the NULL!
315
        {
316
        node.mChildren = new ArrayList<>(2);
317
        }
318

    
319
      mChildren = node.mChildren;
320
      mNumChildren = node.mNumChildren;
321
      }
322
    else
323
      {
324
      mChildren = null;
325
      mNumChildren = new int[1];
326
      mNumChildren[0] = 0;
327
      }
328
   
329
    ArrayList<Long> list = generateIDList();
330
   
331
    mData = mMapNodeID.get(list);
332
   
333
    if( mData!=null )
334
      {
335
      mData.numPointingNodes++;
336
      }
337
    else
338
      {
339
      mData = new NodeData(++mNextNodeID,list);
340
      mMapNodeID.put(list, mData);
341
      }
342
    }
343

    
344
///////////////////////////////////////////////////////////////////////////////////////////////////
345
/**
346
 * Adds a new child to the last position in the list of our Node's children.
347
 * <p>
348
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
349
 * DistortedAttachDeamon (by calling attachNow())
350
 *
351
 * @param node The new Node to add.
352
 */
353
  public void attach(DistortedNode node)
354
    {
355
    DistortedAttachDaemon.attach(this,node);
356
    }
357

    
358
///////////////////////////////////////////////////////////////////////////////////////////////////
359
/**
360
 * Adds a new child to the last position in the list of our Node's children.
361
 * <p>
362
 * We cannot do this mid-render - actual attachment will be done just before the next render, by the
363
 * DistortedAttachDeamon (by calling attachNow())
364
 *
365
 * @param surface InputSurface to initialize our child Node with.
366
 * @param effects DistortedEffects to initialize our child Node with.
367
 * @param mesh MeshObject to initialize our child Node with.
368
 * @return the newly constructed child Node, or null if we couldn't allocate resources.
369
 */
370
  public DistortedNode attach(DistortedInputSurface surface, DistortedEffects effects, MeshObject mesh)
371
    {
372
    DistortedNode node = new DistortedNode(surface,effects,mesh);
373
    DistortedAttachDaemon.attach(this,node);
374
    return node;
375
    }
376

    
377
///////////////////////////////////////////////////////////////////////////////////////////////////
378
/**
379
 * This is not really part of the public API. Has to be public only because it is a part of the
380
 * DistortedAttacheable interface, which should really be a class that we extend here instead but
381
 * Java has no multiple inheritance.
382
 *
383
 * @y.exclude
384
 * @param node The new Node to add.
385
 */
386
  public void attachNow(DistortedNode node)
387
    {
388
    if( mChildren==null ) mChildren = new ArrayList<>(2);
389

    
390
    node.mParent = this;
391
    mChildren.add(node);
392
    mNumChildren[0]++;
393
    adjustIsomorphism();
394
    }
395

    
396
///////////////////////////////////////////////////////////////////////////////////////////////////
397
/**
398
 * Removes the first occurrence of a specified child from the list of children of our Node.
399
 * <p>
400
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
401
 * DistortedAttachDeamon (by calling detachNow())
402
 *
403
 * @param node The Node to remove.
404
 */
405
  public void detach(DistortedNode node)
406
    {
407
    DistortedAttachDaemon.detach(this,node);
408
    }
409

    
410
///////////////////////////////////////////////////////////////////////////////////////////////////
411
/**
412
 * Removes the first occurrence of a specified child from the list of children of our Node.
413
 * <p>
414
 * A bit questionable method as there can be many different Nodes attached as children, some
415
 * of them having the same Effects but - for instance - different Mesh. Use with care.
416
 * <p>
417
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
418
 * DistortedAttachDeamon (by calling detachNow())
419
 *
420
 * @param effects DistortedEffects to remove.
421
 */
422
  public void detach(DistortedEffects effects)
423
    {
424
    long id = effects.getID();
425
    DistortedNode node;
426

    
427
    for(int i=0; i<mNumChildren[0]; i++)
428
      {
429
      node = mChildren.get(i);
430

    
431
      if( node.mEffects.getID()==id )
432
        {
433
        DistortedAttachDaemon.detach(this,node);
434
        break;
435
        }
436
      }
437
    }
438

    
439
///////////////////////////////////////////////////////////////////////////////////////////////////
440
/**
441
 * This is not really part of the public API. Has to be public only because it is a part of the
442
 * DistortedAttacheable interface, which should really be a class that we extend here instead but
443
 * Java has no multiple inheritance.
444
 *
445
 * @y.exclude
446
 * @param node The Node to remove.
447
 */
448
  public void detachNow(DistortedNode node)
449
    {
450
    if( mNumChildren[0]>0 && mChildren.remove(node) )
451
      {
452
      node.mParent = null;
453
      mNumChildren[0]--;
454
      adjustIsomorphism();
455
      }
456
    }
457

    
458
///////////////////////////////////////////////////////////////////////////////////////////////////
459
/**
460
 * Removes all children Nodes.
461
 * <p>
462
 * We cannot do this mid-render - actual detachment will be done just before the next render, by the
463
 * DistortedAttachDeamon (by calling detachAllNow())
464
 */
465
  public void detachAll()
466
    {
467
    DistortedAttachDaemon.detachAll(this);
468
    }
469

    
470
///////////////////////////////////////////////////////////////////////////////////////////////////
471
/**
472
 * This is not really part of the public API. Has to be public only because it is a part of the
473
 * DistortedAttacheable interface, which should really be a class that we extend here instead but
474
 * Java has no multiple inheritance.
475
 *
476
 * @y.exclude
477
 */
478
  public void detachAllNow()
479
    {
480
    if( mNumChildren[0]>0 )
481
      {
482
      DistortedNode tmp;
483

    
484
      for(int i=mNumChildren[0]-1; i>=0; i--)
485
        {
486
        tmp = mChildren.remove(i);
487
        tmp.mParent = null;
488
        }
489

    
490
      mNumChildren[0] = 0;
491
      adjustIsomorphism();
492
      }
493
    }
494

    
495
///////////////////////////////////////////////////////////////////////////////////////////////////
496
/**
497
 * Returns the DistortedEffects object that's in the Node.
498
 * 
499
 * @return The DistortedEffects contained in the Node.
500
 */
501
  public DistortedEffects getEffects()
502
    {
503
    return mEffects;
504
    }
505

    
506
///////////////////////////////////////////////////////////////////////////////////////////////////
507
/**
508
 * Returns the DistortedInputSurface object that's in the Node.
509
 *
510
 * @return The DistortedInputSurface contained in the Node.
511
 */
512
  public DistortedInputSurface getSurface()
513
    {
514
    return mSurface;
515
    }
516

    
517
///////////////////////////////////////////////////////////////////////////////////////////////////
518
/**
519
 * Returns the DistortedFramebuffer object that's in the Node.
520
 *
521
 * @return The DistortedFramebuffer contained in the Node.
522
 */
523
  public DistortedFramebuffer getFramebuffer()
524
    {
525
    return mData.mFBO;
526
    }
527

    
528

    
529
///////////////////////////////////////////////////////////////////////////////////////////////////
530
/**
531
 * When rendering this Node, use ColorMask (r,g,b,a).
532
 *
533
 * @param r Write to the RED color channel when rendering this Node?
534
 * @param g Write to the GREEN color channel when rendering this Node?
535
 * @param b Write to the BLUE color channel when rendering this Node?
536
 * @param a Write to the ALPHA channel when rendering this Node?
537
 */
538
  public void glColorMask(boolean r, boolean g, boolean b, boolean a)
539
    {
540
    mState.glColorMask(r,g,b,a);
541
    }
542

    
543
///////////////////////////////////////////////////////////////////////////////////////////////////
544
/**
545
 * When rendering this Node, switch on writing to Depth buffer?
546
 *
547
 * @param mask Write to the Depth buffer when rendering this Node?
548
 */
549
  public void glDepthMask(boolean mask)
550
    {
551
    mState.glDepthMask(mask);
552
    }
553

    
554
///////////////////////////////////////////////////////////////////////////////////////////////////
555
/**
556
 * When rendering this Node, which bits of the Stencil buffer to write to?
557
 *
558
 * @param mask Marks the bits of the Stencil buffer we will write to when rendering this Node.
559
 */
560
  public void glStencilMask(int mask)
561
    {
562
    mState.glStencilMask(mask);
563
    }
564

    
565
///////////////////////////////////////////////////////////////////////////////////////////////////
566
/**
567
 * When rendering this Node, which Tests to enable?
568
 *
569
 * @param test Valid values: GL_DEPTH_TEST, GL_STENCIL_TEST, GL_BLEND
570
 */
571
  public void glEnable(int test)
572
    {
573
    mState.glEnable(test);
574
    }
575

    
576
///////////////////////////////////////////////////////////////////////////////////////////////////
577
/**
578
 * When rendering this Node, which Tests to enable?
579
 *
580
 * @param test Valid values: GL_DEPTH_TEST, GL_STENCIL_TEST, GL_BLEND
581
 */
582
  public void glDisable(int test)
583
    {
584
    mState.glDisable(test);
585
    }
586

    
587
///////////////////////////////////////////////////////////////////////////////////////////////////
588
/**
589
 * When rendering this Node, use the following StencilFunc.
590
 *
591
 * @param func Valid values: GL_NEVER, GL_ALWAYS, GL_LESS, GL_LEQUAL, GL_EQUAL, GL_GEQUAL, GL_GREATER, GL_NOTEQUAL
592
 * @param ref  Reference valut to compare our stencil with.
593
 * @param mask Mask used when comparing.
594
 */
595
  public void glStencilFunc(int func, int ref, int mask)
596
    {
597
    mState.glStencilFunc(func,ref,mask);
598
    }
599

    
600
///////////////////////////////////////////////////////////////////////////////////////////////////
601
/**
602
 * When rendering this Node, use the following StencilOp.
603
 * <p>
604
 * Valid values of all 3 parameters: GL_KEEP, GL_ZERO, GL_REPLACE, GL_INCR, GL_DECR, GL_INVERT, GL_INCR_WRAP, GL_DECR_WRAP
605
 *
606
 * @param sfail  What to do when Stencil Test fails.
607
 * @param dpfail What to do when Depth Test fails.
608
 * @param dppass What to do when Depth Test passes.
609
 */
610
  public void glStencilOp(int sfail, int dpfail, int dppass)
611
    {
612
    mState.glStencilOp(sfail,dpfail,dppass);
613
    }
614

    
615
///////////////////////////////////////////////////////////////////////////////////////////////////
616
/**
617
 * When rendering this Node, use the following DepthFunc.
618
 *
619
 * @param func Valid values: GL_NEVER, GL_ALWAYS, GL_LESS, GL_LEQUAL, GL_EQUAL, GL_GEQUAL, GL_GREATER, GL_NOTEQUAL
620
 */
621
  public void glDepthFunc(int func)
622
    {
623
    mState.glDepthFunc(func);
624
    }
625

    
626
///////////////////////////////////////////////////////////////////////////////////////////////////
627
/**
628
 * When rendering this Node, use the following Blending mode.
629
 * <p>
630
 * Valid values: GL_ZERO, GL_ONE, GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA,
631
 *               GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR,
632
 *               GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_SRC_ALPHA_SATURATE
633
 *
634
 * @param src Source Blend function
635
 * @param dst Destination Blend function
636
 */
637
  public void glBlendFunc(int src, int dst)
638
    {
639
    mState.glBlendFunc(src,dst);
640
    }
641
  }
(7-7/23)