-
Notifications
You must be signed in to change notification settings - Fork 1
/
HoloPrint.js
1516 lines (1447 loc) · 67.5 KB
/
HoloPrint.js
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 NBT from "https://esm.run/[email protected]";
import JSZip from "https://esm.run/[email protected]";
import BlockGeoMaker from "./BlockGeoMaker.js";
import TextureAtlas from "./TextureAtlas.js";
import MaterialList from "./MaterialList.js";
import PreviewRenderer from "./PreviewRenderer.js";
import { awaitAllEntries, concatenateFiles, JSONMap, JSONSet, max, min, pi, sha256, translate } from "./essential.js";
import ResourcePackStack from "./ResourcePackStack.js";
export const IGNORED_BLOCKS = ["air", "piston_arm_collision", "sticky_piston_arm_collision"]; // blocks to be ignored when scanning the structure file
export const IGNORED_MATERIAL_LIST_BLOCKS = ["bubble_column"]; // blocks that will always be hidden on the material list
const IGNORED_BLOCK_ENTITIES = ["Beacon", "Beehive", "Bell", "BrewingStand", "ChiseledBookshelf", "CommandBlock", "Comparator", "Conduit", "EnchantTable", "EndGateway", "JigsawBlock", "Lodestone", "SculkCatalyst", "SculkShrieker", "SculkSensor", "CalibratedSculkSensor", "StructureBlock", "BrushableBlock", "TrialSpawner", "Vault"];
export const PLAYER_CONTROL_NAMES = {
TOGGLE_RENDERING: "player_controls.toggle_rendering",
CHANGE_OPACITY: "player_controls.change_opacity",
TOGGLE_VALIDATING: "player_controls.toggle_validating",
CHANGE_LAYER: "player_controls.change_layer",
DECREASE_LAYER: "player_controls.decrease_layer",
MOVE_HOLOGRAM: "player_controls.move_hologram",
CHANGE_STRUCTURE: "player_controls.change_structure",
DISABLE_PLAYER_CONTROLS: "player_controls.disable_player_controls"
};
export const DEFAULT_PLAYER_CONTROLS = {
TOGGLE_RENDERING: createItemCriteria("stone"),
CHANGE_OPACITY: createItemCriteria("glass"),
TOGGLE_VALIDATING: createItemCriteria("iron_ingot"),
CHANGE_LAYER: createItemCriteria([], "planks"),
DECREASE_LAYER: createItemCriteria([], "logs"),
MOVE_HOLOGRAM: createItemCriteria("stick"),
CHANGE_STRUCTURE: createItemCriteria("arrow"),
DISABLE_PLAYER_CONTROLS: createItemCriteria("bone")
};
/**
* Makes a HoloPrint resource pack from a structure file.
* @param {File|Array<File>} structureFiles Either a singular structure file (`*.mcstructure`), or an array of structure files
* @param {HoloPrintConfig} [config]
* @param {ResourcePackStack} [resourcePackStack]
* @param {HTMLElement} [previewCont]
* @returns {Promise<File>} Resource pack (`*.mcpack`)
*/
export async function makePack(structureFiles, config = {}, resourcePackStack, previewCont) {
if(!resourcePackStack) {
console.debug("Waiting for resource pack stack initialisation...");
resourcePackStack = await new ResourcePackStack()
console.debug("Resource pack stack initialised!");
}
let startTime = performance.now();
config = addDefaultConfig(config);
if(!Array.isArray(structureFiles)) {
structureFiles = [structureFiles];
}
let nbts = await Promise.all(structureFiles.map(structureFile => readStructureNBT(structureFile)));
console.info("Finished reading structure NBTs!");
console.log("NBTs:", nbts);
let structureSizes = nbts.map(nbt => nbt["size"].map(x => +x)); // Stored as Number instances: https://github.com/Offroaders123/NBTify/issues/50
let packName = config.PACK_NAME ?? getDefaultPackName(structureFiles);
// Make the pack
let loadedStuff = await loadStuff({
packTemplate: {
manifest: "manifest.json",
hologramRenderControllers: "render_controllers/armor_stand.hologram.render_controllers.json",
hologramGeo: "models/entity/armor_stand.hologram.geo.json", // this is where we put all the ghost blocks
hologramMaterial: "materials/entity.material",
hologramAnimationControllers: "animation_controllers/armor_stand.hologram.animation_controllers.json",
hologramAnimations: "animations/armor_stand.hologram.animation.json",
boundingBoxOutlineParticle: "particles/bounding_box_outline.json",
blockValidationParticle: "particles/block_validation.json",
singleWhitePixelTexture: "textures/particle/single_white_pixel.png",
hudScreenUI: "ui/hud_screen.json",
languagesDotJson: "texts/languages.json"
},
resources: {
entityFile: "entity/armor_stand.entity.json",
defaultPlayerRenderControllers: "render_controllers/player.render_controllers.json",
armorStandGeo: "models/entity/armor_stand.geo.json", // for visible bounds. I don't think we need this
translationFile: `texts/${config.MATERIAL_LIST_LANGUAGE}.lang`
},
otherFiles: {
packIcon: config.PACK_ICON_BLOB ?? makePackIcon(concatenateFiles(structureFiles)),
},
data: { // these will not be put into the pack
blockMetadata: "metadata/vanilladata_modules/mojang-blocks.json",
itemMetadata: "metadata/vanilladata_modules/mojang-items.json"
}
}, resourcePackStack);
let { manifest, packIcon, entityFile, hologramRenderControllers, defaultPlayerRenderControllers, hologramGeo, armorStandGeo, hologramMaterial, hologramAnimationControllers, hologramAnimations, boundingBoxOutlineParticle, blockValidationParticle, singleWhitePixelTexture, hudScreenUI, languagesDotJson, translationFile } = loadedStuff.files;
let { blockMetadata, itemMetadata } = loadedStuff.data;
let structures = nbts.map(nbt => nbt["structure"]);
let palettesAndIndices = structures.map(structure => tweakBlockPalette(structure, config.IGNORED_BLOCKS));
let { palette: blockPalette, indices: allStructureIndicesByLayer } = mergeMultiplePalettesAndIndices(palettesAndIndices);
console.log("combined palette: ", blockPalette);
console.log("remapped indices: ", allStructureIndicesByLayer);
window.blockPalette = blockPalette;
window.blockIndices = allStructureIndicesByLayer;
let blockGeoMaker = await new BlockGeoMaker(config);
// makeBoneTemplate() is an impure function and adds texture references to the textureRefs set property.
let boneTemplatePalette = blockPalette.map(block => blockGeoMaker.makeBoneTemplate(block));
console.info("Finished making block geometry templates!");
console.log("Block geo maker:", blockGeoMaker);
console.log("Bone template palette:", structuredClone(boneTemplatePalette));
let textureAtlas = await new TextureAtlas(config, resourcePackStack);
let textureRefs = [...blockGeoMaker.textureRefs];
await textureAtlas.makeAtlas(textureRefs); // each texture reference will get added to the textureUvs array property
let textureBlobs = textureAtlas.imageBlobs;
let defaultTextureIndex = max(textureBlobs.length - 3, 0); // default to 80% opacity
console.log("Texture UVs:", textureAtlas.textures);
boneTemplatePalette.forEach(boneTemplate => {
boneTemplate["cubes"].forEach(cube => {
Object.keys(cube["uv"]).forEach(faceName => {
let face = cube["uv"][faceName];
let imageUv = structuredClone(textureAtlas.textures[face["index"]]);
if(face["flip_horizontally"]) {
imageUv["uv"][0] += imageUv["uv_size"][0];
imageUv["uv_size"][0] *= -1;
}
if(face["flip_vertically"]) {
imageUv["uv"][1] += imageUv["uv_size"][1];
imageUv["uv_size"][1] *= -1;
}
cube["uv"][faceName] = {
"uv": imageUv["uv"],
"uv_size": imageUv["uv_size"]
};
if("crop" in imageUv) {
let crop = imageUv["crop"];
let cropXRem = 1 - crop["w"] - crop["x"]; // remaining horizontal space on the other side of the cropped region
let cropYRem = 1 - crop["h"] - crop["y"];
if(cube["size"][0] == 0) {
cube["origin"][2] += cube["size"][2] * (face["flip_horizontally"]? cropXRem : crop["x"]);
cube["origin"][1] += cube["size"][1] * (face["flip_vertically"]? crop["y"] : cropYRem); // the latter term is the distance from the bottom of the texture, which is upwards direction in 3D space.
cube["size"][2] *= crop["w"];
cube["size"][1] *= crop["h"];
} else if(cube["size"][1] == 0) {
cube["origin"][0] += cube["size"][0] * (face["flip_horizontally"]? cropXRem : crop["x"]);
cube["origin"][2] += cube["size"][2] * (face["flip_vertically"]? cropYRem: crop["y"]);
cube["size"][0] *= crop["w"];
cube["size"][2] *= crop["h"];
} else if(cube["size"][2] == 0) {
cube["origin"][0] += cube["size"][0] * (face["flip_horizontally"]? cropXRem : crop["x"]);
cube["origin"][1] += cube["size"][1] * (face["flip_vertically"]? crop["y"] : cropYRem);
cube["size"][0] *= crop["w"];
cube["size"][1] *= crop["h"];
} else {
console.error("Cannot crop bone template without zero size in one axis:", boneTemplate);
}
}
});
});
});
console.log("Bone template palette with resolved UVs:", boneTemplatePalette);
// I have no idea if these visible bounds actually influence anything...
let visibleBoundsWidth = 16 * max(...structureSizes.map(structureSize => max(structureSize[0], structureSize[2])));
let visibleBoundsHeight = 16 * max(...structureSizes.map(structureSize => structureSize[1]));
armorStandGeo["minecraft:geometry"][0]["description"]["visible_bounds_width"] = visibleBoundsWidth;
armorStandGeo["minecraft:geometry"][0]["description"]["visible_bounds_height"] = visibleBoundsHeight;
let structureGeoTemplate = hologramGeo["minecraft:geometry"][0];
hologramGeo["minecraft:geometry"].splice(0, 1);
structureGeoTemplate["description"]["visible_bounds_width"] = visibleBoundsWidth;
structureGeoTemplate["description"]["visible_bounds_height"] = visibleBoundsHeight;
structureGeoTemplate["description"]["texture_width"] = textureAtlas.atlasWidth;
structureGeoTemplate["description"]["texture_height"] = textureAtlas.atlasHeight;
let structureWMolang = arrayToMolang(structureSizes.map(structureSize => structureSize[0]), "v.structure_index");
let structureHMolang = arrayToMolang(structureSizes.map(structureSize => structureSize[1]), "v.structure_index");
let structureDMolang = arrayToMolang(structureSizes.map(structureSize => structureSize[2]), "v.structure_index");
let makeHologramSpawnAnimation;
if(config.DO_SPAWN_ANIMATION) {
let totalAnimationLength = 0;
makeHologramSpawnAnimation = (x, y, z, structureSize) => {
let delay = config.SPAWN_ANIMATION_LENGTH * 0.25 * (structureSize[0] - x + y + structureSize[2] - z + Math.random() * 2) + 0.05;
delay = Number(delay.toFixed(2));
let animationEnd = Number((delay + config.SPAWN_ANIMATION_LENGTH).toFixed(2));
totalAnimationLength = max(totalAnimationLength, animationEnd);
hologramAnimations["animations"]["animation.armor_stand.hologram.spawn"]["animation_length"] = totalAnimationLength;
return {
"scale": `q.anim_time <= ${delay}? 0 : (q.anim_time >= ${animationEnd}? 1 : (1 - math.pow(1 - (q.anim_time - ${delay}) / ${config.SPAWN_ANIMATION_LENGTH}, 3)))`.replaceAll(" ", "")
};
};
} else {
// Totally empty animation
delete hologramAnimations["animations"]["animation.armor_stand.hologram.spawn"]["loop"];
delete hologramAnimations["animations"]["animation.armor_stand.hologram.spawn"]["bones"];
}
let layerAnimationStates = hologramAnimationControllers["animation_controllers"]["controller.animation.armor_stand.hologram.layers"]["states"];
let topLayer = max(...structureSizes.map(structureSize => structureSize[1])) - 1;
layerAnimationStates["default"]["transitions"].push(
{
"l_0": `v.hologram_layer > -1 && v.hologram_layer != ${topLayer}`
},
{
[`l_${topLayer}`]: `v.hologram_layer == ${topLayer}`
}
);
let entityDescription = entityFile["minecraft:client_entity"]["description"];
let totalBlockCount = 0;
let totalBlocksToValidateByStructure = [];
let uniqueBlocksToValidate = new Set();
let materialList = new MaterialList(blockMetadata, itemMetadata, translationFile);
allStructureIndicesByLayer.forEach((structureIndicesByLayer, structureI) => {
let structureSize = structureSizes[structureI];
let geoShortName = `hologram_${structureI}`;
let geoIdentifier = `geometry.armor_stand.hologram_${structureI}`;
let geo = structuredClone(structureGeoTemplate);
geo["description"]["identifier"] = geoIdentifier;
entityDescription["geometry"][geoShortName] = geoIdentifier;
hologramRenderControllers["render_controllers"]["controller.render.armor_stand.hologram"]["arrays"]["geometries"]["Array.geometries"].push(`Geometry.${geoShortName}`);
let blocksToValidate = [];
for(let y = 0; y < structureSize[1]; y++) {
let layerName = `l_${y}`;
geo["bones"].push({
"name": layerName,
"parent": "hologram_offset_wrapper",
"pivot": [8, 0, -8]
});
layerAnimationStates[layerName] = {
"animations": [`hologram.l_${y}`],
"blend_transition": 0.1,
"blend_via_shortest_path": true,
"transitions": [
{
[y == 0? "default" : `l_${y - 1}`]: `v.hologram_layer < ${y}${y == topLayer? " && v.hologram_layer != -1" : ""}`
},
(y == topLayer? {
"default": "v.hologram_layer == -1"
} : {
[`l_${y + 1}`]: `v.hologram_layer > ${y}`
})
]
};
hologramAnimations["animations"][`animation.armor_stand.hologram.l_${y}`] ??= {};
let layerAnimation = hologramAnimations["animations"][`animation.armor_stand.hologram.l_${y}`];
layerAnimation["loop"] = "hold_on_last_frame";
layerAnimation["bones"] ??= {};
for(let otherLayerY = 0; otherLayerY < structureSize[1]; otherLayerY++) {
if(otherLayerY == y || config.LAYER_MODE == "all_below" && otherLayerY < y) {
continue;
}
layerAnimation["bones"][`l_${otherLayerY}`] = {
"scale": config.MINI_SCALE
};
}
if(Object.entries(layerAnimation["bones"]).length == 0) {
delete layerAnimation["bones"];
}
entityDescription["animations"][`hologram.l_${y}`] = `animation.armor_stand.hologram.l_${y}`;
for(let x = 0; x < structureSize[0]; x++) {
for(let z = 0; z < structureSize[2]; z++) {
let blockI = (x * structureSize[1] + y) * structureSize[2] + z;
let firstBoneForThisBlock = true;
structureIndicesByLayer.forEach((blockPaletteIndices, layerI) => {
let paletteI = blockPaletteIndices[blockI];
if(!(paletteI in boneTemplatePalette)) {
if(paletteI in blockPalette) {
console.error(`A bone template wasn't made for blockPalette[${paletteI}] = ${blockPalette[paletteI]["name"]}!`);
}
return;
}
let boneTemplate = boneTemplatePalette[paletteI];
// console.table({x, y, z, i, paletteI, boneTemplate});
let boneName = `b_${x}_${y}_${z}`;
if(!firstBoneForThisBlock) {
boneName += `_${layerI}`;
}
let bonePos = [-16 * x - 8, 16 * y, 16 * z - 8]; // I got these values from trial and error with blockbench (which makes the x negative I think. it's weird.)
let positionedBoneTemplate = blockGeoMaker.positionBoneTemplate(boneTemplate, bonePos);
let bonesToAdd = [{
"name": boneName,
"parent": layerName,
...positionedBoneTemplate
}];
let rotWrapperBones = new JSONMap();
let extraRotCounter = 0;
bonesToAdd[0]["cubes"] = bonesToAdd[0]["cubes"].filter(cube => {
if("extra_rots" in cube) { // cubes that copy with rotation in both the cube and the copied cube need wrapper bones to handle multiple rotations
let extraRots = cube["extra_rots"];
delete cube["extra_rots"];
if(!rotWrapperBones.has(extraRots)) { // some rotations may be the same, so we use a map to cache the wrapper bone this cube should be added to
let wrapperBones = [];
let parentBoneName = boneName;
extraRots.forEach(extraRot => {
let wrapperBoneName = `${boneName}_rot_wrapper_${extraRotCounter++}`;
wrapperBones.push({
"name": wrapperBoneName,
"parent": parentBoneName,
"rotation": extraRot["rot"],
"pivot": extraRot["pivot"]
});
parentBoneName = wrapperBoneName;
});
bonesToAdd.push(...wrapperBones);
wrapperBones.at(-1)["cubes"] = [];
rotWrapperBones.set(extraRots, wrapperBones.at(-1));
}
rotWrapperBones.get(extraRots)["cubes"].push(cube);
return false;
} else {
return true;
}
});
geo["bones"].push(...bonesToAdd);
if(firstBoneForThisBlock) { // we only need 1 locator for each block position, even though there may be 2 bones in this position because of the 2nd layer
hologramGeo["minecraft:geometry"][2]["bones"][1]["locators"][boneName] ??= bonePos.map(x => x + 8);
}
if(config.DO_SPAWN_ANIMATION) {
hologramAnimations["animations"]["animation.armor_stand.hologram.spawn"]["bones"][boneName] = makeHologramSpawnAnimation(x, y, z, structureSize);
}
let blockName = blockPalette[paletteI]["name"];
if(!config.IGNORED_MATERIAL_LIST_BLOCKS.includes(blockName)) {
materialList.add(blockName);
}
if(layerI == 0) { // particle_expire_if_in_blocks only works on the first layer :(
blocksToValidate.push({
"bone_name": boneName,
"block": blockName,
"pos": [x, y, z]
});
uniqueBlocksToValidate.add(blockName);
}
firstBoneForThisBlock = false;
totalBlockCount++;
});
}
}
}
hologramGeo["minecraft:geometry"].push(geo);
addBoundingBoxParticles(hologramAnimationControllers, structureI, structureSize);
addBlockValidationParticles(hologramAnimationControllers, structureI, blocksToValidate);
totalBlocksToValidateByStructure.push(blocksToValidate.length);
});
entityDescription["materials"]["hologram"] = "holoprint_hologram";
entityDescription["materials"]["hologram.wrong_block_overlay"] = "holoprint_hologram.wrong_block_overlay";
entityDescription["textures"]["hologram.overlay"] = "textures/entity/overlay";
entityDescription["animations"]["hologram.align"] = "animation.armor_stand.hologram.align";
entityDescription["animations"]["hologram.offset"] = "animation.armor_stand.hologram.offset";
entityDescription["animations"]["hologram.spawn"] = "animation.armor_stand.hologram.spawn";
entityDescription["animations"]["hologram.wrong_block_overlay"] = "animation.armor_stand.hologram.wrong_block_overlay";
entityDescription["animations"]["controller.hologram.layers"] = "controller.animation.armor_stand.hologram.layers";
entityDescription["animations"]["controller.hologram.bounding_box"] = "controller.animation.armor_stand.hologram.bounding_box";
entityDescription["animations"]["controller.hologram.block_validation"] = "controller.animation.armor_stand.hologram.block_validation";
entityDescription["scripts"]["animate"] ??= [];
entityDescription["scripts"]["animate"].push("hologram.align", "hologram.offset", "hologram.spawn", "hologram.wrong_block_overlay", "controller.hologram.layers", "controller.hologram.bounding_box", "controller.hologram.block_validation");
entityDescription["scripts"]["initialize"] ??= [];
entityDescription["scripts"]["initialize"].push(functionToMolang((v, structureSize, structureCount) => {
v.hologram_offset_x = 0;
v.hologram_offset_y = 0;
v.hologram_offset_z = 0;
v.structure_w = $[structureSize[0]];
v.structure_h = $[structureSize[1]];
v.structure_d = $[structureSize[2]];
v.render_hologram = true;
v.hologram_texture_index = $[defaultTextureIndex];
v.hologram_layer = -1;
v.validate_hologram = false;
v.show_wrong_block_overlay = false;
v.wrong_blocks = -1;
v.wrong_block_x = 0;
v.wrong_block_y = 0;
v.wrong_block_z = 0;
v.structure_index = 0;
v.structure_count = $[structureCount];
// v.last_held_item = q.get_equipped_item_name ?? "";
v.last_held_item = "";
v.last_hurt_direction = 1;
// v.player_action_counter = t.player_action_counter ?? 0;
v.player_action_counter = 0;
}, { structureSize: structureSizes[0], defaultTextureIndex, structureCount: structureFiles.length }));
entityDescription["scripts"]["pre_animation"] ??= [];
entityDescription["scripts"]["pre_animation"].push(functionToMolang((v, q, t, textureBlobsCount, totalBlocksToValidate, toggleRendering, changeOpacity, toggleValidating, changeLayer, decreaseLayer, disablePlayerControls) => {
v.hologram_dir = Math.floor(q.body_y_rotation / 90) + 2; // [south, west, north, east] (since it goes from -180 to 180)
t.process_action = false; // this is the only place I'm using temp variables for their intended purpose
t.action = "";
t.check_layer_validity = false;
t.changed_structure = false;
if(v.last_held_item != q.get_equipped_item_name) {
v.last_held_item = q.get_equipped_item_name;
t.process_action = true;
}
if(v.last_hurt_direction != q.hurt_direction) { // hitting the armour stand changes this: https://wiki.bedrock.dev/entities/non-mob-runtime-identifiers.html#notable-queries-3
v.last_hurt_direction = q.hurt_direction;
t.process_action = true;
if(!q.is_item_equipped) { // change structure on hit when holding nothing
t.action = "next_structure";
}
}
v.last_pose ??= v.armor_stand.pose_index;
if(v.last_pose != v.armor_stand.pose_index) {
v.last_pose = v.armor_stand.pose_index;
if(v.render_hologram) {
t.action = "increase_layer";
}
}
if(t.process_action) {
if($[toggleRendering]) {
t.action = "toggle_rendering";
} else if($[changeOpacity]) {
t.action = "increase_opacity";
} else if($[toggleValidating]) {
t.action = "toggle_validating";
} else if($[changeLayer]) {
t.action = "increase_layer";
} else if($[decreaseLayer]) {
t.action = "decrease_layer";
} else if(q.is_item_name_any("slot.weapon.mainhand", "minecraft:white_wool")) { // Movement controls (I hate that I'm having to do this)
t.action = "move_y-";
} else if(q.is_item_name_any("slot.weapon.mainhand", "minecraft:red_wool")) {
t.action = "move_y+";
} else if(q.is_item_name_any("slot.weapon.mainhand", "minecraft:orange_wool")) {
t.action = "move_z-";
} else if(q.is_item_name_any("slot.weapon.mainhand", "minecraft:yellow_wool")) {
t.action = "move_z+";
} else if(q.is_item_name_any("slot.weapon.mainhand", "minecraft:lime_wool")) {
t.action = "move_x+";
} else if(q.is_item_name_any("slot.weapon.mainhand", "minecraft:light_blue_wool")) {
t.action = "move_x-";
}
}
t.player_action_counter ??= 0;
if(v.player_action_counter != t.player_action_counter && t.player_action_counter > 0 && t.player_action != "") {
v.player_action_counter = t.player_action_counter;
if(!$[disablePlayerControls]) {
t.action = t.player_action;
}
}
if(t.action != "") {
if(t.action == "toggle_rendering") {
v.render_hologram = !v.render_hologram;
} else if(t.action == "toggle_validating") {
v.validate_hologram = !v.validate_hologram;
if(v.validate_hologram) {
v.wrong_blocks = $[totalBlocksToValidate];
t.wrong_blocks = $[totalBlocksToValidate];
} else {
v.show_wrong_block_overlay = false;
}
} else if(v.render_hologram) { // opacity, layer, movement, and structure controls require the hologram to be visible, otherwise it could be confusing if you accidentally change something when it's invisible
if(t.action == "increase_opacity") {
v.hologram_texture_index++;
if(v.hologram_texture_index >= $[textureBlobsCount]) {
v.hologram_texture_index = 0;
}
} else if(t.action == "decrease_opacity") {
v.hologram_texture_index--;
if(v.hologram_texture_index < 0) {
v.hologram_texture_index = $[textureBlobsCount - 1];
}
} else if(t.action == "increase_layer") {
v.hologram_layer++;
t.check_layer_validity = true;
} else if(t.action == "decrease_layer") {
v.hologram_layer--;
t.check_layer_validity = true;
} else if(t.action == "move_x-") {
v.hologram_offset_x--;
} else if(t.action == "move_x+") {
v.hologram_offset_x++;
} else if(t.action == "move_y-") {
v.hologram_offset_y--;
} else if(t.action == "move_y+") {
v.hologram_offset_y++;
} else if(t.action == "move_z-") {
v.hologram_offset_z--;
} else if(t.action == "move_z+") {
v.hologram_offset_z++;
} else if(t.action == "next_structure" && v.structure_count > 1) {
v.structure_index++;
t.changed_structure = true;
} else if(t.action == "previous_structure" && v.structure_count > 1) {
v.structure_index--;
t.changed_structure = true;
}
}
}
if(t.check_layer_validity) {
if(v.hologram_layer < -1) {
v.hologram_layer = v.structure_h - 1;
}
if(v.hologram_layer >= v.structure_h) {
v.hologram_layer = -1;
}
}
if(t.changed_structure) {
if(v.structure_index < 0) {
v.structure_index = v.structure_count - 1;
}
if(v.structure_index >= v.structure_count) {
v.structure_index = 0;
}
v.structure_w = $[structureWMolang];
v.structure_h = $[structureHMolang];
v.structure_d = $[structureDMolang];
v.hologram_layer = -1;
v.validate_hologram = false;
v.show_wrong_block_overlay = false;
}
if(v.validate_hologram) {
// block validation particles rely on temp variables. this code checks if the temp variables are defined; if they are, it updates the internal state; if not, it sets the temp variables to its internal state. very messy ik
if((t.wrong_blocks ?? -1) == -1) {
t.wrong_blocks = v.wrong_blocks;
} else {
v.wrong_blocks = t.wrong_blocks;
}
if((t.show_wrong_block_overlay ?? -1) == -1) {
t.show_wrong_block_overlay = v.show_wrong_block_overlay;
} else {
v.show_wrong_block_overlay = t.show_wrong_block_overlay;
}
if((t.wrong_block_x ?? -1) == -1) {
t.wrong_block_x = v.wrong_block_x;
} else {
v.wrong_block_x = t.wrong_block_x;
}
if((t.wrong_block_y ?? -1) == -1) {
t.wrong_block_y = v.wrong_block_y;
} else {
v.wrong_block_y = t.wrong_block_y;
}
if((t.wrong_block_z ?? -1) == -1) {
t.wrong_block_z = v.wrong_block_z;
} else {
v.wrong_block_z = t.wrong_block_z;
}
}
}, {
textureBlobsCount: textureBlobs.length,
totalBlocksToValidate: arrayToMolang(totalBlocksToValidateByStructure, "v.structure_index"),
structureWMolang,
structureHMolang,
structureDMolang,
toggleRendering: itemCriteriaToMolang(config.CONTROLS.TOGGLE_RENDERING),
changeOpacity: itemCriteriaToMolang(config.CONTROLS.CHANGE_OPACITY),
toggleValidating: itemCriteriaToMolang(config.CONTROLS.TOGGLE_VALIDATING),
changeLayer: itemCriteriaToMolang(config.CONTROLS.CHANGE_LAYER),
decreaseLayer: itemCriteriaToMolang(config.CONTROLS.DECREASE_LAYER),
disablePlayerControls: itemCriteriaToMolang(config.CONTROLS.DISABLE_PLAYER_CONTROLS)
}));
entityDescription["geometry"]["hologram.wrong_block_overlay"] = "geometry.armor_stand.hologram.wrong_block_overlay";
entityDescription["geometry"]["hologram.valid_structure_overlay"] = "geometry.armor_stand.hologram.valid_structure_overlay";
entityDescription["geometry"]["hologram.particle_alignment"] = "geometry.armor_stand.hologram.particle_alignment";
entityDescription["render_controllers"] ??= [];
entityDescription["render_controllers"].push({
"controller.render.armor_stand.hologram": "v.render_hologram"
}, {
"controller.render.armor_stand.hologram.wrong_block_overlay": "v.show_wrong_block_overlay"
}, {
"controller.render.armor_stand.hologram.valid_structure_overlay": "v.validate_hologram && v.wrong_blocks == 0"
}, "controller.render.armor_stand.hologram.particle_alignment");
entityDescription["particle_effects"] ??= {};
entityDescription["particle_effects"]["bounding_box_outline"] = "holoprint:bounding_box_outline";
textureBlobs.forEach(([textureName]) => {
entityDescription["textures"][textureName] = `textures/entity/${textureName}`;
hologramRenderControllers["render_controllers"]["controller.render.armor_stand.hologram"]["arrays"]["textures"]["Array.textures"].push(`Texture.${textureName}`);
});
hologramRenderControllers["render_controllers"]["controller.render.armor_stand.hologram"]["textures"][0] = `Array.textures[v.hologram_texture_index ?? ${defaultTextureIndex}]`;
if(config.TINT != undefined) {
// By putting the overlay in the render controller instead of modifying the texture, the overlay isn't applied on transparent pixels. It also saves us the work of having to manipulate the image data directly :)
hologramRenderControllers["render_controllers"]["controller.render.armor_stand.hologram"]["overlay_color"] = {
"r": config.TINT[0],
"g": config.TINT[1],
"b": config.TINT[2],
"a": config.TINT[3]
};
}
let overlayTexture = await singleWhitePixelTexture.setOpacity(config.WRONG_BLOCK_OVERLAY_COLOR[3]);
let totalMaterialCount = materialList.totalMaterialCount;
// add the particles' short names, and then reference them in the animation controller
uniqueBlocksToValidate.forEach(blockName => {
let particleName = `validate_${blockName.replace(":", ".")}`;
entityDescription["particle_effects"][particleName] = `holoprint:${particleName}`;
});
let playerRenderControllers = addPlayerControlsToRenderControllers(config, defaultPlayerRenderControllers);
console.log("Block counts map:", materialList.materials);
let finalisedMaterialList = materialList.export();
console.log("Finalised material list:", finalisedMaterialList);
// console.log(partitionedBlockCounts);
let missingItemAux = blockMetadata["data_items"].find(block => block.name == "minecraft:reserved6")["raw_id"];
hudScreenUI["material_list_entries"]["controls"].push(...finalisedMaterialList.map(({ translationKey, partitionedCount, auxId }, i) => ({
[`material_list_${i}@hud.material_list_entry`]: {
"$item_translation_key": translationKey,
"$item_count": partitionedCount,
"$item_id_aux": auxId ?? missingItemAux,
"$background_opacity": i % 2 * 0.2
}
})));
hudScreenUI["material_list"]["size"][1] = finalisedMaterialList.length * 12 + 12; // 12px for each item + 12px for the heading
manifest["header"]["uuid"] = crypto.randomUUID();
manifest["modules"][0]["uuid"] = crypto.randomUUID();
if(config.AUTHORS.length) {
manifest["metadata"]["authors"].push(...config.AUTHORS);
}
let inGameControls;
if(JSON.stringify(config.CONTROLS) != JSON.stringify(DEFAULT_PLAYER_CONTROLS)) { // add controls to pack description only if they've been changed
// make a fake material list for the in-game control items
let controlsMaterialList = new MaterialList(blockMetadata, itemMetadata, translationFile);
inGameControls = "";
for(let [control, itemCriteria] of Object.entries(config.CONTROLS)) {
itemCriteria["names"].forEach(itemName => controlsMaterialList.addItem(itemName));
let itemInfo = controlsMaterialList.export();
controlsMaterialList.clear();
inGameControls += `\n${await translate(PLAYER_CONTROL_NAMES[control], "en")}: ${[itemInfo.map(item => `§3${item.translatedName}§r`).join(", "), itemCriteria.tags.map(tag => `§p${tag}§r`).join(", ")].removeFalsies().join("; ")}`;
}
}
let packGenerationTime = (new Date()).toLocaleString();
let languageFiles = await Promise.all(languagesDotJson.map(async language => {
let languageFile = (await fetch(`packTemplate/texts/${language}.lang`).then(res => res.text())).replaceAll("\r\n", "\n"); // I hate windows sometimes (actually quite often now because of windows 11)
languageFile = languageFile.replaceAll("{PACK_NAME}", packName);
languageFile = languageFile.replaceAll("{PACK_GENERATION_TIME}", packGenerationTime);
languageFile = languageFile.replaceAll(/\{STRUCTURE_AUTHORS\[([^)]+)\]\}/g, (useless, delimiter) => config.AUTHORS.join(delimiter));
languageFile = languageFile.replaceAll("{DESCRIPTION}", config.DESCRIPTION?.replaceAll("\n", "\\n"));
languageFile = languageFile.replaceAll("{CONTROLS}", inGameControls?.replaceAll("\n", "\\n"));
languageFile = languageFile.replaceAll("{TOTAL_MATERIAL_COUNT}", totalMaterialCount);
languageFile = languageFile.replaceAll("{MATERIAL_LIST}", finalisedMaterialList.map(({ translatedName, count }) => `${count} ${translatedName}`).join(", "));
// now substitute in the extra bits into the main description if needed
languageFile = languageFile.replaceAll("{AUTHORS_SECTION}", config.AUTHORS.length? languageFile.match(/pack\.description\.authors=([^\t#\n]+)/)[1] : "");
languageFile = languageFile.replaceAll("{DESCRIPTION_SECTION}", config.DESCRIPTION? languageFile.match(/pack\.description\.description=([^\t#\n]+)/)[1] : "");
languageFile = languageFile.replaceAll("{CONTROLS_SECTION}", inGameControls? languageFile.match(/pack\.description\.controls=([^\t#\n]+)/)[1] : "");
languageFile = languageFile.replaceAll(/pack\.description\..+\s*/g, ""); // remove all the description sections
return [language, languageFile];
}));
console.info("Finished making all pack files!");
let pack = new JSZip();
if(structureFiles.length == 1) {
pack.file(".mcstructure", structureFiles[0], {
comment: structureFiles[0].name
});
} else {
structureFiles.forEach((structureFile, i) => {
pack.file(`${i}.mcstructure`, structureFile, {
comment: structureFile.name
});
});
}
pack.file("manifest.json", JSON.stringify(manifest));
pack.file("pack_icon.png", packIcon);
pack.file("entity/armor_stand.entity.json", JSON.stringify(entityFile));
pack.file("render_controllers/armor_stand.hologram.render_controllers.json", JSON.stringify(hologramRenderControllers));
pack.file("render_controllers/player.render_controllers.json", JSON.stringify(playerRenderControllers));
pack.file("models/entity/armor_stand.geo.json", JSON.stringify(armorStandGeo));
pack.file("models/entity/armor_stand.hologram.geo.json", stringifyWithFixedDecimals(hologramGeo));
pack.file("materials/entity.material", JSON.stringify(hologramMaterial));
pack.file("animation_controllers/armor_stand.hologram.animation_controllers.json", JSON.stringify(hologramAnimationControllers));
pack.file("particles/bounding_box_outline.json", JSON.stringify(boundingBoxOutlineParticle));
uniqueBlocksToValidate.forEach(blockName => {
let particleName = `validate_${blockName.replace(":", ".")}`; // file names can't have : in them
let particle = structuredClone(blockValidationParticle);
particle["particle_effect"]["description"]["identifier"] = `holoprint:${particleName}`;
particle["particle_effect"]["components"]["minecraft:particle_expire_if_in_blocks"] = [blockName.includes(":")? blockName : `minecraft:${blockName}`]; // add back minecraft: namespace if it's missing
pack.file(`particles/${particleName}.json`, JSON.stringify(particle));
});
pack.file("textures/particle/single_white_pixel.png", await singleWhitePixelTexture.toBlob());
pack.file("textures/entity/overlay.png", await overlayTexture.toBlob());
pack.file("animations/armor_stand.hologram.animation.json", JSON.stringify(hologramAnimations));
textureBlobs.forEach(([textureName, blob]) => {
pack.file(`textures/entity/${textureName}.png`, blob);
});
pack.file("ui/hud_screen.json", JSON.stringify(hudScreenUI));
pack.file("texts/languages.json", JSON.stringify(languagesDotJson));
languageFiles.forEach(([language, languageFile]) => {
pack.file(`texts/${language}.lang`, languageFile);
});
let zippedPack = await pack.generateAsync({
type: "blob",
compression: "DEFLATE",
compressionOptions: {
level: 9 // too much???
}
});
console.info(`Finished creating pack in ${(performance.now() - startTime).toFixed(0) / 1000}s!`);
if(previewCont) {
let showPreview = () => {
hologramGeo["minecraft:geometry"].filter(geo => geo["description"]["identifier"].startsWith("geometry.armor_stand.hologram_")).map(geo => {
(new PreviewRenderer(previewCont, textureAtlas, geo, hologramAnimations, config.SHOW_PREVIEW_SKYBOX)).catch(e => console.error("Preview renderer error:", e)); // is async but we won't wait for it
});
};
if(totalBlockCount < config.PREVIEW_BLOCK_LIMIT) {
showPreview();
} else {
let message = document.createElement("div");
message.classList.add("previewMessage", "clickToView");
let p = document.createElement("p");
p.dataset.translationSubstitutions = JSON.stringify({
"{TOTAL_BLOCK_COUNT}": totalBlockCount
});
p.dataset.translate = "preview.click_to_view";
message.appendChild(p);
message.onEvent("click", () => {
message.remove();
showPreview();
});
previewCont.appendChild(message);
}
}
return new File([zippedPack], `${packName}.holoprint.mcpack`);
}
/**
* Retrieves the structure files from a completed HoloPrint resource pack.
* @param {File} resourcePack HoloPrint resource pack (`*.mcpack)
* @returns {Promise<Array<File>>}
*/
export async function extractStructureFilesFromPack(resourcePack) {
let packFolder = await JSZip.loadAsync(resourcePack);
let structureZipObjects = Object.values(packFolder.files).filter(file => file.name.endsWith(".mcstructure"));
let structureBlobs = await Promise.all(structureZipObjects.map(async zipObject => await zipObject.async("blob")));
let packName = resourcePack.name.slice(0, resourcePack.name.indexOf("."));
if(structureBlobs.length == 1) {
return [new File([structureBlobs[0]], structureZipObjects[0].comment ?? `${packName}.mcstructure`)];
} else {
return await Promise.all(structureBlobs.map(async (structureBlob, i) => new File([structureBlob], structureZipObjects[i].comment ?? `${packName}_${i}.mcstructure`)));
}
}
/**
* Updates a HoloPrint resource pack by remaking it.
* @param {File} resourcePack HoloPrint resource pack to update (`*.mcpack`)
* @param {HoloPrintConfig} [config]
* @param {ResourcePackStack} [resourcePackStack]
* @param {HTMLElement} [previewCont]
* @returns {Promise<File>}
*/
export async function updatePack(resourcePack, config, resourcePackStack, previewCont) {
let structureFiles = extractStructureFilesFromPack(resourcePack);
if(!structureFiles) {
throw new Error(`No structure files found inside resource pack ${resourcePack.name}; cannot update pack!`);
}
return await makePack(structureFiles, config, resourcePackStack, previewCont);
}
/**
* Returns the default pack name that would be used if no pack name is specified.
* @param {Array<File>} structureFiles
* @returns {String}
*/
export function getDefaultPackName(structureFiles) {
let defaultName = structureFiles.map(structureFile => structureFile.name.replace(/(\.holoprint)?\.[^.]+$/, "")).join(", ");
if(defaultName.length > 40) {
defaultName = `${defaultName.slice(0, 19)}...${defaultName.slice(-19)}`
}
return defaultName;
}
/**
* Creates an ItemCriteria from arrays of names and tags.
* @param {String|Array<String>} names
* @param {String|Array<String>} [tags]
* @returns {ItemCriteria}
*/
export function createItemCriteria(names, tags = []) { // IDK why I haven't made this a class
if(!Array.isArray(names)) {
names = [names];
}
if(!Array.isArray(tags)) {
tags = [tags];
}
return { names, tags };
}
/**
* Adds default config options to a potentially incomplete config object.
* @param {HoloPrintConfig} config
* @returns {HoloPrintConfig}
*/
function addDefaultConfig(config) {
return Object.freeze({
...{ // defaults
IGNORED_BLOCKS: [],
IGNORED_MATERIAL_LIST_BLOCKS: [],
SCALE: 0.95,
OPACITY: 0.9,
MULTIPLE_OPACITIES: true,
// TINT = [0.53, 0.81, 0.98, 0.2], // to convert rgba to these, type 0x__ / 255 into any JS console
TINT: undefined,
MINI_SCALE: 0.125, // size of ghost blocks when in the mini view for layers
LAYER_MODE: "single", // single | all_below
TEXTURE_OUTLINE_WIDTH: 0.25, // pixels, x ∈ [0, 1], x ∈ 2^ℝ
TEXTURE_OUTLINE_COLOR: "#00F9",
TEXTURE_OUTLINE_ALPHA_DIFFERENCE_MODE: "threshold", // difference: will compare alpha channel difference; threshold: will only look at the second pixel
TEXTURE_OUTLINE_ALPHA_THRESHOLD: 0, // if using difference mode, will draw outline between pixels with at least this much alpha difference; else, will draw outline on pixels next to pixels with an alpha less than or equal to this
DO_SPAWN_ANIMATION: true,
SPAWN_ANIMATION_LENGTH: 0.4, // in seconds
WRONG_BLOCK_OVERLAY_COLOR: [1, 0, 0, 0.3],
CONTROLS: {},
MATERIAL_LIST_LANGUAGE: "en_US",
PACK_NAME: undefined,
PACK_ICON_BLOB: undefined,
AUTHORS: [],
DESCRIPTION: undefined,
PREVIEW_BLOCK_LIMIT: 1000,
SHOW_PREVIEW_SKYBOX: true
},
...config,
...{ // overrides (applied after)
IGNORED_BLOCKS: IGNORED_BLOCKS.concat(config.IGNORED_BLOCKS ?? []),
IGNORED_MATERIAL_LIST_BLOCKS: IGNORED_MATERIAL_LIST_BLOCKS.concat(config.IGNORED_MATERIAL_LIST_BLOCKS ?? []),
CONTROLS: {
...DEFAULT_PLAYER_CONTROLS,
...config.CONTROLS
}
}
});
}
/**
* Reads the NBT of a structure file, returning a JSON object.
* @param {File} structureFile `*.mcstructure`
* @returns {Promise<Object>}
*/
async function readStructureNBT(structureFile) {
let arrayBuffer = await structureFile.arrayBuffer().catch(e => { throw new Error(`Could not read bytes of structure file ${structureFile.name}!\n${e}`); });
let nbt = await NBT.read(arrayBuffer).catch(e => { throw new Error(`Could not parse NBT of structure file ${structureFile.name}!\n${e}`); });
return nbt.data;
}
/**
* Loads many files from different sources.
* @param {Object} stuff
* @param {ResourcePackStack} resourcePackStack
* @returns {Promise<Object>}
*/
async function loadStuff(stuff, resourcePackStack) {
let filePromises = {};
Object.entries(stuff.packTemplate).forEach(([name, path]) => {
filePromises[name] = getResponseContents(fetch(`packTemplate/${path}`));
});
Object.entries(stuff.resources).forEach(([name, path]) => {
filePromises[name] = getResponseContents(resourcePackStack.fetchResource(path));
});
Object.assign(filePromises, stuff.otherFiles);
let dataPromises = {};
Object.entries(stuff.data).forEach(([name, path]) => {
dataPromises[name] = getResponseContents(resourcePackStack.fetchData(path));
});
return await awaitAllEntries({
files: awaitAllEntries(filePromises),
data: awaitAllEntries(dataPromises)
});
}
/**
* Gets the contents of a response based on the requested file extension (e.g. object from .json, image from .png, etc.).
* @param {Promise<Response>} resPromise
* @returns {Promise<String|Blob|Object|HTMLImageElement>}
*/
async function getResponseContents(resPromise) {
let res = await resPromise;
if(res.status >= 400) {
throw new Error(`HTTP error ${res.status} for ${res.url}`);
}
let fileExtension = res.url.slice(res.url.lastIndexOf(".") + 1);
switch(fileExtension) {
case "json":
case "material": return await res.jsonc();
case "lang": return await res.text();
case "png": return await res.toImage();
}
return await res.blob();
}
/**
* Removes ignored blocks from the block palette, and adds block entities as separate entries.
* @param {Object} structure The de-NBT-ed structure file
* @returns {{ palette: Array<Block>, indices: [Array<Number>, Array<Number>] }}
*/
function tweakBlockPalette(structure, ignoredBlocks) {
let palette = structuredClone(structure["palette"]["default"]["block_palette"]);
let blockVersions = new Set(); // version should be constant for all blocks. just wanted to test this
palette.forEach((block, i) => {
block["name"] = block["name"].replace(/^minecraft:/, ""); // remove namespace here, right at the start
blockVersions.add(+block["version"]);
if(ignoredBlocks.includes(block["name"])) {
delete palette[i];
return;
}
delete block["version"];
if(!Object.keys(block["states"]).length) {
delete block["states"]; // easier viewing
}
});
console.log("Block versions:", [...blockVersions], [...blockVersions].map(v => v.toString(16).padStart(8, 0).match(/.{2}/g).map(x => parseInt(x, 16)).join(".")));
// add block entities into the block palette (on layer 0)
let indices = structure["block_indices"].map(layer => structuredClone(layer).map(i => +i));
let newIndexCache = new Map();
let entitylessBlockEntityIndices = new Set(); // contains all the block palette indices for blocks with block entities. since they don't have block entity data yet, and all block entities well be cloned and added to the end of the palette, we can remove all the entries in here from the palette.
let blockPositionData = structure["palette"]["default"]["block_position_data"];
for(let i in blockPositionData) {
let oldPaletteI = indices[0][i];
if(!(oldPaletteI in palette)) { // if the block is ignored, it will be deleted already, so there's no need to touch its block entities
continue;
}
if(!("block_entity_data" in blockPositionData[i])) { // observers have tick_queue_data
continue;
}
let blockEntityData = structuredClone(blockPositionData[i]["block_entity_data"]);
if(IGNORED_BLOCK_ENTITIES.includes(blockEntityData["id"])) {
continue;
}
delete blockEntityData["x"];
delete blockEntityData["y"];
delete blockEntityData["z"];
// clone the old block and add the block entity data
let newBlock = structuredClone(palette[oldPaletteI]);
newBlock["block_entity_data"] = blockEntityData;
let stringifiedNewBlock = JSON.stringify(newBlock, (_, x) => typeof x == "bigint"? x.toString() : x);
// check that we haven't seen this block entity before. since in JS objects are compared by reference we have to stringify it first then check the cache.
if(newIndexCache.has(stringifiedNewBlock)) {
indices[0][i] = newIndexCache.get(stringifiedNewBlock);
} else {
let paletteI = palette.length;
palette[paletteI] = newBlock;
indices[0][i] = paletteI;
newIndexCache.set(stringifiedNewBlock, paletteI);
entitylessBlockEntityIndices.add(oldPaletteI); // we can schedule to delete the original block palette entry later, as it doesn't have any block entity data and all block entities clone it.
}
}
for(let paletteI of entitylessBlockEntityIndices) {
// console.log(`deleting entityless block entity ${paletteI} = ${JSON.stringify(blockPalette[paletteI])}`);
delete palette[paletteI]; // this makes the blockPalette array discontinuous; when using native array methods, they skip over the empty slots.
}
return { palette, indices };
}
/**
* Combines multiple block palettes into one, and updates indices for each.
* @param {Array<{palette: Array<Block>, indices: Array<[Number, Number]>}>} palettesAndIndices
* @returns {{palette: Array<Block>, indices: Array<Array<[Number, Number]>>}}
*/
function mergeMultiplePalettesAndIndices(palettesAndIndices) {
if(palettesAndIndices.length == 1) {
return {
palette: palettesAndIndices[0].palette,
indices: [palettesAndIndices[0].indices]
};
}
let mergedPaletteSet = new JSONSet();
let remappedIndices = [];
palettesAndIndices.forEach(({ palette, indices }) => {
let indexRemappings = [];
palette.forEach((block, i) => {
mergedPaletteSet.add(block);
indexRemappings[i] = mergedPaletteSet.indexOf(block);
});
remappedIndices.push(indices.map(layer => layer.map(i => indexRemappings[i] ?? -1)));
});
return {
palette: [...mergedPaletteSet],
indices: remappedIndices
};
}
/**
* Adds bounding box particles for a single structure to the hologram animation controllers in-place.
* @param {Object} hologramAnimationControllers
* @param {Number} structureI
* @param {Vec3} structureSize
*/
function addBoundingBoxParticles(hologramAnimationControllers, structureI, structureSize) {
let outlineParticleSettings = [