public
Fork of rikrd/geomerative
Description: Geomerative is a library for Processing. It extends 2D geometry operations to facilitate generative geometry. Includes a TrueType font and an SVG interpreters. This library exposes the shapes (such as vector drawings or typographies) in a more approchable way. Geomerative makes it easy to access the contours, the control points and the curve points, making it easy to develop generative typography and geometry pieces in Processing.
Homepage: http://www.ricardmarxer.com/geomerative
Clone URL: git://github.com/markluffel/geomerative.git
geomerative / src / geomerative / RShape.java
100644 1119 lines (967 sloc) 35.527 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
/**
Copyright 2004-2008 Ricard Marxer <email@ricardmarxer.com>
 
This file is part of Geomerative.
 
Geomerative is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
 
Geomerative is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Geomerative. If not, see <http://www.gnu.org/licenses/>.
*/
 
package geomerative ;
import processing.core.*;
 
/**
* RShape is a reduced interface for creating, holding and drawing complex Shapes. Shapes are groups of one or more subshapes (RSubshape). Shapes can be selfintersecting and can contain holes. This interface also allows you to transform shapes into polygons by segmenting the curves forming the shape.
* @eexample RShape
* @usage Geometry
* @related RSubshape
*/
public class RShape extends RGeomElem
{
  /**
* @invisible
*/
  public int type = RGeomElem.SHAPE;
  
  /**
* Array of RSubshape objects holding the subshapes of the polygon.
* @eexample subshapes
* @related RSubshape
* @related countSubshapes ( )
* @related addSubshape ( )
*/
  public RSubshape[] subshapes;
  protected int currentSubshape = 0;
  
  // ----------------------
  // --- Public Methods ---
  // ----------------------
  
  /**
* Use this method to create a new empty shape.
* @eexample RShape
*/
  public RShape(){
    this.subshapes= null;
    type = RGeomElem.SHAPE;
  }
  
  public RShape(RSubshape newsubshape){
    this.append(newsubshape);
    type = RGeomElem.SHAPE;
  }
  
  public RShape(RShape s){
    for(int i=0;i<s.countSubshapes();i++){
      this.append(new RSubshape(s.subshapes[i]));
    }
    type = RGeomElem.SHAPE;
 
    setStyle(s);
  }
 
  /**
* Use this method to create a new ring polygon.
* @eexample createRing
* @param radiusBig float, the outter radius of the ring polygon
* @param radiusSmall float, the inner radius of the ring polygon
* @param detail int, the number of vertices on each contour of the ring
* @return RShape, the ring polygon newly created
*/
  static public RShape createRing(float x, float y, float radiusBig, float radiusSmall){
    RShape ring = new RShape();
    RShape outer = RShape.createCircle(x, y, radiusBig);
    RShape inner = RShape.createCircle(x, y, -radiusSmall);
    
    ring.addSubshape(outer.subshapes[0]);
    ring.addSubshape(inner.subshapes[0]);
 
    return ring;
  }
 
  /**
* Use this method to create a new starform polygon.
* @eexample createStar
* @param radiusBig float, the outter radius of the star polygon
* @param radiusSmall float, the inner radius of the star polygon
* @param spikes int, the amount of spikes on the star polygon
* @return RShape, the starform polygon newly created
*/
  static public RShape createStar(float x, float y, float radiusBig, float radiusSmall, int spikes){
    RShape star = new RShape();
 
    star.addMoveTo( x - radiusBig, y );
    star.addLineTo( x - (float)(radiusSmall*Math.cos(Math.PI/spikes)), y - (float)(radiusSmall*Math.sin(Math.PI/spikes)));
 
    for(int i=2;i<2*spikes;i+=2){
      star.addLineTo( x - (float)(radiusBig*Math.cos(Math.PI*i/spikes)), y - (float)(radiusBig*Math.sin(Math.PI*i/spikes)));
      star.addLineTo( x - (float)(radiusSmall*Math.cos(Math.PI*(i+1)/spikes)), y - (float)(radiusSmall*Math.sin(Math.PI*(i+1)/spikes)));
    }
 
    star.addClose();
 
    return star;
  }
  
  /**
* Use this method to create a new circle shape.
* @eexample createRectangle
* @param x float, the x position of the rectangle
* @param y float, the y position of the rectangle
* @param w float, the width of the rectangle
* @param h float, the height of the rectangle
* @return RShape, the rectangular shape just created
*/
  static public RShape createRectangle(float x, float y, float w, float h){
    RShape rect = new RShape();
    rect.addMoveTo(x, y);
    rect.addLineTo(x+w, y);
    rect.addLineTo(x+w, y+h);
    rect.addLineTo(x, y+h);
    rect.addLineTo(x, y);
    return rect;
  }
  
