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
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
|
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
* Copyright (c) 2010 JogAmp Community. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
* INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN
* MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR
* ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR
* ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR
* DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
* DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
* ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF
* SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use
* in the design, construction, operation or maintenance of any nuclear
* facility.
*
* Sun gratefully acknowledges that this software was originally authored
* and developed by Kenneth Bradley Russell and Christopher John Kline.
*/
package com.jogamp.gluegen.opengl;
import com.jogamp.gluegen.CodeGenUtils;
import com.jogamp.gluegen.JavaType;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.nio.Buffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class BuildComposablePipeline {
/** <p>Default: true</p>. */
public static final int GEN_DEBUG = 1 << 0;
/** <p>Default: true</p>. */
public static final int GEN_TRACE = 1 << 1;
/** <p>Default: false</p>. */
public static final int GEN_CUSTOM = 1 << 2;
/**
* By extra command-line argument: <code>prolog_xor_downstream</code>.
* <p>
* If true, either prolog (if exist) is called or downstream's method, but not both.
* By default, both methods would be called.
* </p>
* <p>Default: false</p>
*/
public static final int GEN_PROLOG_XOR_DOWNSTREAM = 1 << 3;
/**
* By extra command-line argument: <code>gl_identity_by_assignable_class</code>.
* <p>
* If true, implementation does not utilize downstream's <code>isGL*()</code>
* implementation, but determines whether the GL profile is matched by interface inheritance.
* </p>
* <p>Default: false</p>
*/
public static final int GEN_GL_IDENTITY_BY_ASSIGNABLE_CLASS = 1 << 4;
private static final HashMap<String, String> addedGLHooks = new HashMap<String, String>();
private static final String[] addedGLHookMethodNames = new String[] {
"mapBuffer", "mapBufferRange",
"mapNamedBuffer", "mapNamedBufferRange" };
static {
for(int i=0; i<addedGLHookMethodNames.length; i++) {
addedGLHooks.put(addedGLHookMethodNames[i], addedGLHookMethodNames[i]);
}
}
int mode;
private final String outputDir;
private final String outputPackage;
private final String outputName;
private final Class<?> classToComposeAround;
private final Class<?> classPrologOpt;
private final Class<?> classDownstream;
// Only desktop OpenGL has immediate mode glBegin / glEnd
private boolean hasImmediateMode;
// Desktop OpenGL and GLES1 have GL_STACK_OVERFLOW and GL_STACK_UNDERFLOW errors
private boolean hasGL2ES1StackOverflow;
public static Class<?> getClass(final String name) {
Class<?> clazz = null;
try {
clazz = Class.forName(name);
} catch (final Exception e) {
throw new RuntimeException(
"Could not find class \"" + name + "\"", e);
}
return clazz;
}
public static Method getMethod(final Class<?> clazz, final Method m) {
Method res = null;
try {
res = clazz.getMethod(m.getName(), m.getParameterTypes());
} catch (final Exception e) {
}
return res;
}
public static void main(final String[] args) {
final String classToComposeAroundName = args[0];
Class<?> classPrologOpt, classDownstream;
final Class<?> classToComposeAround = getClass(classToComposeAroundName);
final String outputDir = args[1];
String outputPackage, outputName;
int mode;
if (args.length > 2) {
final String outputClazzName = args[2];
outputPackage = getPackageName(outputClazzName);
outputName = getBaseClassName(outputClazzName);
classPrologOpt = getClass(args[3]);
classDownstream = getClass(args[4]);
mode = GEN_CUSTOM;
if (args.length > 5) {
for(int i=5; i<args.length; i++) {
if (args[i].equals("prolog_xor_downstream")) {
mode |= GEN_PROLOG_XOR_DOWNSTREAM;
} else if (args[i].equals("gl_identity_by_assignable_class")) {
mode |= GEN_GL_IDENTITY_BY_ASSIGNABLE_CLASS;
}
}
}
} else {
outputPackage = getPackageName(classToComposeAroundName);
outputName = null; // TBD ..
classPrologOpt = null;
classDownstream = classToComposeAround;
mode = GEN_DEBUG | GEN_TRACE ;
}
final BuildComposablePipeline composer =
new BuildComposablePipeline(mode, outputDir, outputPackage, outputName, classToComposeAround, classPrologOpt, classDownstream);
try {
composer.emit();
} catch (final IOException e) {
throw new RuntimeException(
"Error generating composable pipeline source files", e);
}
}
protected BuildComposablePipeline(final int mode, final String outputDir, final String outputPackage, final String outputName,
final Class<?> classToComposeAround, final Class<?> classPrologOpt, final Class<?> classDownstream) {
this.mode = mode;
this.outputDir = outputDir;
this.outputPackage = outputPackage;
this.outputName = outputName;
this.classToComposeAround = classToComposeAround;
this.classPrologOpt = classPrologOpt;
this.classDownstream = classDownstream;
if (!classToComposeAround.isInterface()) {
throw new IllegalArgumentException(
classToComposeAround.getName() + " is not an interface class");
}
try {
// Keep assignment w/ null comparison for clarification.
// If no exception is thrown, return value is always non-null;
hasImmediateMode =
null != classToComposeAround.getMethod("glBegin", new Class<?>[]{Integer.TYPE});
} catch (final Exception e) {
}
try {
hasGL2ES1StackOverflow = hasImmediateMode &&
(classToComposeAround.getField("GL_STACK_OVERFLOW") != null);
} catch (final Exception e) {
}
}
/**
* Emit the java source code for the classes that comprise the composable
* pipeline.
*/
public void emit() throws IOException {
final List<Method> publicMethodsRaw = Arrays.asList(classToComposeAround.getMethods());
final Set<PlainMethod> publicMethodsPlain = new HashSet<PlainMethod>();
for (final Iterator<Method> iter = publicMethodsRaw.iterator(); iter.hasNext();) {
final Method method = iter.next();
// Don't hook methods which aren't real GL methods,
// such as the synthetic "isGL2ES2" "getGL2ES2"
final String name = method.getName();
if ( !name.startsWith("getGL") &&
!name.startsWith("isGL") &&
!name.equals("getDownstreamGL") &&
!name.equals("toString") ) {
final boolean runHooks = name.startsWith("gl") || addedGLHooks.containsKey(name);
publicMethodsPlain.add(new PlainMethod(method, runHooks));
}
}
if (0 != (mode & GEN_DEBUG)) {
(new DebugPipeline(outputDir, outputPackage, classToComposeAround, classDownstream)).emit(publicMethodsPlain.iterator());
}
if (0 != (mode & GEN_TRACE)) {
(new TracePipeline(outputDir, outputPackage, classToComposeAround, classDownstream)).emit(publicMethodsPlain.iterator());
}
if (0 != (mode & GEN_CUSTOM)) {
(new CustomPipeline(mode, outputDir, outputPackage, outputName, classToComposeAround, classPrologOpt, classDownstream)).emit(publicMethodsPlain.iterator());
}
}
public static String getPackageName(final String clazzName) {
final int lastDot = clazzName.lastIndexOf('.');
if (lastDot == -1) {
// no package, class is at root level
return null;
}
return clazzName.substring(0, lastDot);
}
public static String getBaseClassName(final String clazzName) {
final int lastDot = clazzName.lastIndexOf('.');
if (lastDot == -1) {
// no package, class is at root level
return clazzName;
}
return clazzName.substring(lastDot + 1);
}
//-------------------------------------------------------
protected class PlainMethod {
Method m;
boolean runHooks;
PlainMethod(final Method m, final boolean runHooks) {
this.m = m;
this.runHooks = runHooks;
}
public Method getWrappedMethod() {
return m;
}
public boolean runHooks() {
return runHooks;
}
@Override
public boolean equals(final Object obj) {
if (obj instanceof PlainMethod) {
final PlainMethod b = (PlainMethod) obj;
final boolean res =
m.getName().equals(b.m.getName())
&& m.getModifiers() == b.m.getModifiers()
&& m.getReturnType().equals(b.m.getReturnType())
&& Arrays.equals(m.getParameterTypes(), b.m.getParameterTypes());
return res;
}
return false;
}
@Override
public int hashCode() {
int hash = m.getName().hashCode() ^ m.getModifiers() ^ m.getReturnType().hashCode();
final Class<?>[] args = m.getParameterTypes();
for (int i = 0; i < args.length; i++) {
hash ^= args[i].hashCode();
}
return hash;
}
@Override
public String toString() {
final Class<?>[] args = m.getParameterTypes();
final StringBuilder argsString = new StringBuilder();
argsString.append("(");
for (int i = 0; i < args.length; i++) {
if (i > 0) {
argsString.append(", ");
}
argsString.append(args[i].getName());
}
argsString.append(")");
return m.toString()
+ "\n\tname: " + m.getName()
+ "\n\tmods: " + m.getModifiers()
+ "\n\tretu: " + m.getReturnType()
+ "\n\targs[" + args.length + "]: " + argsString.toString();
}
}
/**
* Emits a Java source file that represents one element of the composable
* pipeline.
*/
protected abstract class PipelineEmitter {
private File file;
protected String basePackage;
protected String baseName; // does not include package!
protected String downstreamPackage;
protected String downstreamName; // does not include package!
protected String prologPackageOpt = null;
protected String prologNameOpt = null; // does not include package!
protected String outputDir;
protected String outputPackage;
protected Class<?> baseInterfaceClass;
protected Class<?> prologClassOpt = null;
protected Class<?> downstreamClass;
/**
* @param outputDir the directory into which the pipeline classes will be
* generated.
* @param baseInterfaceClassName the full class name (including package,
* e.g. "java.lang.String") of the interface that the pipeline wraps
* @exception IllegalArgumentException if classToComposeAround is not an
* interface.
*/
PipelineEmitter(final String outputDir, final String outputPackage, final Class<?> baseInterfaceClass, final Class<?> prologClassOpt, final Class<?> downstreamClass) {
this.outputDir = outputDir;
this.outputPackage = outputPackage;
this.baseInterfaceClass = baseInterfaceClass;
this.prologClassOpt = prologClassOpt;
this.downstreamClass = downstreamClass;
basePackage = getPackageName(baseInterfaceClass.getName());
baseName = getBaseClassName(baseInterfaceClass.getName());
downstreamPackage = getPackageName(downstreamClass.getName());
downstreamName = getBaseClassName(downstreamClass.getName());
if (null != prologClassOpt) {
prologPackageOpt = getPackageName(prologClassOpt.getName());
prologNameOpt = getBaseClassName(prologClassOpt.getName());
}
}
public void emit(final Iterator<PlainMethod> methodsToWrap) throws IOException {
final String outputClassName = getOutputName();
this.file = new File(outputDir + File.separatorChar + outputClassName + ".java");
final String parentDir = file.getParent();
if (parentDir != null) {
final File pDirFile = new File(parentDir);
pDirFile.mkdirs();
}
final PrintWriter output = new PrintWriter(new BufferedWriter(new FileWriter(file)));
final List<Class<?>> baseInterfaces = Arrays.asList(baseInterfaceClass.getInterfaces());
final HashSet<Class<?>> clazzList = new HashSet<Class<?>>();
clazzList.add(baseInterfaceClass);
clazzList.addAll(baseInterfaces);
final int ifNamesNumber = clazzList.size();
// keep original order ..
clazzList.clear();
final String[] ifNames = new String[ifNamesNumber];
{
int i = 0;
for (final Iterator<Class<?>> iter = baseInterfaces.iterator(); iter.hasNext();) {
final Class<?> ifClass = iter.next();
if (!clazzList.contains(ifClass)) {
ifNames[i++] = ifClass.getName();
clazzList.add(ifClass);
}
}
if ( !clazzList.contains(baseInterfaceClass) ) {
ifNames[i++] = baseInterfaceClass.getName();
clazzList.add(baseInterfaceClass);
}
}
clazzList.add(downstreamClass);
if (null != prologClassOpt) {
clazzList.add(prologClassOpt);
}
final ArrayList<String> imports = new ArrayList<String>();
imports.add("java.io.*");
imports.add("javax.media.opengl.*");
imports.add("com.jogamp.gluegen.runtime.*");
imports.add(Buffer.class.getPackage().getName()+".*");
for (final Class<?> clasS : clazzList) {
imports.add(clasS.getName());
}
CodeGenUtils.emitJavaHeaders(output,
outputPackage,
outputClassName,
true,
imports,
new String[]{"public"},
ifNames,
null,
new CodeGenUtils.EmissionCallback() {
@Override
public void emit(final PrintWriter w) {
emitClassDocComment(w);
}
});
preMethodEmissionHook(output);
constructorHook(output);
emitGLIsMethods(output);
emitGLGetMethods(output);
while (methodsToWrap.hasNext()) {
final PlainMethod pm = methodsToWrap.next();
final Method m = pm.getWrappedMethod();
emitMethodDocComment(output, m);
emitSignature(output, m);
emitBody(output, m, pm.runHooks());
}
postMethodEmissionHook(output);
output.println();
output.print(" private " + downstreamName + " " + getDownstreamObjectName() + ";");
// end the class
output.println();
output.print("} // end class ");
output.println(outputClassName);
output.flush();
output.close();
System.out.println("wrote to file: " + file);
}
/** Get the name of the object through which API calls should be routed. */
protected String getDownstreamObjectName() {
return "downstream" + downstreamName;
}
/** Get the name of the object which shall be called as a prolog. */
protected String getPrologObjectNameOpt() {
if (null != prologNameOpt) {
return "prolog" + prologNameOpt;
}
return null;
}
protected void emitMethodDocComment(final PrintWriter output, final Method m) {
}
protected void emitSignature(final PrintWriter output, final Method m) {
output.format(" @Override%n public %s %s(%s)%n",
JavaType.createForClass(m.getReturnType()).getName(),
m.getName(),
getArgListAsString(m, true, true));
}
protected void emitBody(final PrintWriter output, final Method m, final boolean runHooks) {
output.println(" {");
final Class<?> retType = m.getReturnType();
final boolean callPreDownstreamHook = runHooks && hasPreDownstreamCallHook(m);
final boolean callPostDownstreamHook = runHooks && hasPostDownstreamCallHook(m);
final boolean callDownstream = (null != getMethod(downstreamClass, m))
&& !(0 != (GEN_PROLOG_XOR_DOWNSTREAM & getMode()) && callPreDownstreamHook);
final boolean hasResult = (retType != Void.TYPE);
if (!callDownstream) {
if (!emptyDownstreamAllowed()) {
throw new RuntimeException("Method " + m + " has no downstream (" + downstreamName + ")");
}
}
if (!callPreDownstreamHook && !callPostDownstreamHook && !callDownstream) {
if (!emptyMethodAllowed()) {
throw new RuntimeException("Method " + m + " is empty, no downstream (" + downstreamName + ") nor prolog (" + prologNameOpt + ").");
} else {
output.print(" if(DEBUG) { System.out.println(\"WARNING: No prolog, no downstream, empty: \"+");
printFunctionCallString(output, m);
output.println("); } ");
}
}
if (callPreDownstreamHook) {
if (hasResult && !callDownstream) {
if (callPostDownstreamHook) {
output.print(" " + JavaType.createForClass(retType).getName());
output.print(" _res = ");
} else {
output.print(" return ");
}
}
preDownstreamCallHook(output, m);
}
if (callDownstream) {
if (hasResult) {
if (callPostDownstreamHook) {
output.print(" " + JavaType.createForClass(retType).getName());
output.print(" _res = ");
} else {
output.print(" return ");
}
}
else {
output.print(" ");
}
output.print(getDownstreamObjectName());
output.print('.');
output.print(m.getName());
output.print('(');
output.print(getArgListAsString(m, false, true));
output.println(");");
}
if (callPostDownstreamHook) {
postDownstreamCallHook(output, m);
}
if (hasResult && callDownstream && callPostDownstreamHook) {
output.println(" return _res;");
}
output.println(" }");
}
protected String getArgListAsString(final Method m, final boolean includeArgTypes, final boolean includeArgNames) {
final StringBuilder buf = new StringBuilder(256);
if (!includeArgNames && !includeArgTypes) {
throw new IllegalArgumentException(
"Cannot generate arglist without both arg types and arg names");
}
final Class<?>[] argTypes = m.getParameterTypes();
for (int i = 0; i < argTypes.length; ++i) {
if (includeArgTypes) {
buf.append(JavaType.createForClass(argTypes[i]).getName());
buf.append(' ');
}
if (includeArgNames) {
buf.append("arg");
buf.append(i);
}
if (i < argTypes.length - 1) {
buf.append(',');
}
}
return buf.toString();
}
/** The name of the class around which this pipeline is being
* composed. E.g., if this pipeline was constructed with
* "java.util.Set" as the baseInterfaceClassName, then this method will
* return "Set".
*/
protected String getBaseInterfaceName() {
return baseName;
}
/** Get the output name for this pipeline class. */
protected abstract String getOutputName();
/**
* Called after the class headers have been generated, but before any
* method wrappers have been generated.
*/
protected void preMethodEmissionHook(final PrintWriter output) {
output.println(" public static final boolean DEBUG = jogamp.opengl.Debug.debug(\"" + getOutputName() + "\");");
}
/**
* Emits the constructor for the pipeline; called after the preMethodEmissionHook.
*/
protected abstract void constructorHook(PrintWriter output);
/**
* Called after the method wrappers have been generated, but before the
* closing parenthesis of the class is emitted.
*/
protected void postMethodEmissionHook(final PrintWriter output) {
output.println(" @Override");
output.println(" public String toString() {");
output.println(" StringBuilder sb = new StringBuilder();");
output.println(" sb.append(\"" + getOutputName() + " [this 0x\"+Integer.toHexString(hashCode())+\" implementing " + baseInterfaceClass.getName() + ",\\n\\t\");");
if (null != prologClassOpt) {
output.println(" sb.append(\" prolog: \"+" + getPrologObjectNameOpt() + ".toString()+\",\\n\\t\");");
}
output.println(" sb.append(\" downstream: \"+" + getDownstreamObjectName() + ".toString()+\"\\n\\t]\");");
output.println(" return sb.toString();");
output.println(" }");
}
/**
* Called before the pipeline routes the call to the downstream object.
*/
protected abstract void preDownstreamCallHook(PrintWriter output, Method m);
protected abstract boolean hasPreDownstreamCallHook(Method m);
/**
* Called after the pipeline has routed the call to the downstream object,
* but before the calling function exits or returns a value.
*/
protected abstract void postDownstreamCallHook(PrintWriter output, Method m);
protected abstract boolean hasPostDownstreamCallHook(Method m);
protected abstract int getMode();
protected abstract boolean emptyMethodAllowed();
protected abstract boolean emptyDownstreamAllowed();
/** Emit a Javadoc comment for this pipeline class. */
protected abstract void emitClassDocComment(PrintWriter output);
/**
* Emits one of the isGL* methods.
*/
protected void emitGLIsMethod(final PrintWriter output, final String type) {
output.println(" @Override");
output.println(" public final boolean is" + type + "() {");
if( 0 != (GEN_GL_IDENTITY_BY_ASSIGNABLE_CLASS & getMode() ) ) {
final Class<?> clazz = BuildComposablePipeline.getClass("javax.media.opengl." + type);
if (clazz.isAssignableFrom(baseInterfaceClass)) {
output.println(" return true;");
} else {
output.println(" return false;");
}
} else {
output.println(" return " + getDownstreamObjectName() + ".is" + type + "();");
}
output.println(" }");
}
/**
* Emits all of the isGL* methods.
*/
protected void emitGLIsMethods(final PrintWriter output) {
output.println(" @Override");
output.println(" public final boolean isGL() {");
output.println(" return true;");
output.println(" }");
emitGLIsMethod(output, "GL4bc");
emitGLIsMethod(output, "GL4");
emitGLIsMethod(output, "GL3bc");
emitGLIsMethod(output, "GL3");
emitGLIsMethod(output, "GL2");
emitGLIsMethod(output, "GLES1");
emitGLIsMethod(output, "GLES2");
emitGLIsMethod(output, "GLES3");
emitGLIsMethod(output, "GL2ES1");
emitGLIsMethod(output, "GL2ES2");
emitGLIsMethod(output, "GL2ES3");
emitGLIsMethod(output, "GL3ES3");
emitGLIsMethod(output, "GL4ES3");
emitGLIsMethod(output, "GL2GL3");
if( 0 != (GEN_GL_IDENTITY_BY_ASSIGNABLE_CLASS & getMode() ) ) {
output.println(" @Override");
output.println(" public final boolean isGLES() {");
output.println(" return isGLES3() || isGLES2() || isGLES1();");
output.println(" }");
} else {
emitGLIsMethod(output, "GLES");
}
output.println(" @Override");
output.println(" public final boolean isGL4core() {");
output.println(" return " + getDownstreamObjectName() + ".isGL4core();");
output.println(" }");
output.println(" @Override");
output.println(" public final boolean isGL3core() {");
output.println(" return " + getDownstreamObjectName() + ".isGL3core();");
output.println(" }");
output.println(" @Override");
output.println(" public final boolean isGLcore() {");
output.println(" return " + getDownstreamObjectName() + ".isGLcore();");
output.println(" }");
output.println(" @Override");
output.println(" public final boolean isGLES2Compatible() {");
output.println(" return " + getDownstreamObjectName() + ".isGLES2Compatible();");
output.println(" }");
output.println(" @Override");
output.println(" public final boolean isGLES3Compatible() {");
output.println(" return " + getDownstreamObjectName() + ".isGLES3Compatible();");
output.println(" }");
}
/**
* Emits one of the getGL* methods.
*/
protected void emitGLGetMethod(final PrintWriter output, final String type) {
output.println(" @Override");
output.println(" public final javax.media.opengl." + type + " get" + type + "() {");
final Class<?> clazz = BuildComposablePipeline.getClass("javax.media.opengl." + type);
if (clazz.isAssignableFrom(baseInterfaceClass)) {
if( 0 != (GEN_GL_IDENTITY_BY_ASSIGNABLE_CLASS & getMode() ) ) {
output.println(" return this;");
} else {
output.println(" if( is" + type + "() ) { return this; }");
output.println(" throw new GLException(\"Not a " + type + " implementation\");");
}
} else {
output.println(" throw new GLException(\"Not a " + type + " implementation\");");
}
output.println(" }");
}
/**
* Emits all of the getGL* methods.
*/
protected void emitGLGetMethods(final PrintWriter output) {
output.println(" @Override");
output.println(" public final javax.media.opengl.GL getGL() {");
output.println(" return this;");
output.println(" }");
emitGLGetMethod(output, "GL4bc");
emitGLGetMethod(output, "GL4");
emitGLGetMethod(output, "GL3bc");
emitGLGetMethod(output, "GL3");
emitGLGetMethod(output, "GL2");
emitGLGetMethod(output, "GLES1");
emitGLGetMethod(output, "GLES2");
emitGLGetMethod(output, "GLES3");
emitGLGetMethod(output, "GL2ES1");
emitGLGetMethod(output, "GL2ES2");
emitGLGetMethod(output, "GL2ES3");
emitGLGetMethod(output, "GL3ES3");
emitGLGetMethod(output, "GL4ES3");
emitGLGetMethod(output, "GL2GL3");
output.println(" @Override");
output.println(" public final GL getDownstreamGL() throws GLException {");
output.println(" return " + getDownstreamObjectName() + ";");
output.println(" }");
output.println(" @Override");
output.println(" public final GLProfile getGLProfile() {");
output.println(" return " + getDownstreamObjectName() + ".getGLProfile();");
output.println(" }");
}
} // end class PipelineEmitter
//-------------------------------------------------------
protected class CustomPipeline extends PipelineEmitter {
String className;
int mode;
CustomPipeline(final int mode, final String outputDir, final String outputPackage, final String outputName, final Class<?> baseInterfaceClass, final Class<?> prologClassOpt, final Class<?> downstreamClass) {
super(outputDir, outputPackage, baseInterfaceClass, prologClassOpt, downstreamClass);
className = outputName;
this.mode = mode;
}
@Override
protected String getOutputName() {
return className;
}
@Override
protected int getMode() {
return mode;
}
@Override
protected boolean emptyMethodAllowed() {
return true;
}
@Override
protected boolean emptyDownstreamAllowed() {
return true;
}
@Override
protected void preMethodEmissionHook(final PrintWriter output) {
super.preMethodEmissionHook(output);
}
@Override
protected void constructorHook(final PrintWriter output) {
output.print(" public " + getOutputName() + "(");
output.print(downstreamName + " " + getDownstreamObjectName());
if (null != prologNameOpt) {
output.println(", " + prologNameOpt + " " + getPrologObjectNameOpt() + ")");
} else {
output.println(")");
}
output.println(" {");
output.println(" if (" + getDownstreamObjectName() + " == null) {");
output.println(" throw new IllegalArgumentException(\"null " + getDownstreamObjectName() + "\");");
output.println(" }");
output.print(" this." + getDownstreamObjectName());
output.println(" = " + getDownstreamObjectName() + ";");
if (null != prologNameOpt) {
output.print(" this." + getPrologObjectNameOpt());
output.println(" = " + getPrologObjectNameOpt() + ";");
}
output.println(" }");
output.println();
}
@Override
protected void postMethodEmissionHook(final PrintWriter output) {
super.postMethodEmissionHook(output);
if (null != prologNameOpt) {
output.print(" private " + prologNameOpt + " " + getPrologObjectNameOpt() + ";");
}
}
@Override
protected void emitClassDocComment(final PrintWriter output) {
output.println("/**");
output.println(" * Composable pipeline {@link " + outputPackage + "." + outputName + "}, implementing the interface");
output.println(" * {@link " + baseInterfaceClass.getName() + "}");
output.println(" * <p>");
output.println(" * Each method follows the call graph <ul>");
if (null != prologClassOpt) {
output.println(" * <li> call <em>prolog</em> {@link " + prologClassOpt.getName() + "} if available");
}
output.println(" * <li> call <em>downstream</em> {@link " + downstreamClass.getName() + "} if available");
if (null != prologClassOpt && 0 != (GEN_PROLOG_XOR_DOWNSTREAM & getMode())) {
output.println(" * <strong>and</strong> if no call to {@link " + prologClassOpt.getName() + "} is made");
}
output.println(" * </ul><p>");
output.println(" * ");
output.println(" * <ul>");
output.println(" * <li> <em>Interface</em> {@link " + baseInterfaceClass.getName() + "}");
if (null != prologClassOpt) {
output.println(" * <li> <em>Prolog</em> {@link " + prologClassOpt.getName() + "}");
}
output.println(" * <li> <em>Downstream</em> {@link " + downstreamClass.getName() + "}");
output.println(" * </ul><p>");
output.println(" * Sample code which installs this pipeline: </P>");
output.println(" * ");
output.println("<PRE>");
if (null != prologNameOpt) {
output.println(" GL gl = drawable.setGL( new " + className + "( drawable.getGL().getGL2ES2(), new " + prologNameOpt + "( drawable.getGL().getGL2ES2() ) ) );");
} else {
output.println(" GL gl = drawable.setGL( new " + className + "( drawable.getGL().getGL2ES2() ) );");
}
output.println("</PRE>");
output.println("*/");
}
@Override
protected boolean hasPreDownstreamCallHook(final Method m) {
return null != getMethod(prologClassOpt, m);
}
@Override
protected void preDownstreamCallHook(final PrintWriter output, final Method m) {
if (null != prologNameOpt) {
output.print(getPrologObjectNameOpt());
output.print('.');
output.print(m.getName());
output.print('(');
output.print(getArgListAsString(m, false, true));
output.println(");");
}
}
@Override
protected boolean hasPostDownstreamCallHook(final Method m) {
return false;
}
@Override
protected void postDownstreamCallHook(final PrintWriter output, final Method m) {
}
} // end class CustomPipeline
protected class DebugPipeline extends PipelineEmitter {
String className;
DebugPipeline(final String outputDir, final String outputPackage, final Class<?> baseInterfaceClass, final Class<?> downstreamClass) {
super(outputDir, outputPackage, baseInterfaceClass, null, downstreamClass);
className = "Debug" + getBaseInterfaceName();
}
@Override
protected String getOutputName() {
return className;
}
@Override
protected int getMode() {
return 0;
}
@Override
protected boolean emptyMethodAllowed() {
return false;
}
@Override
protected boolean emptyDownstreamAllowed() {
return false;
}
@Override
protected void preMethodEmissionHook(final PrintWriter output) {
super.preMethodEmissionHook(output);
}
@Override
protected void constructorHook(final PrintWriter output) {
output.print(" public " + getOutputName() + "(");
output.println(downstreamName + " " + getDownstreamObjectName() + ")");
output.println(" {");
output.println(" if (" + getDownstreamObjectName() + " == null) {");
output.println(" throw new IllegalArgumentException(\"null " + getDownstreamObjectName() + "\");");
output.println(" }");
output.print(" this." + getDownstreamObjectName());
output.println(" = " + getDownstreamObjectName() + ";");
if (null != prologNameOpt) {
output.print(" this." + getPrologObjectNameOpt());
output.println(" = " + getPrologObjectNameOpt() + ";");
}
output.println(" // Fetch GLContext object for better error checking (if possible)");
output.println(" _context = " + getDownstreamObjectName() + ".getContext();");
output.println(" }");
output.println();
}
@Override
protected void postMethodEmissionHook(final PrintWriter output) {
super.postMethodEmissionHook(output);
output.println(" private int checkGLError() {");
if (hasImmediateMode) {
output.println(" if (insideBeginEndPair) return GL_NO_ERROR;");
output.println();
}
output.format(" return %s.glGetError();%n", getDownstreamObjectName());
output.println(" }");
output.println(" private void writeGLError(int err, String fmt, Object... args)");
output.println(" {");
output.println(" StringBuilder buf = new StringBuilder();");
output.println(" buf.append(Thread.currentThread().toString());");
output.println(" buf.append(\" glGetError() returned the following error codes after a call to \");");
output.println(" buf.append(String.format(fmt, args));");
output.println(" buf.append(\": \");");
output.println();
output.println(" // Loop repeatedly to allow for distributed GL implementations,");
output.println(" // as detailed in the glGetError() specification");
output.println(" int recursionDepth = 10;");
output.println(" do {");
output.println(" switch (err) {");
output.println(" case GL_INVALID_ENUM: buf.append(\"GL_INVALID_ENUM \"); break;");
output.println(" case GL_INVALID_VALUE: buf.append(\"GL_INVALID_VALUE \"); break;");
output.println(" case GL_INVALID_OPERATION: buf.append(\"GL_INVALID_OPERATION \"); break;");
if (hasGL2ES1StackOverflow) {
output.println(" case GL2ES1.GL_STACK_OVERFLOW: buf.append(\"GL_STACK_OVERFLOW \"); break;");
output.println(" case GL2ES1.GL_STACK_UNDERFLOW: buf.append(\"GL_STACK_UNDERFLOW \"); break;");
}
output.println(" case GL_OUT_OF_MEMORY: buf.append(\"GL_OUT_OF_MEMORY \"); break;");
output.println(" case GL_NO_ERROR: throw new InternalError(\"Should not be treating GL_NO_ERROR as error\");");
output.println(" default: buf.append(\"Unknown glGetError() return value: \");");
output.println(" }");
output.println(" buf.append(\"( \" + err + \" 0x\"+Integer.toHexString(err).toUpperCase() + \"), \");");
output.println(" } while ((--recursionDepth >= 0) && (err = "
+ getDownstreamObjectName()
+ ".glGetError()) != GL_NO_ERROR);");
output.println(" throw new GLException(buf.toString());");
output.println(" }");
if (hasImmediateMode) {
output.println(" /** True if the pipeline is inside a glBegin/glEnd pair.*/");
output.println(" private boolean insideBeginEndPair = false;");
output.println();
}
output.println(" private void checkContext() {");
output.println(" GLContext currentContext = GLContext.getCurrent();");
output.println(" if (currentContext == null) {");
output.println(" throw new GLException(\"No OpenGL context is current on this thread\");");
output.println(" }");
output.println(" if ((_context != null) && (_context != currentContext)) {");
output.println(" throw new GLException(\"This GL object is being incorrectly used with a different GLContext than that which created it\");");
output.println(" }");
output.println(" }");
output.println(" private GLContext _context;");
}
@Override
protected void emitClassDocComment(final PrintWriter output) {
output.println("/**");
output.println(" * <p>");
output.println(" * Composable pipeline which wraps an underlying {@link GL} implementation,");
output.println(" * providing error checking after each OpenGL method call. If an error occurs,");
output.println(" * causes a {@link GLException} to be thrown at exactly the point of failure.");
output.println(" * </p>");
output.println(" * <p>");
output.println(" * Sample code which installs this pipeline:");
output.println(" * <pre>");
output.println(" * gl = drawable.setGL(new DebugGL(drawable.getGL()));");
output.println(" * </pre>");
output.println(" * For automatic instantiation see {@link GLPipelineFactory#create(String, Class, GL, Object[])}");
output.println(" * </p>");
output.println(" */");
}
@Override
protected boolean hasPreDownstreamCallHook(final Method m) {
return true;
}
@Override
protected void preDownstreamCallHook(final PrintWriter output, final Method m) {
output.println(" checkContext();");
}
@Override
protected boolean hasPostDownstreamCallHook(final Method m) {
return true;
}
@Override
protected void postDownstreamCallHook(final PrintWriter output, final Method m) {
if (m.getName().equals("glBegin")) {
output.println(" insideBeginEndPair = true;");
output.println(" // NOTE: can't check glGetError(); it's not allowed inside glBegin/glEnd pair");
} else {
if (m.getName().equals("glEnd")) {
output.println(" insideBeginEndPair = false;");
}
output.println(" final int err = checkGLError();");
output.println(" if (err != GL_NO_ERROR) {");
final StringBuilder fmtsb = new StringBuilder();
final StringBuilder argsb = new StringBuilder();
fmtsb.append("\"%s(");
argsb.append("\"").append(m.getName()).append("\"");
final Class<?>[] params = m.getParameterTypes();
for (int i = 0; i < params.length; i++) {
if (i > 0) {
fmtsb.append(", ");
}
fmtsb.append("<").append(params[i].getName()).append(">");
if (params[i].isArray()) {
//nothing
} else if (params[i].equals(int.class)) {
fmtsb.append(" 0x%X");
argsb.append(", arg").append(i);
} else {
fmtsb.append(" %s");
argsb.append(", arg").append(i);
}
}
fmtsb.append(")\",");
argsb.append(");");
// calls to glGetError() are only allowed outside of glBegin/glEnd pairs
output.print(" writeGLError(err, ");
output.println(fmtsb.toString());
output.print(" ");
output.println(argsb.toString());
output.println(" }");
}
}
} // end class DebugPipeline
//-------------------------------------------------------
protected class TracePipeline extends PipelineEmitter {
String className;
TracePipeline(final String outputDir, final String outputPackage, final Class<?> baseInterfaceClass, final Class<?> downstreamClass) {
super(outputDir, outputPackage, baseInterfaceClass, null, downstreamClass);
className = "Trace" + getBaseInterfaceName();
}
@Override
protected String getOutputName() {
return className;
}
@Override
protected int getMode() {
return 0;
}
@Override
protected boolean emptyMethodAllowed() {
return false;
}
@Override
protected boolean emptyDownstreamAllowed() {
return false;
}
@Override
protected void preMethodEmissionHook(final PrintWriter output) {
super.preMethodEmissionHook(output);
}
@Override
protected void constructorHook(final PrintWriter output) {
output.print(" public " + getOutputName() + "(");
output.println(downstreamName + " " + getDownstreamObjectName() + ", PrintStream " + getOutputStreamName() + ")");
output.println(" {");
output.println(" if (" + getDownstreamObjectName() + " == null) {");
output.println(" throw new IllegalArgumentException(\"null " + getDownstreamObjectName() + "\");");
output.println(" }");
output.print(" this." + getDownstreamObjectName());
output.println(" = " + getDownstreamObjectName() + ";");
output.print(" this." + getOutputStreamName());
output.println(" = " + getOutputStreamName() + ";");
output.println(" }");
output.println();
}
@Override
protected void postMethodEmissionHook(final PrintWriter output) {
super.postMethodEmissionHook(output);
output.println("private PrintStream " + getOutputStreamName() + ";");
output.println("private int indent = 0;");
output.println("protected String dumpArray(Object obj)");
output.println("{");
output.println(" if (obj == null) return \"[null]\";");
output.println(" StringBuilder sb = new StringBuilder(\"[\");");
output.println(" int len = java.lang.reflect.Array.getLength(obj);");
output.println(" int count = Math.min(len,16);");
output.println(" for ( int i =0; i < count; i++ ) {");
output.println(" sb.append(java.lang.reflect.Array.get(obj,i));");
output.println(" if (i < count-1)");
output.println(" sb.append(',');");
output.println(" }");
output.println(" if ( len > 16 )");
output.println(" sb.append(\"...\").append(len);");
output.println(" sb.append(']');");
output.println(" return sb.toString();");
output.println("}");
output.println("protected void print(String str)");
output.println("{");
output.println(" " + getOutputStreamName() + ".print(str);");
output.println("}");
output.println("protected void println(String str)");
output.println("{");
output.println(" " + getOutputStreamName() + ".println(str);");
output.println("}");
output.println("protected void printIndent()");
output.println("{");
output.println(" for( int i =0; i < indent; i++) {" + getOutputStreamName() + ".print(' ');}");
output.println("}");
}
@Override
protected void emitClassDocComment(final PrintWriter output) {
output.println("/**");
output.println(" * <p>");
output.println(" * Composable pipeline which wraps an underlying {@link GL} implementation,");
output.println(" * providing tracing information to a user-specified {@link java.io.PrintStream}");
output.println(" * before and after each OpenGL method call.");
output.println(" * </p>");
output.println(" * <p>");
output.println(" * Sample code which installs this pipeline:");
output.println(" * <pre>");
output.println(" * gl = drawable.setGL(new TraceGL(drawable.getGL(), System.err));");
output.println(" * </pre>");
output.println(" * For automatic instantiation see {@link GLPipelineFactory#create(String, Class, GL, Object[])}");
output.println(" * </p>");
output.println(" */");
}
@Override
protected boolean hasPreDownstreamCallHook(final Method m) {
return true;
}
@Override
protected void preDownstreamCallHook(final PrintWriter output, final Method m) {
if (m.getName().equals("glEnd") || m.getName().equals("glEndList")) {
output.println(" indent-=2;");
output.println(" printIndent();");
} else {
output.println(" printIndent();");
}
output.print(" print(");
printFunctionCallString(output, m);
output.println(");");
}
@Override
protected boolean hasPostDownstreamCallHook(final Method m) {
return true;
}
@Override
protected void postDownstreamCallHook(final PrintWriter output, final Method m) {
final Class<?> ret = m.getReturnType();
if (ret != Void.TYPE) {
output.println(" println(\" = \"+_res);");
} else {
output.println(" println(\"\");");
}
if (m.getName().equals("glBegin"))
output.println(" indent+=2;");
}
private String getOutputStreamName() {
return "stream";
}
} // end class TracePipeline
public static final void printFunctionCallString(final PrintWriter output, final Method m) {
final Class<?>[] params = m.getParameterTypes();
output.print(" \"" + m.getName() + "(\"");
for (int i = 0; i < params.length; i++) {
output.print("+\"<" + params[i].getName() + ">");
if (params[i].isArray()) {
output.print("\"");
} else if (params[i].equals(int.class)) {
output.print(" 0x\"+Integer.toHexString(arg" + i + ").toUpperCase()");
} else {
output.print(" \"+arg" + i);
}
if (i < params.length - 1) {
output.print("+\", \"");
}
}
output.print("+\")\"");
}
}
|