-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsketchpad.pde
2878 lines (2283 loc) · 87.4 KB
/
sketchpad.pde
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
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileSystemView;
public class Sketchpad extends Screen {
class AutomationBar {
public float myHeight = 100f;
public float LABEL_HEIGHT = 28f;
public float SELECTION_BOX_WIDTH = 200f;
float TOP_Y = 0f;
float BOTTOM_Y = 0f;
float LEFT_X = 0f;
float RIGHT_X = 0f;
public String name = "Automation bar";
protected color mycolor = color(255, 198, 75);
public boolean snapping = true;
public boolean beatsVisible = false;
public AutomationBar(String name) {
this.name = name;
}
public AutomationBar() {
}
public float getHeight() {
return myHeight+LABEL_HEIGHT;
}
public void resizeTime() {
}
private boolean resizing = false;
public boolean display(float yFromBottom) {
BOTTOM_Y = HEIGHT-myLowerBarWeight;
TOP_Y = BOTTOM_Y-yFromBottom-getHeight();
RIGHT_X = middle();
float y = TOP_Y;
boolean mouseInPane = (input.mouseX() > 0f && input.mouseX() < RIGHT_X-2 && input.mouseY() > y && input.mouseY() < y+myHeight+LABEL_HEIGHT);
app.stroke(200);
app.strokeWeight(2f);
app.fill(60);
app.rect(0f, y, RIGHT_X-2, myHeight+LABEL_HEIGHT);
app.line(0f, y+LABEL_HEIGHT, RIGHT_X, y+LABEL_HEIGHT);
app.fill(255);
app.textAlign(LEFT, TOP);
app.textSize(LABEL_HEIGHT-10f);
app.text(name, 5, y+5);
app.text(nf(getFloatVal(time), 0, 3), RIGHT_X*0.4f, y+5);
boolean colorpickerClicked = ui.buttonImg("nothing", RIGHT_X*0.5f, y, LABEL_HEIGHT, LABEL_HEIGHT);
app.fill(mycolor);
app.noStroke();
app.rect(RIGHT_X*0.5f+2f, y+2f, LABEL_HEIGHT-4f, LABEL_HEIGHT-4f);
if (colorpickerClicked) {
Runnable r = new Runnable() {
public void run() {
mycolor = ui.getPickedColor();
save();
}
};
ui.colorPicker(RIGHT_X*0.5f+LABEL_HEIGHT, y+LABEL_HEIGHT, r);
}
// Snapping button
if (snapping) app.tint(255);
else app.tint(127);
boolean snaptoClicked = ui.buttonImg("snapto_64", RIGHT_X*0.5f+LABEL_HEIGHT+10f, y, LABEL_HEIGHT, LABEL_HEIGHT);
app.noTint();
if (snaptoClicked) {
snapping = !snapping;
if (snapping) sound.playSound("select_bigger");
else sound.playSound("select_smaller");
save();
}
// Show music bars button
if (beatsVisible) app.tint(255);
else app.tint(127);
boolean beatsClicked = ui.buttonImg("music", RIGHT_X*0.5f+(LABEL_HEIGHT+10f)*2f, y, LABEL_HEIGHT, LABEL_HEIGHT);
app.noTint();
if (beatsClicked) {
beatsVisible = !beatsVisible;
if (beatsVisible) sound.playSound("select_bigger");
else sound.playSound("select_smaller");
save();
}
// Resizer
boolean resizerClicked = ui.buttonImg("dragger_64", RIGHT_X-(LABEL_HEIGHT+10f)*2f, y, LABEL_HEIGHT, LABEL_HEIGHT);
if (resizerClicked) {
resizing = true;
}
if (resizing) {
myHeight = max(BOTTOM_Y-input.mouseY()-yFromBottom-LABEL_HEIGHT/2f, 30f);
if (!input.primaryDown) {
resizing = false;
save();
}
}
// Cross button
boolean crossClicked = ui.buttonImg("cross", RIGHT_X-LABEL_HEIGHT-5f, y, LABEL_HEIGHT, LABEL_HEIGHT);
if (crossClicked) {
sound.playSound("select_smaller");
displayAutomationBars.remove(this);
save();
}
display.clip(0f, y+LABEL_HEIGHT, RIGHT_X, myHeight);
app.noStroke();
//app.fill(0, 127);
//app.rect(5, 5, SELECTION_BOX_WIDTH, LABEL_HEIGHT-10f);
prev_x = 0f;
TOP_Y += LABEL_HEIGHT;
if (beatsVisible) {
renderBeats();
}
renderData();
display.noClip();
return mouseInPane;
}
public float getFloatVal(float ttime) {
return engine.noise(ttime*0.1);
}
private float prev_x = 0f;
protected float plotLine(float normalizedX, boolean showVal) {
float TOTAL_WIDTH = timeLength*autoBarsZoom;
float tt = time/timeLength;
float offX = (RIGHT_X/2f)-tt*TOTAL_WIDTH;
float x = (normalizedX)*TOTAL_WIDTH;
float posToTime_prev = (prev_x/TOTAL_WIDTH)*timeLength;
float posToTime = (x/TOTAL_WIDTH)*timeLength;
float prev_y = TOP_Y+myHeight*(1f-getFloatVal(posToTime_prev));
float y = TOP_Y+myHeight*(1f-getFloatVal(posToTime));
float actualPrevX = prev_x+offX;
float actualX = x+offX;
prev_x = x;
if ((actualPrevX > RIGHT_X && actualX > RIGHT_X) || (actualPrevX < 0f && actualX < 0f)) {
return actualX;
}
app.line(actualPrevX, prev_y, actualX, y);
if (showVal) {
app.textSize(10);
app.textAlign(CENTER, TOP);
app.text(getFloatVal(posToTime), x+offX, y-19f);
}
return actualX;
}
protected float plotLine(float normalizedX) {
return plotLine(normalizedX, false);
}
protected void save() {
}
protected float screenXToTime(float x) {
float TOTAL_WIDTH = timeLength*autoBarsZoom;
float tt = time/timeLength;
float offX = (RIGHT_X/2f)-tt*TOTAL_WIDTH;
float val = (x-offX)/TOTAL_WIDTH;
float xx = val*timeLength;
return xx;
}
protected float normalizedXToScreenX(float normalizedX) {
float TOTAL_WIDTH = timeLength*autoBarsZoom;
float tt = time/timeLength;
float offX = (RIGHT_X/2f)-tt*TOTAL_WIDTH;
float x = (normalizedX)*TOTAL_WIDTH;
float actualX = x+offX;
return actualX;
}
protected float closestBeatSnap = -1f;
protected float BEATSNAP_THRESHOLD = 10f;
protected void renderBeats() {
app.stroke(30, 180);
app.strokeWeight(2f);
closestBeatSnap = -1f;
int l = (int)(timeLength/sound.framesPerBeat())+1;
for (int i = 0; i < l; i++) {
float x = normalizedXToScreenX((sound.framesPerBeat()*float(i))/timeLength);
if (input.mouseX() > x-BEATSNAP_THRESHOLD && input.mouseX() < x+BEATSNAP_THRESHOLD) {
closestBeatSnap = screenXToTime(x);
}
app.line(x, TOP_Y, x, BOTTOM_Y);
}
}
protected void renderData() {
app.stroke(mycolor);
app.strokeWeight(2f);
app.noFill();
float MAX = 1000f;
for (float i = 0; i < MAX; i++) {
plotLine((i)/MAX);
}
app.stroke(255, 127);
app.line(RIGHT_X/2f, TOP_Y, RIGHT_X/2f, BOTTOM_Y);
}
}
class LerpAutomationBar extends AutomationBar {
class Point {
public Point(float t, float val) {
this.t = t;
this.val = val;
}
float t = 0f;
float val = 0f;
//public Point addPoint(float t, float val) {
// Point newPoint = new Point(t, val);
// next = newPoint;
// return newPoint;
//}
}
ArrayList<Point> points = new ArrayList<Point>();
public LerpAutomationBar(JSONObject json) {
super();
load(json);
}
public LerpAutomationBar(String name) {
super(name);
save();
}
@Override
public float getFloatVal(float ttime) {
return getFloatVal(ttime, false);
}
public float getVal() {
return getFloatVal(time, false);
}
// Simply brings the last point to the end of the animation.
@Override
public void resizeTime() {
// Delete all points in shortening timelength.
// (Except the last point)
ArrayList<Point> pointsToDelete = new ArrayList<Point>();
for (int i = 0; i < points.size(); i++) {
if (points.get(i).t > timeLength && i != points.size()-1) {
pointsToDelete.add(points.get(i));
}
}
for (Point p : pointsToDelete) {
points.remove(p);
}
// Move last point to the new time position
if (points.size() > 0) {
points.get(points.size()-1).t = timeLength;
}
}
// How to find the index with an arbritrary float value?
// Do it the lazy way cus I can't be bothered with a big algorithm.
// Select an approximate point and then backtrace until we find a point between our float val.
public float getFloatVal(float ttime, boolean countiterations) {
// Calc approx
int l = points.size();
int index = min((int)((ttime/timeLength)*((float)l)), l-1);
if (ttime >= timeLength-0.02) {
return points.get(l-1).val;
}
try {
int count = 0;
while (index > 0 && points.get(index).t > ttime) {
count++;
index--;
}
while (index < l-2 && points.get(index+1).t < ttime) {
count++;
index++;
}
Point lowerPoint = points.get(index);
Point higherPoint = points.get(index+1);
float timerange = higherPoint.t-lowerPoint.t;
float t = ttime-lowerPoint.t;
float percentage = t/timerange;
if (countiterations) {
console.log(count);
}
return PApplet.lerp(lowerPoint.val, higherPoint.val, percentage);
}
catch (IndexOutOfBoundsException e) {
//console.warn("EXCEPTION");
return 0f;
}
}
private boolean lineRect(float x1, float y1, float x2, float y2, float rx, float ry, float rw, float rh) {
// check if the line has hit any of the rectangle's sides
// uses the Line/Line function below
boolean left = lineLine(x1,y1,x2,y2, rx,ry,rx, ry+rh);
boolean right = lineLine(x1,y1,x2,y2, rx+rw,ry, rx+rw,ry+rh);
boolean top = lineLine(x1,y1,x2,y2, rx,ry, rx+rw,ry);
boolean bottom = lineLine(x1,y1,x2,y2, rx,ry+rh, rx+rw,ry+rh);
// if ANY of the above are true, the line
// has hit the rectangle
if (left || right || top || bottom) {
return true;
}
return false;
}
// LINE/LINE
private boolean lineLine(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) {
// calculate the direction of the lines
float uA = ((x4-x3)*(y1-y3) - (y4-y3)*(x1-x3)) / ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1));
float uB = ((x2-x1)*(y1-y3) - (y2-y1)*(x1-x3)) / ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1));
// if uA and uB are between 0-1, lines are colliding
if (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1) {
return true;
}
return false;
}
AtomicBoolean saving = new AtomicBoolean(false);
@Override
public void save() {
if (saving.get()) {
// If already saving don't bother.
// Ideally we should put the thread into a waiting state
// until saving goes false but cant be bothered.
return;
}
JSONArray jsonarr = new JSONArray();
JSONObject barjson = new JSONObject();
for (int i = 0; i < points.size(); i++) {
Point p = points.get(i);
JSONObject jsonpoint = new JSONObject();
jsonpoint.setFloat("val", p.val);
jsonpoint.setFloat("t", p.t);
jsonarr.setJSONObject(i, jsonpoint);
}
barjson.setString("name", name);
barjson.setString("type", "LerpAutomationBar");
barjson.setFloat("height", myHeight);
barjson.setInt("color", mycolor);
barjson.setBoolean("snapping", snapping);
barjson.setBoolean("beats_visible", beatsVisible);
barjson.setBoolean("in_view", displayAutomationBars.contains(this));
barjson.setJSONArray("data", jsonarr);
Thread t = new Thread(new Runnable() {
public void run() {
// Ensure autobars path exists
file.mkdir(sketchiePath+"autobars/");
app.saveJSONObject(barjson, sketchiePath+"autobars/"+name+".json");
saving.set(false);
}
}
);
saving.set(true);
t.start();
}
public void load(JSONObject json) {
this.name = json.getString("name");
this.mycolor = json.getInt("color", color(0,0,0));
this.snapping = json.getBoolean("snapping", false);
this.beatsVisible = json.getBoolean("beats_visible", false);
this.myHeight = json.getFloat("height", 100f);
if (json.getBoolean("in_view", false)) {
displayAutomationBars.add(this);
}
JSONArray jsonarr = json.getJSONArray("data");
if (jsonarr == null) {
console.warn("Autobar "+name+" file is missing data array.");
return;
}
int l = jsonarr.size();
for (int i = 0; i < l; i++) {
JSONObject obj = jsonarr.getJSONObject(i);
if (obj != null) {
points.add(new Point(obj.getFloat("t"), obj.getFloat("val")));
}
}
}
// Can't be bothered commenting so long story short...
// - We move our mouse int to the point
// - Point glows indicating its clickable
// - We try moving the point
// - Point becomes deselected as our mouse is outside of the clicking bounds of the point cus we moved it too fast
// - We rage
// solution: good ol' keeping track of shiz.
private int draggingIndex = -1;
private int hoverLineIndex = -1;
private boolean unsnapDragX = false;
private boolean unsnapDragY = false;
protected void renderData() {
app.strokeWeight(2f);
app.textSize(10);
app.textAlign(CENTER, TOP);
final float RECTWIHI = 12f;
final float HALFWIHI = RECTWIHI/2f;
final float UNSNAP_THRESHOLD = 20f;
final float VAL_SNAP_THRESHOLD = 0.05f;
if (!input.primaryDown && draggingIndex != -1) {
draggingIndex = -1;
save();
}
// Must have at least 2 points
if (points.size() == 0) {
points.add(new Point(0f, 0.5f));
points.add(new Point(timeLength, 0.5f));
}
float lineSelectorX = input.mouseX()-RECTWIHI;
float lineSelectorY = input.mouseY()-RECTWIHI;
int pointIndexForDeletion = -1;
int createPointAtIndex = -1;
int l = points.size();
float prevActualX = 0f, prevActualY = 0f;
for (int i = 0; i < l; i++) {
app.fill(255);
app.strokeWeight(2f);
if (hoverLineIndex == i) {
app.stroke(255);
hoverLineIndex = -1;
}
else {
app.stroke(mycolor);
}
Point point = points.get(i);
float x = plotLine(point.t/timeLength, true);
float actualX = x-HALFWIHI;
float actualY = TOP_Y+(1f-point.val)*myHeight-HALFWIHI;
//if (actualX > RIGHT_X+200f || actualX < 0f) {
// continue;
//}
if (input.mouseX() > actualX && input.mouseX() < actualX+RECTWIHI && input.mouseY() > actualY && input.mouseY() < actualY+RECTWIHI && !playing) {
app.fill(255);
hoverLineIndex = -1;
if (input.primaryOnce) {
draggingIndex = i;
unsnapDragX = false;
unsnapDragY = false;
}
if (input.secondaryOnce) {
pointIndexForDeletion = i;
}
}
else if (lineRect(actualX, actualY, prevActualX, prevActualY, lineSelectorX, lineSelectorY, RECTWIHI, RECTWIHI) && !playing) {
hoverLineIndex = i;
app.fill(mycolor);
if (input.secondaryOnce) {
createPointAtIndex = i;
}
}
else {
app.fill(mycolor);
}
if (draggingIndex == i) {
app.fill(255);
// Update point to new position.
// Unsnapping mechanism so that we can adjust one axis without affecting the other.
// Both for x/y
// No unsnapping for Y
//if (!unsnapDragY) {
// if (input.mouseY() > actualY + UNSNAP_THRESHOLD || input.mouseY() < actualY - UNSNAP_THRESHOLD) {
// unsnapDragY = true;
// point.val = min(max(1f-(input.mouseY()-TOP_Y)/myHeight, 0f), 1f);
// }
//}
//else {
float vv = min(max(1f-(input.mouseY()-TOP_Y)/myHeight, 0f), 1f);
float nextval = timeLength;
float prevval = -1;
if (i-1 >= 0) {
prevval = points.get(i-1).val;
}
if (i+1 < points.size()) {
nextval = points.get(i+1).val;
}
point.val = vv;
if (snapping) {
// Point behind
app.strokeWeight(1f);
app.stroke(255, 127);
if (i-1 >= 0) {
if (vv < prevval+VAL_SNAP_THRESHOLD && vv > prevval-VAL_SNAP_THRESHOLD) {
point.val = prevval;
app.line(0, actualY+HALFWIHI, RIGHT_X, actualY+HALFWIHI);
}
}
// Point behind
if (i+1 < points.size()) {
if (vv < nextval+VAL_SNAP_THRESHOLD && vv > nextval-VAL_SNAP_THRESHOLD) {
point.val = nextval;
app.line(0, actualY+HALFWIHI, RIGHT_X, actualY+HALFWIHI);
}
}
}
//}
// X pos
// No dragging for start and end points of the entire line.
if (i != 0 && i != points.size()-1) {
if (!unsnapDragX) {
if (input.mouseX() > actualX + UNSNAP_THRESHOLD || input.mouseX() < actualX - UNSNAP_THRESHOLD) {
unsnapDragX = true;
point.t = screenXToTime(input.mouseX());
}
}
else {
// Limit dragging x pos to next and prev point's position.
float MICRO_OFFSET = 0.025;
float minx = 0f;
float maxx = timeLength;
if (i-1 >= 0) {
minx = points.get(i-1).t+MICRO_OFFSET;
}
if (i+1 < points.size()) {
maxx = points.get(i+1).t-MICRO_OFFSET;
}
point.t = min(max(screenXToTime(input.mouseX()), minx), maxx);
if (snapping && beatsVisible && closestBeatSnap > 0f
&& vv < prevval+VAL_SNAP_THRESHOLD && vv > prevval-VAL_SNAP_THRESHOLD
&& vv < nextval+VAL_SNAP_THRESHOLD && vv > nextval-VAL_SNAP_THRESHOLD
) {
point.t = closestBeatSnap;
}
}
}
}
app.noStroke();
app.rect(actualX, actualY, RECTWIHI, RECTWIHI);
prevActualX = actualX;
prevActualY = actualY;
}
// Do not allow deletion of index 0 or the last index.
if (pointIndexForDeletion > 0 && points.size() > 2 && pointIndexForDeletion != points.size()-1) {
points.remove(pointIndexForDeletion);
pointIndexForDeletion = -1;
save();
}
else if (createPointAtIndex != -1) {
points.add(createPointAtIndex, new Point(screenXToTime(input.mouseX()), min(max(1f-(input.mouseY()-TOP_Y)/myHeight, 0f), 1f)));
createPointAtIndex = -1;
save();
}
// For performance testing
//getFloatVal(time, true);
app.stroke(255, 127);
app.line(RIGHT_X/2f, TOP_Y, RIGHT_X/2f, BOTTOM_Y);
}
}
private String sketchiePath = "";
private TWEngine.PluginModule.Plugin plugin;
private FFmpegEngine ffmpeg;
private String code = "";
private AtomicBoolean compiling = new AtomicBoolean(false);
private AtomicBoolean successful = new AtomicBoolean(false);
private AtomicBoolean once = new AtomicBoolean(true);
private SpriteSystemPlaceholder sprites;
private SpriteSystemPlaceholder gui;
private PGraphics canvas;
private float canvasScale = 1.0;
private float canvasX = 0.0;
private float canvasY = 0.0;
private float canvasPaneScroll = 0.;
private float codePaneScroll = 0.;
private ArrayList<String> imagesInSketch = new ArrayList<String>(); // This is so that we can know what to remove when we exit this screen.
private ArrayList<PImage> loadedImages = new ArrayList<PImage>();
private JSONObject configJSON = null;
private AtomicBoolean loading = new AtomicBoolean(true);
private AtomicInteger processAfterLoadingIndex = new AtomicInteger(0);
private float textAreaZoom = 22.0;
private boolean configMenu = false;
private boolean renderMenu = false;
private boolean errorMenu = false;
private boolean automationBarSelectMenu = false;
private String errorLog = "";
private float errorHeight = 0f;
private int canvasSmooth = 1;
private String renderFormat = "MPEG-4";
private float upscalePixels = 1.;
private boolean rendering = false;
private boolean converting = false;
private int timeBeforeStartingRender = 0;
private PGraphics shaderCanvas;
private PGraphics scaleCanvas;
private int renderFrameCount = 0;
private float renderFramerate = 0.;
//private float musicVolume = 0.5;
private String[] musicFiles = new String[0];
private String[] loadedShaders = new String[0];
private String selectedMusic = "";
private String selectedShader = "";
public Object[] shaderParams = null;
private boolean playing = false;
private boolean loop = false;
private float time = 0f;
private float timeLength = 10f*60f;
private float bpm = 120f;
// Canvas
private float beginDragX = 0.;
private float beginDragY = 0.;
private float prevCanvasX = 0.;
private float prevCanvasY = 0.;
private boolean isDragging = false;
// Selected pane
private int selectedPane = 0;
private int lastSelectedPane = 0; // Mostly just so I can use the space bar.
final static int CANVAS_PANE = 1;
final static int CODE_PANE = 2;
final static int TIMELINE_PANE = 3;
final static int AUTOBAR_PANE = 4;
private final int MAX_DISPLAY_AUTOMATION_BARS = 8;
private HashMap<String, AutomationBar> automationBars = new HashMap<String, AutomationBar>();
private ArrayList<AutomationBar> displayAutomationBars = new ArrayList<AutomationBar>();
private String[] defaultCode = {
"public void start() {",
" ",
"}",
"",
"public void run() {",
" g.background(120, 100, 140);",
" ",
"}"
};
public Sketchpad(TWEngine engine, String path) {
this(engine);
loadSketchieInSeperateThread(path);
}
public Sketchpad(TWEngine engine) {
super(engine);
myUpperBarWeight = 100.;
gui = new SpriteSystemPlaceholder(engine, engine.APPPATH+engine.PATH_SPRITES_ATTRIB()+"gui/sketchpad/");
gui.interactable = false;
plugin = plugins.createPlugin();
createCanvas(1024, 1024, 1);
resetView();
canvasY = myUpperBarWeight;
input.keyboardMessage = "";
code = "";
// Load default code into keyboardMessage
for (String s : defaultCode) {
code += s+"\n";
}
ffmpeg = new FFmpegEngine();
lastSelectedPane = CODE_PANE;
//sound.streamMusic(engine.APPPATH+"engine/music/test.mp3");
}
//{
// if (file.exists(engine.APPPATH+engine.CACHE_PATH)) {
// File[] cacheFolder = (new File(engine.APPPATH+engine.CACHE_PATH)).listFiles();
// for (File f : cacheFolder) {
// console.log(file.getExt(f.getName()));
// if (file.getExt(f.getName()).equals("jar")) {
// f.delete();
// }
// }
// }
//}
////////////////////////////////////////////////////
// SETUP AND LOADING
private void createCanvas(int wi, int hi, int smooth) {
//console.log("CANVAS "+wi+" "+hi);
canvas = createGraphics(wi, hi, P2D);
if (smooth == 0) {
// Nearest neighbour (hey remember this ancient line of code?)
((PGraphicsOpenGL)canvas).textureSampling(2);
}
else {
canvas.smooth(smooth);
}
shaderCanvas = createGraphics(canvas.width, canvas.height, P2D);
((PGraphicsOpenGL)shaderCanvas).textureSampling(2); // Disable texture smoothing
plugin.sketchioGraphics = canvas;
}
private void loadSketchieInSeperateThread(String path) {
loading.set(true);
processAfterLoadingIndex.set(0);
Thread t1 = new Thread(new Runnable() {
public void run() {
loadSketchie(path);
loading.set(false);
}
});
t1.start();
}
// NOTE: there isn't an equivalent "saveSketchie" method because we don't have
// to save the whole thing:
// - sprite data is saved automatically by the sprite class
// - images... well, I don't think they need to be saved.
// - config is saved when we click "confirm"
// - autobars are saved as they're modified
private void saveScripts() {
// Not gonna bother putting a TODO but you know that the script isn't going to stick to
// a keyboard forever.
String[] strs = new String[1];
strs[0] = code;
file.backupMove(sketchiePath+"scripts/main.java");
app.saveStrings(sketchiePath+"scripts/main.java", strs);
console.log("Saved.");
}
private void saveConfig() {
JSONObject json = new JSONObject();
json.setInt("canvas_width", canvas.width);
json.setInt("canvas_height", canvas.height);
json.setInt("smooth", canvasSmooth);
json.setFloat("time_length", timeLength);
json.setString("music_file", selectedMusic);
json.setBoolean("show_code_editor", codeEditorShown);
json.setFloat("bpm", bpm);
json.setBoolean("loop", loop);
json.setString("shader", selectedShader);
app.saveJSONObject(json, sketchiePath+"sketch_config.json");
}
private void loadConfig() {
if (file.exists(sketchiePath+"sketch_config.json")) {
configJSON = app.loadJSONObject(sketchiePath+"sketch_config.json");
// Need to load the canvas from a seperate thread
// But while we're here, now's a good time to set the music file.
// and timelength cus why not.
timeLength = configJSON.getFloat("time_length", 10.0);
selectedMusic = configJSON.getString("music_file", "");
codeEditorShown = configJSON.getBoolean("show_code_editor", true);
bpm = configJSON.getFloat("bpm", 120f);
sound.setBPM(bpm);
loop = configJSON.getBoolean("loop", false);
selectedShader = configJSON.getString("shader", "");
}
}
private void loadAutobars() {
if (file.exists(sketchiePath+"autobars/")) {
File ff = new File(sketchiePath+"autobars/");
File[] files = ff.listFiles();
for (File f : files) {
try {
JSONObject json = app.loadJSONObject(f.getAbsolutePath());
if (json == null) {
console.warn("Failed to load autobar "+f.getAbsolutePath()+": null");
continue;
}
String name = json.getString("name", "null");
String type = json.getString("type", "null");
if (type.equals("LerpAutomationBar")) {
automationBars.put(name, new LerpAutomationBar(json));
}
}
catch (RuntimeException e) {
console.warn("Failed to load autobar "+f.getAbsolutePath()+": "+e.getMessage());
}
}
}
}
// TODO: only loads one script
private String loadScript() {
String scriptPath = "";
String ccode = "";
if (file.exists(sketchiePath+"scripts")) scriptPath = sketchiePath+"scripts/";
if (file.exists(sketchiePath+"script")) scriptPath = sketchiePath+"script/";
// If scripts exist.
if (scriptPath.length() > 0) {
File[] scripts = (new File(scriptPath)).listFiles();
for (File f : scripts) {
String scriptAbsolutePath = f.getAbsolutePath();
if (file.getExt(scriptAbsolutePath).equals("java")) {
String[] lines = app.loadStrings(scriptAbsolutePath);
ccode = "";
for (String s : lines) {
ccode += s+"\n";
}
// Big TODO here: we're just gonna load one script for now
// until I get things working.
break;
}
}
}
else {
// Script doesn't exist: return default code instead
for (String s : defaultCode) {
ccode += s+"\n";
}
}
//println(" ---------------------- CODE: ----------------------");
//println(ccode);
return ccode;
}
private void loadSketchie(String path) {
// Just in case the thread is still running
terminateFileUpdateThread();
imagesInSketch.clear();
loadedImages.clear();
processAfterLoadingIndex.set(0);
// Undirectorify path
if (path.charAt(path.length()-1) == '/') {
path.substring(0, path.length()-1);
}
if (!file.getExt(path).equals(engine.SKETCHIO_EXTENSION) || !file.isDirectory(path)) {
console.warn("Not a valid sketchie file: "+path);
return;
}
// Re-directorify path
path = file.directorify(path);
sketchiePath = path;
//////////////////
// IMAGES
// Load images
String imgPath = "";
if (file.exists(path+"imgs")) imgPath = path+"imgs";
if (file.exists(path+"img")) imgPath = path+"img";
// Only if imgs folder exists
if (imgPath.length() > 0) {
// List out all the files, get each image.
File[] imgs = (new File(imgPath)).listFiles();
int numberImages = 0;
for (File f : imgs) {
if (f == null) continue;
String pathToSingularImage = f.getAbsolutePath().replaceAll("\\\\", "/");
String name = file.getIsolatedFilename(pathToSingularImage);
// Only load images
if (!file.isImage(pathToSingularImage)) {
continue;
}
// Actual loading (you'll want to run loadSketchie in a seperate thread);
PImage img = loadImage(pathToSingularImage);
// Error checking
if (img == null) {
console.warn("Error while loading image "+name);
continue;
}