  /**
* Use this method to create a new elliptical shape.
* @eexample createEllipse
* @param x float, the x position of the ellipse
* @param y float, the y position of the ellipse
* @param rx float, the horizontal radius of the ellipse
* @param ry float, the vertical radius of the ellipse
* @return RShape, the elliptical shape just created
*/
  static public RShape createEllipse(float x, float y, float rx, float ry){
    RPoint center = new RPoint(x,y);
    RShape circle = new RShape();
    float kx = (((8F/(float)Math.sqrt(2F))-4F)/3F) * rx;
    float ky = (((8F/(float)Math.sqrt(2F))-4F)/3F) * ry;
    circle.addMoveTo(center.x, center.y - ry);
    circle.addBezierTo(center.x+kx, center.y-ry, center.x+rx, center.y-ky, center.x+rx, center.y);
    circle.addBezierTo(center.x+rx, center.y+ky, center.x+kx, center.y+ry, center.x, center.y+ry);
    circle.addBezierTo(center.x-kx, center.y+ry, center.x-rx, center.y+ky, center.x-rx, center.y);
    circle.addBezierTo(center.x-rx, center.y-ky, center.x-kx, center.y-ry, center.x, center.y-ry);
    circle.addClose();
    return circle;
  }
 
  static public RShape createCircle(float x, float y, float r){
    return createEllipse(x, y, r, r);
  }
  
  /**
* Use this method to get the centroid of the element.
* @eexample RGroup_getCentroid
* @return RPoint, the centroid point of the element
* @related getBounds ( )
* @related getCenter ( )
*/
  public RPoint getCentroid(){
    RPoint bestCentroid = new RPoint();
    float bestArea = Float.NEGATIVE_INFINITY;
    if(subshapes != null){
      for(int i=0;i<subshapes.length;i++)
        {
          float area = Math.abs(subshapes[i].getArea());
          if(area > bestArea){
            bestArea = area;
            bestCentroid = subshapes[i].getCentroid();
          }
        }
      return bestCentroid;
    }
    return null;
  }
  
  /**
* Use this method to count the number of subshapes in the polygon.
* @eexample countSubshapes
* @return int, the number countours in the polygon.
* @related addSubshape ( )
*/
  public int countSubshapes(){
    if(this.subshapes==null){
      return 0;
    }
    
    return this.subshapes.length;
  }
  
  /**
* Use this method to add a new shape. The subshapes of the shape we are adding will simply be added to the current shape.
* @eexample addShape
* @param s RShape, the shape to be added.
* @related setSubshape ( )
* @related addMoveTo ( )
* @invisible
*/
  public void addShape(RShape s){
    for(int i=0;i<s.countSubshapes();i++){
      this.append(s.subshapes[i]);
    }
  }
  
  /**
* Use this method to create a new subshape. The first point of the new subshape will be set to (0,0). Use addMoveTo ( ) in order to add a new subshape with a different first point.
* @eexample addSubshape
* @param s RSubshape, the subshape to be added.
* @related setSubshape ( )
* @related addMoveTo ( )
*/
  public void addSubshape(){
    this.append(new RSubshape());
  }
  
  public void addSubshape(RSubshape s){
    this.append(s);
  }
  
  /**
* Use this method to set the current subshape.
* @eexample setSubshape
* @related addMoveTo ( )
* @related addLineTo ( )
* @related addQuadTo ( )
* @related addBezierTo ( )
* @related addSubshape ( )
*/
  public void setSubshape(int indSubshape){
    this.currentSubshape = indSubshape;
  }
  
  /**
* Use this method to add a new moveTo command to the shape. The command moveTo acts different to normal commands, in order to make a better analogy to its borthers classes Polygon and Mesh. MoveTo creates a new subshape in the shape. It's similar to adding a new contour to a polygon.
* @eexample addMoveTo
* @param endx float, the x coordinate of the first point for the new subshape.
* @param endy float, the y coordinate of the first point for the new subshape.
* @related addLineTo ( )
* @related addQuadTo ( )
* @related addBezierTo ( )
* @related addSubshape ( )
* @related setSubshape ( )
*/
  public void addMoveTo(float endx, float endy){
    if (subshapes == null){
      this.append(new RSubshape(endx,endy));
    }else if(subshapes[currentSubshape].countCommands() == 0){
      this.subshapes[currentSubshape].lastPoint = new RPoint(endx,endy);
    }else{
      this.append(new RSubshape(endx,endy));
    }
  }
 
