forked from flipcomputing/flock
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblocks.js
More file actions
1378 lines (1203 loc) · 43 KB
/
blocks.js
File metadata and controls
1378 lines (1203 loc) · 43 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
import * as Blockly from "blockly";
//import "@blockly/block-plus-minus";
import * as BlockDynamicConnection from "@blockly/block-dynamic-connection";
import { toolbox } from "./toolbox.js";
import { getOption, translate } from "/main/translation.js";
import {
deleteMeshFromBlock,
updateOrCreateMeshFromBlock,
getMeshFromBlock,
} from "./ui/blockmesh.js";
import { registerFieldColour } from "@blockly/field-colour";
import { createThemeConfig } from "./main/themes.js";
registerFieldColour();
export let nextVariableIndexes = {};
export const inlineIcon =
"data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%3E%3Csvg%20version%3D%221.1%22%20id%3D%22Layer_1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20x%3D%220px%22%20y%3D%220px%22%20width%3D%22122.88px%22%20height%3D%2280.593px%22%20viewBox%3D%220%200%20122.88%2080.593%22%20enable-background%3D%22new%200%200%20122.88%2080.593%22%20xml%3Aspace%3D%22preserve%22%3E%3Cg%3E%3Cpolygon%20fill%3D%22white%22%20points%3D%22122.88%2C80.593%20122.88%2C49.772%2061.44%2C0%200%2C49.772%200%2C80.593%2061.44%2C30.82%20122.88%2C80.593%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E";
const baseHelpUrl = "https://docs.flockxr.com/blocks/";
export function getHelpUrlFor(blockType) {
//return baseHelpUrl + blockType;
return "https://flockxr.com";
}
// Shared utility to add the toggle button to a block
export function addToggleButton(block) {
const toggleButton = new Blockly.FieldImage(
inlineIcon, // Custom icon
30,
30,
"*", // Width, Height, Alt text
() => {
block.toggleDoBlock();
},
);
block
.appendDummyInput()
.setAlign(Blockly.inputs.Align.RIGHT)
.appendField(toggleButton, "TOGGLE_BUTTON");
}
// Shared utility for the mutationToDom function
export function mutationToDom(block) {
const container = document.createElement("mutation");
container.setAttribute("inline", block.isInline);
return container;
}
// Shared utility for the domToMutation function
export function domToMutation(block, xmlElement) {
const isInline = xmlElement.getAttribute("inline") === "true";
block.updateShape_(isInline);
}
// Shared utility to update the shape of the block
export function updateShape(block, isInline) {
block.isInline = isInline;
if (isInline) {
block.setPreviousStatement(true);
block.setNextStatement(true);
} else {
block.setPreviousStatement(false);
block.setNextStatement(false);
}
}
export function handleBlockSelect(event) {
if (event.type === Blockly.Events.SELECTED) {
const block = Blockly.getMainWorkspace().getBlockById(event.newElementId); // Get the selected block
if (
block &&
block.type !== "create_ground" &&
block.type !== "create_map" &&
(block.type.startsWith("create_") || block.type.startsWith("load_"))
) {
// If the block is a create block, update the window.currentMesh variable
window.updateCurrentMeshName(block, "ID_VAR");
}
}
}
export function handleBlockDelete(event) {
if (event.type === Blockly.Events.BLOCK_DELETE) {
// Recursively delete meshes for qualifying blocks
function deleteMeshesRecursively(blockJson) {
// Check if block type matches the prefixes
if (
blockJson.type.startsWith("load_") ||
blockJson.type.startsWith("create_")
) {
deleteMeshFromBlock(blockJson.id);
}
// Check inputs for child blocks
if (blockJson.inputs) {
for (const key in blockJson.inputs) {
const inputBlock = blockJson.inputs[key].block;
if (inputBlock) {
deleteMeshesRecursively(inputBlock);
}
}
}
// Check 'next' for connected blocks
if (blockJson.next && blockJson.next.block) {
deleteMeshesRecursively(blockJson.next.block);
}
}
// Process the main deleted block and its connections
deleteMeshesRecursively(event.oldJson);
}
}
export function handleMeshLifecycleChange(block, changeEvent) {
const mesh = getMeshFromBlock(block);
if (
changeEvent.type === Blockly.Events.BLOCK_MOVE &&
changeEvent.blockId === block.id
) {
if (block.getParent() && !mesh) {
updateOrCreateMeshFromBlock(block, changeEvent);
}
return true;
}
if (
changeEvent.type === Blockly.Events.BLOCK_CHANGE &&
changeEvent.blockId === block.id &&
changeEvent.element === "disabled"
) {
if (block.isEnabled()) {
setTimeout(() => {
if (block.getParent()) {
updateOrCreateMeshFromBlock(block, changeEvent);
}
}, 0);
} else {
deleteMeshFromBlock(block.id);
}
return true;
}
if (
changeEvent.type === Blockly.Events.BLOCK_CREATE &&
changeEvent.blockId === block.id &&
Blockly.getMainWorkspace().getBlockById(block.id)
) {
if (window.loadingCode) return true;
updateOrCreateMeshFromBlock(block, changeEvent);
return true;
}
return false;
}
export function handleFieldOrChildChange(containerBlock, changeEvent) {
if (
changeEvent.type !== Blockly.Events.BLOCK_CHANGE ||
changeEvent.element !== "field"
)
return false;
const changedBlock = Blockly.getMainWorkspace().getBlockById(
changeEvent.blockId,
);
if (!changedBlock) return false;
// Direct change on container block
if (changedBlock.id === containerBlock.id) {
updateOrCreateMeshFromBlock(containerBlock, changeEvent);
return true;
}
// Change on an unchainable child block
const parent = changedBlock.getParent();
if (parent && parent.id === containerBlock.id) {
if (changedBlock.nextConnection || changedBlock.previousConnection)
return false;
updateOrCreateMeshFromBlock(containerBlock, changeEvent);
return true;
}
return false;
}
export function handleParentLinkedUpdate(containerBlock, changeEvent) {
if (
changeEvent.type !== Blockly.Events.BLOCK_CREATE &&
changeEvent.type !== Blockly.Events.BLOCK_CHANGE
)
return false;
const changed = Blockly.getMainWorkspace().getBlockById(changeEvent.blockId);
const parent = findCreateBlock(changed);
if (parent === containerBlock && changed) {
if (!window.loadingCode) {
updateOrCreateMeshFromBlock(containerBlock, changeEvent);
}
return true;
}
return false;
}
export function findCreateBlock(block) {
if (!block || typeof block.getParent !== "function") {
//console.log("no id");
return null;
}
let parent = block;
while (parent) {
if (parent.type === "scale" || parent.type === "rotate_to") {
// Don't update parent if we're modifying a nested scale or rotate
return null;
}
if (
parent.type.startsWith("create_") ||
parent.type.startsWith("load_") ||
parent.type === "set_sky_color" ||
parent.type === "set_background_color"
) {
return parent;
}
// Move up the hierarchy
parent = parent.getParent();
}
// No matching parent found
return null;
}
// smart-variable-duplication.js (final)
// - Split variable on duplicate (duplicate-parent safe)
// - Retarget descendants oldVar -> newVar
// - Adopt isolated default-looking vars in subtree -> newVar
// - Normalize creator var name to the LOWEST available suffix (fixes “skipped 3”)
// - Recompute nextVariableIndexes[prefix] from workspace state
const _pendingRetarget = new WeakMap(); // block -> { from, to, type, prefix } | undefined
function getBlockly(opts) {
return (opts && opts.Blockly) || (typeof Blockly !== "undefined" ? Blockly : null);
}
function getVariableFieldsOnBlock(block, BlocklyNS) {
const out = [];
for (const input of block.inputList || []) {
for (const field of input.fieldRow || []) {
if (field instanceof BlocklyNS.FieldVariable) out.push(field);
}
}
return out;
}
function isVariableUsedElsewhere(workspace, varId, excludingBlockId, BlocklyNS) {
if (!varId) return false;
const blocks = workspace.getAllBlocks(false);
for (const b of blocks) {
if (b.id === excludingBlockId) continue;
const fields = getVariableFieldsOnBlock(b, BlocklyNS);
for (const f of fields) {
if (f.getValue && f.getValue() === varId) return true;
}
}
return false;
}
function getFieldVariableType(block, fieldName, BlocklyNS) {
const field = block.getField(fieldName);
if (!field) return "";
const model = typeof field.getVariable === "function" ? field.getVariable() : null;
if (model && typeof model.type === "string") return model.type || "";
const varId = field.getValue && field.getValue();
const byId = varId ? block.workspace.getVariableById(varId) : null;
return (byId && byId.type) || "";
}
function parseNumericSuffix(name, prefix) {
if (!name || !name.startsWith(prefix)) return null;
const rest = name.slice(prefix.length);
if (!/^\d+$/.test(rest)) return null;
return parseInt(rest, 10);
}
function createFreshVariable(workspace, prefix, type, nextVariableIndexes) {
// Pick the smallest available suffix >= 1 (not just "next"), to be robust to temp vars.
let n = 1;
while (workspace.getVariable(`${prefix}${n}`, type)) n += 1;
// Also keep your counter roughly in sync (but we’ll normalize later).
nextVariableIndexes[prefix] = Math.max(nextVariableIndexes[prefix] || 1, n + 1);
return workspace.getVariableMap().createVariable(`${prefix}${n}`, type); // VariableModel
}
function retargetDescendantsVariables(rootBlock, fromVarId, toVarId, BlocklyNS) {
if (!fromVarId || !toVarId || fromVarId === toVarId) return 0;
const descendants = rootBlock.getDescendants(false);
let changes = 0;
for (const b of descendants) {
const fields = getVariableFieldsOnBlock(b, BlocklyNS);
for (const f of fields) {
if (f.getValue && f.getValue() === fromVarId) {
f.setValue(toVarId);
changes++;
}
}
}
return changes;
}
function subtreeHasVarId(rootBlock, fromVarId, BlocklyNS) {
const descendants = rootBlock.getDescendants(false);
for (const b of descendants) {
const fields = getVariableFieldsOnBlock(b, BlocklyNS);
for (const f of fields) {
if (f.getValue && f.getValue() === fromVarId) return true;
}
}
return false;
}
function buildDescendantIdSet(rootBlock) {
const set = new Set();
for (const b of rootBlock.getDescendants(false)) set.add(b.id);
return set;
}
function countVarUses(workspace, varId, BlocklyNS) {
let count = 0;
const blocks = workspace.getAllBlocks(false);
for (const b of blocks) {
const fields = getVariableFieldsOnBlock(b, BlocklyNS);
for (const f of fields) {
if (f.getValue && f.getValue() === varId) count++;
}
}
return count;
}
/**
* Adopt single-use "default-looking" variables inside the creator's subtree:
* - type matches
* - name startsWith prefix
* - ALL uses are inside this subtree (none outside)
*/
function adoptIsolatedDefaultVarsTo(rootBlock, toVarId, varType, prefix, workspace, BlocklyNS) {
const descendantIds = buildDescendantIdSet(rootBlock);
let adopted = 0;
for (const b of rootBlock.getDescendants(false)) {
const fields = getVariableFieldsOnBlock(b, BlocklyNS);
for (const f of fields) {
const vid = f.getValue && f.getValue();
if (!vid || vid === toVarId) continue;
const model = workspace.getVariableById(vid);
if (!model) continue;
const typeOk = model.type === varType || !model.type || !varType;
if (!typeOk) continue;
if (!model.name || !model.name.startsWith(prefix)) continue;
// ensure all uses are within subtree
let usedOutside = false;
const allBlocks = workspace.getAllBlocks(false);
for (const bb of allBlocks) {
const fields2 = getVariableFieldsOnBlock(bb, BlocklyNS);
for (const f2 of fields2) {
if (f2.getValue && f2.getValue() === vid) {
if (!descendantIds.has(bb.id)) {
usedOutside = true;
break;
}
}
}
if (usedOutside) break;
}
if (usedOutside) continue;
// adopt
f.setValue(toVarId);
adopted++;
// clean up orphan if now unused
if (countVarUses(workspace, vid, BlocklyNS) === 0) {
try { workspace.deleteVariableById(vid); } catch (_) { /* ignore */ }
}
}
}
return adopted;
}
/** Find the LOWEST available numeric suffix for prefix+N (type-scoped). */
function lowestAvailableSuffix(workspace, prefix, type) {
let n = 1;
while (workspace.getVariable(`${prefix}${n}`, type)) n += 1;
return n;
}
/** Compute the max numeric suffix currently present for prefix (type-scoped). */
function maxExistingSuffix(workspace, prefix, type) {
let max = 0;
const vars = type ? workspace.getVariablesOfType(type) : workspace.getAllVariables();
for (const v of vars) {
const n = parseNumericSuffix(v.name, prefix);
if (n && n > max) max = n;
}
return max;
}
/**
* After adoption, normalize the creator variable's NAME to the LOWEST free suffix.
* Then recompute nextVariableIndexes[prefix] = maxSuffix + 1.
*/
function normalizeVarNameAndIndex(workspace, varId, prefix, type, nextVariableIndexes) {
const model = workspace.getVariableById(varId);
if (!model) return;
const currentSuffix = parseNumericSuffix(model.name, prefix);
const targetSuffix = lowestAvailableSuffix(workspace, prefix, type);
// If our current name isn't the lowest available, and the lowest is different, rename.
if (targetSuffix && targetSuffix !== currentSuffix) {
try {
workspace.getVariableMap().renameVariable(model, `${prefix}${targetSuffix}`);
} catch (_) { /* ignore rename failures */ }
}
const maxSuffix = maxExistingSuffix(workspace, prefix, type);
nextVariableIndexes[prefix] = maxSuffix + 1;
}
/**
* Public entry: call from your existing handleBlockCreateEvent (or in setOnChange).
*/
export function ensureFreshVarOnDuplicate(
block,
changeEvent,
variableNamePrefix,
nextVariableIndexes,
opts = {}
) {
const BlocklyNS = getBlockly(opts);
if (!BlocklyNS) return;
const fieldName = opts.fieldName || "ID_VAR";
// Finish any pending work (retarget, adopt, normalize) from earlier in the same dup group.
const pending = _pendingRetarget.get(block);
if (pending && pending.from && pending.to) {
BlocklyNS.Events.setGroup(changeEvent.group || null);
try {
BlocklyNS.Events.disable();
retargetDescendantsVariables(block, pending.from, pending.to, BlocklyNS);
adoptIsolatedDefaultVarsTo(block, pending.to, pending.type, pending.prefix, block.workspace, BlocklyNS);
normalizeVarNameAndIndex(block.workspace, pending.to, pending.prefix, pending.type, nextVariableIndexes);
if (!subtreeHasVarId(block, pending.from, BlocklyNS)) {
_pendingRetarget.set(block, undefined);
}
} finally {
BlocklyNS.Events.enable();
BlocklyNS.Events.setGroup(false);
}
}
// Only act on *this block's* create event.
if (changeEvent.type !== BlocklyNS.Events.BLOCK_CREATE) return;
if (changeEvent.blockId !== block.id) return;
const ws = block.workspace;
const idField = block.getField(fieldName);
if (!idField) return;
const oldVarId = idField.getValue && idField.getValue();
if (!oldVarId) return;
// Duplicate/copy/duplicate-parent case?
if (!isVariableUsedElsewhere(ws, oldVarId, block.id, BlocklyNS)) return;
const varType = getFieldVariableType(block, fieldName, BlocklyNS);
const group = changeEvent.group || `auto-split-${block.id}-${Date.now()}`;
BlocklyNS.Events.setGroup(group);
try {
BlocklyNS.Events.disable();
// Mint a new var with the *lowest* available suffix now.
const newVarModel = createFreshVariable(ws, variableNamePrefix, varType, nextVariableIndexes);
const newVarId =
newVarModel.id ||
(typeof newVarModel.getId === "function" ? newVarModel.getId() : null);
if (!newVarId) return;
// Point the creator at the fresh variable.
idField.setValue(newVarId);
// Pass 1: retarget descendants old -> new (for those already present)
retargetDescendantsVariables(block, oldVarId, newVarId, BlocklyNS);
// Pass 2: adopt any isolated default-looking vars inside subtree to the new var
adoptIsolatedDefaultVarsTo(block, newVarId, varType, variableNamePrefix, ws, BlocklyNS);
// Normalize the creator var’s name to the LOWEST free suffix (fixes visible gaps)
normalizeVarNameAndIndex(ws, newVarId, variableNamePrefix, varType, nextVariableIndexes);
// If more children will connect later, remember to finish on subsequent events.
_pendingRetarget.set(block, {
from: oldVarId,
to: newVarId,
type: varType,
prefix: variableNamePrefix
});
} finally {
BlocklyNS.Events.enable();
BlocklyNS.Events.setGroup(false);
}
}
/*
export default Blockly.Theme.defineTheme("flock", {
base: Blockly.Themes.Modern,
componentStyles: {
workspaceBackgroundColour: "white",
toolboxBackgroundColour: "#ffffff66",
//'toolboxForegroundColour': '#fff',
//'flyoutBackgroundColour': '#252526',
//'flyoutForegroundColour': '#ccc',
//'flyoutOpacity': 1,
//'scrollbarColour': '#797979',
insertionMarkerColour: "#defd6c",
insertionMarkerOpacity: 0.3,
scrollbarOpacity: 0.4,
cursorColour: "#defd6c",
//'blackBackground': '#333',
},
});
*/
export class CustomConstantProvider extends Blockly.zelos.ConstantProvider {
constructor() {
super();
this.NOTCH_OFFSET_LEFT = 2 * this.GRID_UNIT;
this.NOTCH_HEIGHT = 2 * this.GRID_UNIT;
this.FIELD_DROPDOWN_SVG_ARROW_DATAURI =
"data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMi43MSIgaGVpZ2h0PSI4Ljc5IiB2aWV3Qm94PSIwIDAgMTIuNzEgOC43OSI+PHRpdGxlPmRyb3Bkb3duLWFycm93PC90aXRsZT48ZyBvcGFjaXR5PSIwLjEiPjxwYXRoIGQ9Ik0xMi43MSwyLjQ0QTIuNDEsMi40MSwwLDAsMSwxMiw0LjE2TDguMDgsOC4wOGEyLjQ1LDIuNDUsMCwwLDEtMy40NSwwTDAuNzIsNC4xNkEyLjQyLDIuNDIsMCwwLDEsMCwyLjQ0LDIuNDgsMi40OCwwLDAsMSwuNzEuNzFDMSwwLjQ3LDEuNDMsMCw2LjM2LDBTMTEuNzUsMC40NiwxMiwuNzFBMi40NCwyLjQ0LDAsMCwxLDEyLjcxLDIuNDRaIiBmaWxsPSIjMjMxZjIwIi8+PC9nPjxwYXRoIGQ9Ik02LjM2LDcuNzlhMS40MywxLjQzLDAsMCwxLTEuNDItTDEuNDIsMy40NWExLjQ0LDEuNDQsMCwwLDEsMC0yYzAuNTYtLjU2LDkuMzEtMC41Niw5Ljg3LDBhMS40NCwxLjQ0LDAsMCwxLDAsMkw3LjM3LDcuMzdBMS40MywxLjQzLDAsMCwxLDYuMzYsNy43OVoiIGZpbGw9IiMwMDAiLz48L3N2Zz4=";
}
}
class CustomRenderInfo extends Blockly.zelos.RenderInfo {
constructor(renderer, block) {
super(renderer, block);
}
adjustXPosition_() {}
}
export class CustomZelosRenderer extends Blockly.zelos.Renderer {
constructor(name) {
super(name);
}
// Override the method to return our custom constant provider
makeConstants_() {
return new CustomConstantProvider();
}
// Override the method to return our custom RenderInfo
makeRenderInfo_(block) {
return new CustomRenderInfo(this, block);
}
}
const mediaPath = window.location.pathname.includes("/flock")
? "/flock/blockly/media/" // For GitHub Pages
: "/blockly/media/"; // For local dev
export const options = {
//theme: FlockTheme,
theme: createThemeConfig('light'),
//theme: "flockTheme",
//renderer: "zelos",
renderer: "custom_zelos_renderer",
media: mediaPath,
modalInputs: false,
zoom: {
controls: true,
wheel: false,
startScale: 0.7,
maxScale: 3,
minScale: 0.3,
scaleSpeed: 1.2,
},
move: {
scrollbars: {
horizontal: true,
vertical: true,
},
drag: true,
//dragSurface: false,
wheel: true,
},
toolbox: toolbox,
oneBasedIndex: false,
searchAllBlocks: false,
plugins: {
connectionPreviewer: BlockDynamicConnection.decoratePreviewer(),
},
// Double click the blocks to collapse/expand
// them (A feature from MIT App Inventor).
useDoubleClick: false,
// Bump neighbours after dragging to avoid overlapping.
bumpNeighbours: false,
// Keep the fields of multiple selected same-type blocks with the same value
// See note below.
multiFieldUpdate: true,
// Auto focus the workspace when the mouse enters.
workspaceAutoFocus: true,
// Use custom icon for the multi select controls.
multiselectIcon: {
hideIcon: true,
weight: 3,
enabledIcon:
"https://github.com/mit-cml/workspace-multiselect/raw/main/test/media/select.svg",
disabledIcon:
"https://github.com/mit-cml/workspace-multiselect/raw/main/test/media/unselect.svg",
},
multiSelectKeys: ["Shift"],
multiselectCopyPaste: {
crossTab: true,
menu: true,
},
comments: true,
};
export function initializeVariableIndexes() {
nextVariableIndexes = {
model: 1,
box: 1,
sphere: 1,
cylinder: 1,
capsule: 1,
plane: 1,
wall: 1,
text: 1,
"3dtext": 1,
sound: 1,
character: 1,
object: 1,
instrument: 1,
animation: 1,
clone: 1,
};
const allVariables = Blockly.getMainWorkspace().getVariableMap().getAllVariables(); // Retrieve all variables in the workspace
// Process each type of variable
Object.keys(nextVariableIndexes).forEach(function (type) {
let maxIndex = 0; // To keep track of the highest index used so far
// Regular expression to match variable names like 'type1', 'type2', etc.
const varPattern = new RegExp(`^${type}(\\d+)$`);
allVariables.forEach(function (variable) {
const match = variable.name.match(varPattern);
if (match) {
const currentIndex = parseInt(match[1], 10);
if (currentIndex > maxIndex) {
maxIndex = currentIndex;
}
}
});
nextVariableIndexes[type] = maxIndex + 1;
});
// Optionally return the indexes if needed elsewhere
return nextVariableIndexes;
}
export function defineBlocks() {
//BlockDynamicConnection.overrideOldBlockDefinitions();
//Blockly.Blocks['dynamic_list_create'].minInputs = 1;
// Blockly.Blocks['lists_create_with'] = Blockly.Blocks['dynamic_list_create'];
// Blockly.Blocks['text_join'] = Blockly.Blocks['dynamic_text_join'];
function updateCurrentMeshName(block, variableFieldName) {
const variableName = block.getField(variableFieldName).getText(); // Get the selected variable name
if (variableName) {
window.currentMesh = variableName;
window.currentBlock = block;
}
}
window.updateCurrentMeshName = updateCurrentMeshName;
Blockly.Blocks["create_wall"] = {
init: function () {
const variableNamePrefix = "wall";
let nextVariableName =
variableNamePrefix + nextVariableIndexes[variableNamePrefix]; // Start with "wall1";
this.jsonInit({
type: "create_wall",
message0:
"new wall %1 type %2 colour %3 \n start x %4 z %5 end x %6 z %7 y position %8",
args0: [
{
type: "field_variable",
name: "ID_VAR",
variable: nextVariableName,
},
{
type: "field_dropdown",
name: "WALL_TYPE",
options: [
["solid", "SOLID_WALL"],
["door", "WALL_WITH_DOOR"],
["window", "WALL_WITH_WINDOW"],
["floor/roof", "FLOOR"],
],
},
{
type: "input_value",
name: "COLOR",
check: "Colour",
},
{
type: "input_value",
name: "START_X",
check: "Number",
},
{
type: "input_value",
name: "START_Z",
check: "Number",
},
{
type: "input_value",
name: "END_X",
check: "Number",
},
{
type: "input_value",
name: "END_Z",
check: "Number",
},
{
type: "input_value",
name: "Y_POSITION",
check: "Number",
},
],
inputsInline: true,
previousStatement: null,
nextStatement: null,
colour: categoryColours["Scene"],
tooltip:
"Create a wall with the selected type and color between specified start and end positions.\nKeyword: wall",
});
this.setHelpUrl(getHelpUrlFor(this.type));
this.setOnChange((changeEvent) => {
if (
changeEvent.type === Blockly.Events.BLOCK_CREATE ||
changeEvent.type === Blockly.Events.BLOCK_CHANGE
) {
const blockInWorkspace = Blockly.getMainWorkspace().getBlockById(
this.id,
); // Check if block is in the main workspace
if (blockInWorkspace) {
window.updateCurrentMeshName(this, "ID_VAR"); // Call the function to update window.currentMesh
}
}
handleBlockCreateEvent(
this,
changeEvent,
variableNamePrefix,
nextVariableIndexes,
);
});
},
};
Blockly.Extensions.register("dynamic_mesh_dropdown", function () {
const dropdown = new Blockly.FieldDropdown(function () {
const options = [["everywhere", "__everywhere__"]];
const workspace = this.sourceBlock_ && this.sourceBlock_.workspace;
if (workspace) {
const variables = workspace.getVariableMap().getAllVariables();
variables.forEach((v) => {
options.push([v.name, v.name]);
});
}
return options;
});
// Attach the dropdown to the block
this.getInput("MESH_INPUT").appendField(dropdown, "MESH_NAME");
});
Blockly.Blocks["rotate_camera"] = {
init: function () {
this.jsonInit({
type: "rotate_camera",
message0: "rotate camera by %1 degrees",
args0: [
{
type: "input_value",
name: "DEGREES",
check: "Number",
},
],
inputsInline: true,
previousStatement: null,
nextStatement: null,
colour: categoryColours["Transform"],
tooltip:
"Rotate the camera left or right by the given degrees.\nKeyword: rotate",
});
this.setHelpUrl(getHelpUrlFor(this.type));
},
};
Blockly.Blocks["up"] = {
init: function () {
this.jsonInit({
type: "up",
message0: "up %1 force %2",
args0: [
{
type: "field_variable",
name: "MODEL_VAR",
variable: window.currentMesh,
},
{
type: "input_value",
name: "UP_FORCE",
check: "Number",
},
],
previousStatement: null,
nextStatement: null,
colour: categoryColours["Transform"],
tooltip: "Apply the specified upwards force.\nKeyword: up",
});
this.setHelpUrl(getHelpUrlFor(this.type));
},
};
Blockly.Blocks["random_seeded_int"] = {
init: function () {
this.jsonInit({
type: "random_seeded_int",
message0: "random integer from %1 to %2 seed: %3",
args0: [
{
type: "input_value",
name: "FROM",
check: "Number",
align: "RIGHT",
},
{
type: "input_value",
name: "TO",
check: "Number",
align: "RIGHT",
},
{
type: "input_value",
name: "SEED",
check: "Number",
align: "RIGHT",
},
],
inputsInline: true,
output: "Number",
colour: 230,
tooltip: "Generate a random integer with a seed.\n Keyword: seed",
});
this.setHelpUrl(getHelpUrlFor(this.type));
},
};
Blockly.Blocks["to_number"] = {
init: function () {
this.jsonInit({
type: "to_number",
message0: "convert %1 to %2",
args0: [
{
type: "input_value",
name: "STRING",
check: "String",
},
{
type: "field_dropdown",
name: "TYPE",
options: [
["integer", "INT"],
["float", "FLOAT"],
],
},
],
inputsInline: true,
output: "Number",
colour: 230,
tooltip: "Convert a string to an integer or float.",
});
this.setHelpUrl(getHelpUrlFor(this.type));
},
};
Blockly.Blocks["keyword_block"] = {
init: function () {
this.appendDummyInput().appendField(
new Blockly.FieldTextInput("type a keyword to add a block"),
"KEYWORD",
);
this.setTooltip("Type a keyword to change this block.");
this.setHelpUrl(getHelpUrlFor(this.type));
this.setOnChange(function (changeEvent) {
// Prevent infinite loops or multiple replacements.
if (this.isDisposed() || this.isReplaced) {
return;
}
// Get the entered keyword.
const keyword = this.getFieldValue("KEYWORD").trim();
// Lookup the new block type based on the keyword.
const blockType = findBlockTypeByKeyword(keyword);
if (blockType) {
// Mark the block as replaced.
this.isReplaced = true;
const workspace = this.workspace;
// Create the new block.
const newBlock = workspace.newBlock(blockType);
// Apply toolbox settings if defined.
const blockDefinition = findBlockDefinitionInToolbox(blockType);
if (blockDefinition && blockDefinition.inputs) {
applyToolboxSettings(newBlock, blockDefinition.inputs);
}
newBlock.initSvg();
newBlock.render();
// Position the new block where the old keyword block is.
const pos = this.getRelativeToSurfaceXY();
newBlock.moveBy(pos.x, pos.y);
if (
this.previousConnection &&
this.previousConnection.isConnected()
) {
const parentConnection = this.previousConnection.targetConnection;
if (parentConnection) {
parentConnection.disconnect();
parentConnection.connect(newBlock.previousConnection);
}
}
// Reattach any block that was connected to the keyword block's next connection.
const nextBlock = this.getNextBlock();
if (nextBlock && newBlock.nextConnection) {
newBlock.nextConnection.connect(nextBlock.previousConnection);
}
// Select the new block for immediate editing.
const selectedBlock = Blockly.getSelected();
if (selectedBlock) {
selectedBlock.unselect();
}
newBlock.select();