  public void addMoveTo(RPoint p){
    addMoveTo(p.x, p.y);
  }
  
  /**
* Use this method to add a new lineTo command to the current subshape. This will add a line from the last point added to the point passed as argument.
* @eexample addLineTo
* @param endx float, the x coordinate of the ending point of the line.
* @param endy float, the y coordinate of the ending point of the line.
* @related addMoveTo ( )
* @related addQuadTo ( )
* @related addBezierTo ( )
* @related addSubshape ( )
* @related setSubshape ( )
*/
  public void addLineTo(float endx, float endy){
    if (subshapes == null) {
      this.append(new RSubshape());
    }
    this.subshapes[currentSubshape].addLineTo(endx, endy);
  }
 
  public void addLineTo(RPoint p){
    addLineTo(p.x, p.y);
  }
  
  /**
* Use this method to add a new quadTo command to the current subshape. This will add a quadratic bezier from the last point added with the control and ending points passed as arguments.
* @eexample addQuadTo
* @param cp1x float, the x coordinate of the control point of the bezier.
* @param cp1y float, the y coordinate of the control point of the bezier.
* @param endx float, the x coordinate of the ending point of the bezier.
* @param endy float, the y coordinate of the ending point of the bezier.
* @related addMoveTo ( )
* @related addLineTo ( )
* @related addBezierTo ( )
* @related addSubshape ( )
* @related setSubshape ( )
*/
  public void addQuadTo(float cp1x, float cp1y, float endx, float endy){
    if (subshapes == null) {
      this.append(new RSubshape());
    }
    this.subshapes[currentSubshape].addQuadTo(cp1x,cp1y,endx,endy);
  }
 
  public void addQuadTo(RPoint p1, RPoint p2){
    addQuadTo(p1.x, p1.y, p2.x, p2.y);
  }
  
  /**
* Use this method to add a new bezierTo command to the current subshape. This will add a cubic bezier from the last point added with the control and ending points passed as arguments.
* @eexample addArcTo
* @param cp1x float, the x coordinate of the first control point of the bezier.
* @param cp1y float, the y coordinate of the first control point of the bezier.
* @param cp2x float, the x coordinate of the second control point of the bezier.
* @param cp2y float, the y coordinate of the second control point of the bezier.
* @param endx float, the x coordinate of the ending point of the bezier.
* @param endy float, the y coordinate of the ending point of the bezier.
* @related addMoveTo ( )
* @related addLineTo ( )
* @related addQuadTo ( )
* @related addSubshape ( )
* @related setSubshape ( )
*/
  public void addBezierTo(float cp1x, float cp1y, float cp2x, float cp2y, float endx, float endy){
    if (subshapes == null) {
      this.append(new RSubshape());
    }
    this.subshapes[currentSubshape].addBezierTo(cp1x,cp1y,cp2x,cp2y,endx,endy);
  }
 
  public void addBezierTo(RPoint p1, RPoint p2, RPoint p3){
    addBezierTo(p1.x, p1.y, p2.x, p2.y, p3.x, p3.y);
  }
  
  public void addClose(){
    if (subshapes == null) {
      this.append(new RSubshape());
    }
    this.subshapes[currentSubshape].addClose();
  }
  
  /**
* Use this method to create a new mesh from a given polygon.
* @eexample toMesh
* @return RMesh, the mesh made of tristrips resulting of a tesselation of the polygonization followd by tesselation of the shape.
* @related draw ( )
*/
  public RMesh toMesh(){
    return toPolygon().toMesh();
  }
  
  /**
* Use this method to create a new polygon from a given shape.
* @eexample toPolygon
* @return RPolygon, the polygon resulting of the segmentation of the commands in each subshape.
* @related draw ( )
*/
  public RPolygon toPolygon(){
    int numSubshapes = countSubshapes();
    
    RPolygon result = new RPolygon();
    for(int i=0;i<numSubshapes;i++){
      RPoint[] newpoints = this.subshapes[i].getPoints();
      RContour c = new RContour(newpoints);
      c.closed = subshapes[i].closed;
      c.setStyle(subshapes[i]);
      result.addContour(c);
    }
    
    result.setStyle(this);
    return result;
  }
  
  /**
* @invisible
*/
  public RShape toShape(){
    return this;
  }
 
  /**
* Use this method to get the intersection of the given polygon with the polygon passed as atribute.
* @eexample intersection
* @param p RShape, the polygon with which to perform the intersection
* @return RShape, the intersection of the two polygons
* @related union ( )
* @related xor ( )
* @related diff ( )
*/
  public RShape intersection( RShape p ){
    return RClip.intersection( p.toPolygon(), this.toPolygon() ).toShape();
  }
  
  /**
* Use this method to get the union of the given polygon with the polygon passed as atribute.
* @eexample union
* @param p RShape, the polygon with which to perform the union
* @return RShape, the union of the two polygons
* @related intersection ( )
* @related xor ( )
* @related diff ( )
*/
  public RShape union( RShape p ){
    return RClip.union( p.toPolygon(), this.toPolygon() ).toShape();
  }
  
  /**
* Use this method to get the xor of the given polygon with the polygon passed as atribute.
* @eexample xor
* @param p RShape, the polygon with which to perform the xor
* @return RShape, the xor of the two polygons
* @related union ( )
* @related intersection ( )
* @related diff ( )
*/
  public RShape xor( RShape p ){
    return RClip.xor( p.toPolygon(), this.toPolygon() ).toShape();
  }
  
  /**
* Use this method to get the difference of the given polygon with the polygon passed as atribute.
* @eexample diff
* @param p RShape, the polygon with which to perform the difference
* @return RShape, the difference of the two polygons
* @related union ( )
* @related xor ( )
* @related intersection ( )
*/
  public RShape diff( RShape p ){
    return RClip.diff( this.toPolygon(), p.toPolygon() ).toShape();
  }
    
  /**
* Use this to return the start, control and end points of the shape. It returns the points in the way of an array of RPoint.
* @eexample RShape_getHandles
* @return RPoint[], the start, control and end points returned in an array.
* */
  public RPoint[] getHandles(){
    int numSubshapes = countSubshapes();
    if(numSubshapes == 0){
      return null;
    }
    
    RPoint[] result=null;
    RPoint[] newresult=null;
    for(int i=0;i<numSubshapes;i++){
      RPoint[] newPoints = subshapes[i].getHandles();
      if(newPoints!=null){
        if(result==null){
          result = new RPoint[newPoints.length];
          System.arraycopy(newPoints,0,result,0,newPoints.length);
        }else{
          newresult = new RPoint[result.length + newPoints.length];
          System.arraycopy(result,0,newresult,0,result.length);
          System.arraycopy(newPoints,0,newresult,result.length,newPoints.length);
          result = newresult;
        }
      }
    }
    return result;
  }
  
  /**
* Use this to return a point on the curve given a certain advancement. It returns the point in the way of an RPoint.
* @eexample RShape_getPoints
* @return RPoint[], the point on the curve.
* */
  public RPoint getPoint(float t){
    float[] indAndAdv = indAndAdvAt(t);
    int indOfElement = (int)(indAndAdv[0]);
    float advOfElement = indAndAdv[1];
 
    return subshapes[indOfElement].getPoint(advOfElement);
  }
 
  /**
* Use this to return the points on the curve of the shape. It returns the point in the way of an RPoint.
* @eexample RShape_getPoints
* @return RPoint[], the points returned in an array.
* */
  public RPoint[] getPoints(){
    int numSubshapes = countSubshapes();
    if(numSubshapes == 0){
      return null;
    }
 
    RCommand.segmentAccOffset = RCommand.segmentOffset;
    RPoint[] result=null;
    RPoint[] newresult=null;
    for(int i=0;i<numSubshapes;i++){
      RPoint[] newPoints = subshapes[i].getPoints();
      if(newPoints!=null){
        if(result==null){
          result = new RPoint[newPoints.length];
          System.arraycopy(newPoints,0,result,0,newPoints.length);
        }else{
          newresult = new RPoint[result.length + newPoints.length];
          System.arraycopy(result,0,newresult,0,result.length);
          System.arraycopy(newPoints,0,newresult,result.length,newPoints.length);
          result = newresult;
        }
      }
    }
    return result;
  }
 
  /**
* Use this to return a point on the curve given a certain advancement. It returns the point in the way of an RPoint.
* @eexample RShape_getTangents
* @return RPoint[], the point on the curve.
* */
  public RPoint getTangent(float t){
    float[] indAndAdv = indAndAdvAt(t);
    int indOfElement = (int)(indAndAdv[0]);
    float advOfElement = indAndAdv[1];
 
    return subshapes[indOfElement].getTangent(advOfElement);
  }
 
  /**
* Use this to return the points on the curve of the shape. It returns the point in the way of an RPoint.
* @eexample RShape_getTangents
* @return RPoint[], the points returned in an array.
* */
  public RPoint[] getTangents(){
    int numSubshapes = countSubshapes();
    if(numSubshapes == 0){
      return null;
    }
    
    RPoint[] result=null;
    RPoint[] newresult=null;
    for(int i=0;i<numSubshapes;i++){
      RPoint[] newPoints = subshapes[i].getTangents();
      if(newPoints!=null){
        if(result==null){
          result = new RPoint[newPoints.length];
          System.arraycopy(newPoints,0,result,0,newPoints.length);
        }else{
          newresult = new RPoint[result.length + newPoints.length];
          System.arraycopy(result,0,newresult,0,result.length);
          System.arraycopy(newPoints,0,newresult,result.length,newPoints.length);
          result = newresult;
        }
      }
    }
    return result;
  }
  
  public RShape[] splitAll(float t){
    RShape[] result = new RShape[2];
    result[0] = new RShape();
    result[1] = new RShape();
    
    for(int i=0; i<countSubshapes(); i++){
      RSubshape[] splittedSubshapes = subshapes[i].split(t);
      if(splittedSubshapes != null){
        result[0].addSubshape(splittedSubshapes[0]);
        result[1].addSubshape(splittedSubshapes[1]);
      }
    }
    
    result[0].setStyle(this);
    result[1].setStyle(this);
    return result;
  }
 
  /**
* Use this to insert a split point into the shape.
* @eexample insertHandle
* @param t float, the parameter of advancement on the curve. t must have values between 0 and 1.
* */
  public void insertHandle(float t){
    if((t == 0F) || (t == 1F)){
      return;
    }
 
    float[] indAndAdv = indAndAdvAt(t);
    int indOfElement = (int)(indAndAdv[0]);
    float advOfElement = indAndAdv[1];
 
    subshapes[indOfElement].insertHandle(advOfElement);
    
    // Clear the cache
    lenCurves = null;
    lenCurve = -1F;
 
    return;
  }
 
  /**
* Use this to insert a split point into each command of the shape.
* @eexample insertHandleAll
* @param t float, the parameter of advancement on the curve. t must have values between 0 and 1.
* */
  public void insertHandleAll(float t){
    if((t == 0F) || (t == 1F)){
      return;
    }
    
    int numSubshapes = countSubshapes();
    if(numSubshapes == 0){
      return;
    }
    
    for( int i = 0 ; i < numSubshapes; i++ ) {
      subshapes[i].insertHandleAll(t);
    }
 
    // Clear the cache
    lenCurves = null;
    lenCurve = -1F;
    
    return;
  }
 
  public RShape[] split(float t){
    RShape[] result = new RShape[2];
    result[0] = new RShape();
    result[1] = new RShape();
 
    int numSubshapes = countSubshapes();
    if(numSubshapes == 0){
      return null;
    }
 
    if(t == 0.0F){
      result[0] = new RShape();
      result[0].setStyle(this);
 
      result[1] = new RShape(this);
      result[1].setStyle(this);
 
      return result;
    }
    
    if(t == 1.0F){
      result[0] = new RShape(this);
      result[0].setStyle(this);
    
      result[1] = new RShape();
      result[1].setStyle(this);
 
      return result;
    }
    
    float[] indAndAdv = indAndAdvAt(t);
    int indOfElement = (int)(indAndAdv[0]);
    float advOfElement = indAndAdv[1];
    
    RSubshape[] splittedShapes = subshapes[indOfElement].split(advOfElement);
    
    result[0] = new RShape();
    for(int i = 0; i<indOfElement; i++){
      result[0].addSubshape(new RSubshape(subshapes[i]));
    }
    result[0].addSubshape(new RSubshape(splittedShapes[0]));
    result[0].setStyle(this);
 
    result[1] = new RShape();
    result[1].addSubshape(new RSubshape(splittedShapes[1]));
    for(int i = indOfElement + 1; i < countSubshapes(); i++){
      result[1].addSubshape(new RSubshape(subshapes[i]));
    }
    result[1].setStyle(this);
    
    return result;
  }
 
  /**
* Use this method to adapt a group of of figures to a shape.
* @eexample RGroup_adapt
* @param RSubshape sshp, the subshape to which to adapt
* @return RGroup, the adapted group
*/
  public void adapt(RShape shp, float wght, float lngthOffset) throws RuntimeException{
    RContour c = this.getBounds();
    float xmin = c.points[0].x;
    float xmax = c.points[2].x;
    
    switch(RGeomerative.adaptorType){
    case RGeomerative.BYPOINT:
      RPoint[] ps = this.getHandles();
      if(ps != null){
        for(int k=0;k<ps.length;k++){
          float px = ps[k].x;
          float py = ps[k].y;
          
          float t = ((px-xmin)/(xmax-xmin) + lngthOffset) % 1.001F;
          float amp = (py);
          
          RPoint tg = shp.getTangent(t);
          RPoint p = shp.getPoint(t);
          float angle = (float)Math.atan2(tg.y, tg.x) - (float)Math.PI/2F;
          
          ps[k].x = p.x + wght*amp*(float)Math.cos(angle);
          ps[k].y = p.y + wght*amp*(float)Math.sin(angle);
        }
      }
      break;
    case RGeomerative.BYELEMENTINDEX:
    case RGeomerative.BYELEMENTPOSITION:
      RContour elemc = shp.getBounds();
      
      float px = (elemc.points[2].x + elemc.points[0].x) / 2F;
      float py = (elemc.points[2].y - elemc.points[0].y) / 2F;
      float t = ((px-xmin)/(xmax-xmin) + lngthOffset ) % 1F;
      
      RPoint tg = shp.getTangent(t);
      RPoint p = shp.getPoint(t);
      float angle = (float)Math.atan2(tg.y, tg.x);
      
      RPoint pletter = new RPoint(px,py);
      p.sub(pletter);
      
      RMatrix mtx = new RMatrix();
      mtx.translate(p);
      mtx.rotate(angle,pletter);
      mtx.scale(wght,pletter);
      
      this.transform(mtx);
      break;
      
    default:
      throw new RuntimeException("Unknown adaptor type : "+RGeomerative.adaptorType+". The method RGeomerative.setAdaptor() only accepts RGeomerative.BYPOINT or RGeomerative.BYELEMENT as parameter values.");
    }
  }
  
  public void adapt(RShape shp) throws RuntimeException{
    adapt(shp, RGeomerative.adaptorScale, RGeomerative.adaptorLengthOffset);
  }
 
  /**
* Use this method to get the type of element this is.
* @eexample RShape_getType
* @return int, will allways return RGeomElem.SHAPE
*/
  public int getType(){
    return type;
  }
  
  public void print(){
    System.out.println("subshapes [count " + this.countSubshapes() + "]: ");
    for(int i=0;i<countSubshapes();i++)
      {
        System.out.println("--- subshape "+i+" ---");
        subshapes[i].print();
        System.out.println("---------------");
      }
  }
  
  /**
* Use this method to draw the shape.
* @eexample drawShape
* @param g PGraphics, the graphics object on which to draw the shape
*/
  public void draw(PGraphics g){
    try{
      Class declaringClass = g.getClass().getMethod("breakShape", null).getDeclaringClass();
      if(declaringClass != g.getClass()){
        // The backend does not implement breakShape
        drawUsingInternalTesselator(g);
      }else{
        // The backend does implement breakShape
        drawUsingBreakShape(g);
      }
    }catch(NoSuchMethodException e){
    }
  }
 
  public void draw(PApplet g){
    try{
      Class declaringClass = g.g.getClass().getMethod("breakShape", null).getDeclaringClass();
      if(declaringClass != g.g.getClass()){
        // The backend does not implement breakShape
        drawUsingInternalTesselator(g);
      }else{
        // The backend does implement breakShape
        drawUsingBreakShape(g);
      }
    }catch(NoSuchMethodException e){
    }
  }
  
  // ----------------------
  // --- Private Methods ---
  // ----------------------
 
  protected void calculateCurveLengths(){
    lenCurves = new float[countSubshapes()];
    lenCurve = 0F;
    for(int i=0;i<countSubshapes();i++){
      lenCurves[i] = subshapes[i].getCurveLength();
      lenCurve += lenCurves[i];
    }
  }
 
  private float[] indAndAdvAt(float t){
    int indOfElement = 0;
    float[] lengthsCurves = getCurveLengths();
    float lengthCurve = getCurveLength();
 
    /* Calculate the amount of advancement t mapped to each command */
    /* We use a simple algorithm where we give to each command the same amount of advancement */
    /* A more useful way would be to give to each command an advancement proportional to the length of the command */
    /* Old method with uniform advancement per command
float advPerCommand;
advPerCommand = 1F / numSubshapes;
indCommand = (int)(Math.floor(t / advPerCommand)) % numSubshapes;
advOfCommand = (t*numSubshapes - indCommand);
*/
    
    float accumulatedAdvancement = lengthsCurves[indOfElement] / lengthCurve;
    float prevAccumulatedAdvancement = 0F;
    
    /* Find in what command the advancement point is */
    while(t > accumulatedAdvancement){
      indOfElement++;
      prevAccumulatedAdvancement = accumulatedAdvancement;
      accumulatedAdvancement += (lengthsCurves[indOfElement] / lengthCurve);
    }
    
    float advOfElement = (t-prevAccumulatedAdvancement) / (lengthsCurves[indOfElement] / lengthCurve);
 
    float[] indAndAdv = new float[2];
 
    indAndAdv[0] = indOfElement;
    indAndAdv[1] = advOfElement;
    
    return indAndAdv;
  }
  
  
  
  private void append(RSubshape nextsubshape)
  {
    RSubshape[] newsubshapes;
    if(subshapes==null){
      newsubshapes = new RSubshape[1];
      newsubshapes[0] = nextsubshape;
      currentSubshape = 0;
    }else{
      newsubshapes = new RSubshape[this.subshapes.length+1];
      System.arraycopy(this.subshapes,0,newsubshapes,0,this.subshapes.length);
      newsubshapes[this.subshapes.length]=nextsubshape;
      currentSubshape++;
    }
    this.subshapes=newsubshapes;
  }
 
  private void drawUsingInternalTesselator(PGraphics g){
    int numSubshapes = countSubshapes();
    
    if(numSubshapes!=0){
      if(isIn(g)) {
        if(!RGeomerative.ignoreStyles){
          saveContext(g);
          setContext(g);
        }
 
        // Save the information about the current context
        boolean strokeBefore = g.stroke;
        int strokeColorBefore = g.strokeColor;
        float strokeWeightBefore = g.strokeWeight;
        boolean smoothBefore = g.smooth;
        boolean fillBefore = g.fill;
        int fillColorBefore = g.fillColor;
 
        // By default always drawy with an ADAPTATIVE segmentator
        int lastSegmentator = RCommand.segmentType;
        RCommand.setSegmentator(RCommand.ADAPTATIVE);
        
        // Check whether to draw the fill or not
        if(g.fill){
          // Since we are drawing the different tristrips we must turn off the stroke or make it the same color as the fill
          // NOTE: there's currently no way of drawing the outline of a mesh, since no information is kept about what vertices are at the edge
 
          // This is here because when rendering meshes we get unwanted lines between the triangles
          g.noStroke();
          try{
            g.noSmooth();
          }catch(Exception e){}
          
          RMesh tempMesh = this.toMesh();
          tempMesh.draw(g);
          
          // Restore the old context
          g.stroke(strokeColorBefore);
          if(!strokeBefore){
            g.noStroke();
          }
          
          try{
            if(smoothBefore){
              g.smooth();
            }
          }catch(Exception e){}
        }
        
        // Check whether to draw the stroke
        g.noFill();
        if(!strokeBefore){
          // If there is no stroke to draw
          // we will still draw one the color of the fill in order to have antialiasing
          g.stroke(g.fillColor);
          g.strokeWeight(1F);
        }
          
        for(int i=0;i<numSubshapes;i++){
          subshapes[i].draw(g);
        }
 
        // Restore the fill state and stroke state and color
        if(fillBefore){
          g.fill(fillColorBefore);
        } else {
          g.noFill();
        }
        g.strokeWeight(strokeWeightBefore);
        g.stroke(strokeColorBefore);
        if(!strokeBefore){
          g.noStroke();
        }
        
        // Restore the user set segmentator
        RCommand.setSegmentator(lastSegmentator);
 
        if(!RGeomerative.ignoreStyles){
          restoreContext(g);
        }
      }
    }
  }
 
  private void drawUsingInternalTesselator(PApplet p){
    int numSubshapes = countSubshapes();
    
    if(numSubshapes!=0){
      if(isIn(p)) {
        if(!RGeomerative.ignoreStyles){
          saveContext(p);
          setContext(p);
        }
 
        // Save the information about the current context
        boolean strokeBefore = p.g.stroke;
        int strokeColorBefore = p.g.strokeColor;
        float strokeWeightBefore = p.g.strokeWeight;
        boolean smoothBefore = p.g.smooth;
        boolean fillBefore = p.g.fill;
        int fillColorBefore = p.g.fillColor;
 
        // By default always drawy with an ADAPTATIVE segmentator
        int lastSegmentator = RCommand.segmentType;
        RCommand.setSegmentator(RCommand.ADAPTATIVE);
        
        // Check whether to draw the fill or not
        if(p.g.fill){
          // Since we are drawing the different tristrips we must turn off the stroke or make it the same color as the fill
          // NOTE: there's currently no way of drawing the outline of a mesh, since no information is kept about what vertices are at the edge
 
          // This is here because when rendering meshes we get unwanted lines between the triangles
          p.noStroke();
          try{
            p.noSmooth();
          }catch(Exception e){}
          
          RMesh tempMesh = this.toMesh();
          tempMesh.draw(p);
          
          // Restore the old context
          p.stroke(strokeColorBefore);
          p.strokeWeight(strokeWeightBefore);
          if(!strokeBefore){
            p.noStroke();
          }
          
          try{
            if(smoothBefore){
              p.smooth();
            }
          }catch(Exception e){}
        }
        
        
        // Check whether to draw the stroke
        p.noFill();
        if((smoothBefore && fillBefore) || strokeBefore){
          if(!strokeBefore){
            // If there is no stroke to draw
            // we will still draw one the color
            // of the fill in order to have antialiasing
            p.stroke(fillColorBefore);
            p.strokeWeight(1F);
          }
          
          for(int i=0;i<numSubshapes;i++){
            subshapes[i].draw(p);
          }
          
          // Restore the old context
          if(fillBefore){
            p.fill(fillColorBefore);
          }
          p.strokeWeight(strokeWeightBefore);
          p.stroke(strokeColorBefore);
          if(!strokeBefore){
            p.noStroke();
          }
        }
        
        // Restore the user set segmentator
        RCommand.setSegmentator(lastSegmentator);
 
        if(!RGeomerative.ignoreStyles){
          restoreContext(p);
        }
      }
    }
  }
  
  private void drawUsingBreakShape(PGraphics g){
    int numSubshapes = countSubshapes();
    if(numSubshapes!=0){
      if(isIn(g)){
        if(!RGeomerative.ignoreStyles){
          saveContext(g);
          setContext(g);
        }
 
        boolean closed = false;
        g.beginShape();
        for(int i=0;i<numSubshapes;i++){
          RSubshape subshape = subshapes[i];
          closed |= subshape.closed;
          for(int j = 0; j < subshape.countCommands(); j++ ){
            RPoint[] pnts = subshape.commands[j].getHandles();
            if(j==0){
              g.vertex(pnts[0].x, pnts[0].y);
            }
            switch( subshape.commands[j].getCommandType() )
              {
              case RCommand.LINETO:
                g.vertex( pnts[1].x, pnts[1].y );
                break;
              case RCommand.QUADBEZIERTO:
                g.bezierVertex( pnts[1].x, pnts[1].y, pnts[2].x, pnts[2].y, pnts[2].x, pnts[2].y );
                break;
              case RCommand.CUBICBEZIERTO:
                g.bezierVertex( pnts[1].x, pnts[1].y, pnts[2].x, pnts[2].y, pnts[3].x, pnts[3].y );
                break;
              }
          }
          if(i < (numSubshapes - 1)){
            g.breakShape();
          }
 
        }
        g.endShape(closed ? PConstants.CLOSE : PConstants.OPEN);
 
        if(!RGeomerative.ignoreStyles){
          restoreContext(g);
        }
      }
    }
  }
  
  private void drawUsingBreakShape(PApplet g){
    int numSubshapes = countSubshapes();
    if(numSubshapes!=0){
      if(isIn(g)){
        if(!RGeomerative.ignoreStyles){
          saveContext(g);
          setContext(g);
        }
 
        boolean closed = false;
        g.beginShape();
        for(int i=0;i<numSubshapes;i++){
          RSubshape subshape = subshapes[i];
          closed |= subshape.closed;
          for(int j = 0; j < subshape.countCommands(); j++ ){
            RPoint[] pnts = subshape.commands[j].getHandles();
            if(j==0){
              g.vertex(pnts[0].x, pnts[0].y);
            }
            switch( subshape.commands[j].getCommandType() )
              {
              case RCommand.LINETO:
                g.vertex( pnts[1].x, pnts[1].y );
                break;
              case RCommand.QUADBEZIERTO:
                g.bezierVertex( pnts[1].x, pnts[1].y, pnts[2].x, pnts[2].y, pnts[2].x, pnts[2].y );
                break;
              case RCommand.CUBICBEZIERTO:
                g.bezierVertex( pnts[1].x, pnts[1].y, pnts[2].x, pnts[2].y, pnts[3].x, pnts[3].y );
                break;
              }
          }
          if(i < (numSubshapes - 1)){
            g.breakShape();
          }
 
        }
        g.endShape(closed ? PConstants.CLOSE : PConstants.OPEN);
 
        if(!RGeomerative.ignoreStyles){
          restoreContext(g);
        }
      }
    }
  }
 
}