-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathHoloPrint.js
1571 lines (1503 loc) · 74.9 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 "nbtify";
import { ZipWriter, TextReader, BlobWriter, BlobReader, ZipReader } from "@zip.js/zip.js";
import BlockGeoMaker from "./BlockGeoMaker.js";
import TextureAtlas from "./TextureAtlas.js";
import MaterialList from "./MaterialList.js";
import PreviewRenderer from "./PreviewRenderer.js";
import * as entityScripts from "./entityScripts.molang.js";
import { awaitAllEntries, concatenateFiles, createEnum, exp, floor, hexColorToClampedTriplet, JSONMap, JSONSet, max, min, pi, round, sha256, translate } from "./essential.js";
import ResourcePackStack from "./ResourcePackStack.js";
import BlockUpdater from "./BlockUpdater.js";
const VERSION = "dev";
export const IGNORED_BLOCKS = ["air", "piston_arm_collision", "sticky_piston_arm_collision"]; // blocks to be ignored when scanning the structure file
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_TINT: "player_controls.toggle_tint",
TOGGLE_VALIDATING: "player_controls.toggle_validating",
CHANGE_LAYER: "player_controls.change_layer",
DECREASE_LAYER: "player_controls.decrease_layer",
CHANGE_LAYER_MODE: "player_controls.change_layer_mode",
MOVE_HOLOGRAM: "player_controls.move_hologram",
ROTATE_HOLOGRAM: "player_controls.rotate_hologram",
CHANGE_STRUCTURE: "player_controls.change_structure",
DISABLE_PLAYER_CONTROLS: "player_controls.disable_player_controls",
BACKUP_HOLOGRAM: "player_controls.backup_hologram"
};
export const DEFAULT_PLAYER_CONTROLS = {
TOGGLE_RENDERING: createItemCriteria("brick"),
CHANGE_OPACITY: createItemCriteria("amethyst_shard"),
TOGGLE_TINT: createItemCriteria("white_dye"),
TOGGLE_VALIDATING: createItemCriteria("iron_ingot"),
CHANGE_LAYER: createItemCriteria("leather"),
DECREASE_LAYER: createItemCriteria("feather"),
CHANGE_LAYER_MODE: createItemCriteria("flint"),
MOVE_HOLOGRAM: createItemCriteria("stick"),
ROTATE_HOLOGRAM: createItemCriteria("copper_ingot"),
CHANGE_STRUCTURE: createItemCriteria("arrow"),
DISABLE_PLAYER_CONTROLS: createItemCriteria("bone"),
BACKUP_HOLOGRAM: createItemCriteria("paper")
};
const HOLOGRAM_LAYER_MODES = createEnum(["SINGLE", "ALL_BELOW"]);
/**
* 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) {
console.info(`Running HoloPrint ${VERSION}`);
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",
savingBackupParticle: "particles/saving_backup.json",
singleWhitePixelTexture: "textures/particle/single_white_pixel.png",
exclamationMarkTexture: "textures/particle/exclamation_mark.png",
saveIconTexture: "textures/particle/save_icon.png",
hudScreenUI: "ui/hud_screen.json",
customEmojiFont: "font/glyph_E2.png",
languagesDotJson: "texts/languages.json"
},
resources: {
entityFile: "entity/armor_stand.entity.json",
defaultPlayerRenderControllers: "render_controllers/player.render_controllers.json",
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, hologramMaterial, hologramAnimationControllers, hologramAnimations, boundingBoxOutlineParticle, blockValidationParticle, savingBackupParticle, singleWhitePixelTexture, exclamationMarkTexture, saveIconTexture, hudScreenUI, customEmojiFont, languagesDotJson, translationFile } = loadedStuff.files;
let { blockMetadata, itemMetadata } = loadedStuff.data;
let structures = nbts.map(nbt => nbt["structure"]);
let palettesAndIndices = await Promise.all(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);
let structureGeoTemplate = hologramGeo["minecraft:geometry"][0];
hologramGeo["minecraft:geometry"].splice(0, 1);
structureGeoTemplate["description"]["texture_width"] = textureAtlas.atlasWidth;
structureGeoTemplate["description"]["texture_height"] = textureAtlas.atlasHeight;
let structureWMolang = arrayToMolang(structureSizes.map(structureSize => structureSize[0]), "v.hologram.structure_index");
let structureHMolang = arrayToMolang(structureSizes.map(structureSize => structureSize[1]), "v.hologram.structure_index");
let structureDMolang = arrayToMolang(structureSizes.map(structureSize => structureSize[2]), "v.hologram.structure_index");
if(!config.DO_SPAWN_ANIMATION) {
// 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} && v.hologram.layer_mode == ${HOLOGRAM_LAYER_MODES.SINGLE}`
},
{
[`l_${topLayer}`]: `v.hologram.layer == ${topLayer} && v.hologram.layer_mode == ${HOLOGRAM_LAYER_MODES.SINGLE}`
}
);
if(topLayer > 0) {
layerAnimationStates["default"]["transitions"].push(
{
"l_0-": `v.hologram.layer > -1 && v.hologram.layer != ${topLayer - 1} && v.hologram.layer_mode == ${HOLOGRAM_LAYER_MODES.ALL_BELOW}`
},
{
[`l_${topLayer - 1}-`]: `v.hologram.layer == ${topLayer - 1} && v.hologram.layer_mode == ${HOLOGRAM_LAYER_MODES.ALL_BELOW}`
}
);
}
let entityDescription = entityFile["minecraft:client_entity"]["description"];
let totalBlockCount = 0;
let totalBlocksToValidateByStructure = [];
let totalBlocksToValidateByStructureByLayer = [];
let uniqueBlocksToValidate = new Set();
let materialList = await 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 = [];
let blocksToValidateByLayer = [];
let getSpawnAnimationDelay;
let animationTimingFunc;
let makeHologramSpawnAnimation;
let spawnAnimationAnimatedBones = [];
if(config.DO_SPAWN_ANIMATION) {
let totalVolume = structureSize.reduce((a, b) => a * b);
let totalAnimationLength = 0;
getSpawnAnimationDelay = (x, y, z) => {
let randomness = 2 - 1.9 * exp(-0.005 * totalVolume); // 100 -> ~0.85, 1000 -> ~1.99, asymptotic to 2
return config.SPAWN_ANIMATION_LENGTH * 0.25 * (structureSize[0] - x + y + structureSize[2] - z + Math.random() * randomness);
};
animationTimingFunc = x => 1 - (1 - x) ** 3;
makeHologramSpawnAnimation = (delay, bonePos) => {
let animationEnd = Number((delay + config.SPAWN_ANIMATION_LENGTH).toFixed(2));
totalAnimationLength = max(totalAnimationLength, animationEnd);
hologramAnimations["animations"]["animation.armor_stand.hologram.spawn"]["animation_length"] = totalAnimationLength;
let keyframes = [0, 0.2, 0.4, 0.6, 0.8, 1]; // this is smooth enough
let positionOffset = [-bonePos[0] - 8, -bonePos[1], -bonePos[2] - 8];
let createAnimFromKeyframes = timingFunc => Object.fromEntries(keyframes.map(keyframe => [`${+(delay + keyframe * config.SPAWN_ANIMATION_LENGTH).toFixed(2)}`, timingFunc(keyframe)]));
return {
"scale": createAnimFromKeyframes(keyframe => (new Array(3)).fill(+animationTimingFunc(keyframe).toFixed(2))), // has to be an array here...
"position": createAnimFromKeyframes(keyframe => positionOffset.map(x => +(x * (1 - animationTimingFunc(keyframe))).toFixed(2)))
};
};
}
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 == topLayer? "default" : `${layerName}-`]: `v.hologram.layer_mode == ${HOLOGRAM_LAYER_MODES.ALL_BELOW}`
},
{
[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) {
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}`;
if(y < topLayer) { // top layer with all layers below is the default view, so the animation + animation controller state doesn't need to be made for it
layerAnimationStates[`${layerName}-`] = {
"animations": [`hologram.l_${y}-`],
"blend_transition": 0.1,
"blend_via_shortest_path": true,
"transitions": [
{
[layerName]: `v.hologram.layer_mode == ${HOLOGRAM_LAYER_MODES.SINGLE}`
},
{
[y == 0? "default" : `l_${y - 1}-`]: `v.hologram.layer < ${y}${y == topLayer - 1? " && v.hologram.layer != -1" : ""}`
},
(y >= topLayer - 1? {
"default": "v.hologram.layer == -1"
} : {
[`l_${y + 1}-`]: `v.hologram.layer > ${y}`
})
]
};
hologramAnimations["animations"][`animation.armor_stand.hologram.l_${y}-`] ??= {};
let layerAnimationAllBelow = hologramAnimations["animations"][`animation.armor_stand.hologram.l_${y}-`];
layerAnimationAllBelow["loop"] = "hold_on_last_frame";
layerAnimationAllBelow["bones"] ??= {};
for(let otherLayerY = 0; otherLayerY < structureSize[1]; otherLayerY++) {
if(otherLayerY <= y) {
continue;
}
layerAnimationAllBelow["bones"][`l_${otherLayerY}`] = {
"scale": config.MINI_SCALE
};
}
if(Object.entries(layerAnimationAllBelow["bones"]).length == 0) {
delete layerAnimationAllBelow["bones"];
}
entityDescription["animations"][`hologram.l_${y}-`] = `animation.armor_stand.hologram.l_${y}-`;
}
let blocksToValidateCurrentLayer = 0; // "layer" in here refers to y-coordinate, NOT structure layer
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 firstBoneForThisCoordinate = true; // second-layer blocks (e.g. water in waterlogged blocks) will be at the same position
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 blockCoordinateName = `b_${x}_${y}_${z}`;
let boneName = blockCoordinateName;
if(!firstBoneForThisCoordinate) {
boneName += `_${layerI}`;
}
if(config.DO_SPAWN_ANIMATION && structureI == 0 && structureFiles.length > 1) {
boneName += "_a"; // different bone name in order for the animation to not affect blocks in the same position in other structures
}
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,
"pivot": bonePos.map(x => x + 8), // prevent flickering
...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(firstBoneForThisCoordinate) { // 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"][blockCoordinateName] ??= bonePos.map(x => x + 8);
}
if(config.DO_SPAWN_ANIMATION && structureI == 0) {
spawnAnimationAnimatedBones.push([boneName, getSpawnAnimationDelay(x, y, z), bonePos]);
}
let block = blockPalette[paletteI];
if(!config.IGNORED_MATERIAL_LIST_BLOCKS.includes(block["name"])) {
materialList.add(block);
}
if(layerI == 0) { // particle_expire_if_in_blocks only works on the first layer :(
blocksToValidate.push({
"locator": blockCoordinateName,
"block": block["name"],
"pos": [x, y, z]
});
blocksToValidateCurrentLayer++;
uniqueBlocksToValidate.add(block["name"]);
}
firstBoneForThisCoordinate = false;
totalBlockCount++;
});
}
}
blocksToValidateByLayer.push(blocksToValidateCurrentLayer);
}
hologramGeo["minecraft:geometry"].push(geo);
if(config.DO_SPAWN_ANIMATION && structureI == 0) {
let minDelay = min(...spawnAnimationAnimatedBones.map(([, delay]) => delay));
spawnAnimationAnimatedBones.forEach(([boneName, delay, bonePos]) => {
delay -= minDelay - 0.05;
delay = Number(delay.toFixed(2));
hologramAnimations["animations"]["animation.armor_stand.hologram.spawn"]["bones"][boneName] = makeHologramSpawnAnimation(delay, bonePos);
});
}
addBoundingBoxParticles(hologramAnimationControllers, structureI, structureSize);
addBlockValidationParticles(hologramAnimationControllers, structureI, blocksToValidate, structureSize);
totalBlocksToValidateByStructure.push(blocksToValidate.length);
totalBlocksToValidateByStructureByLayer.push(blocksToValidateByLayer);
});
entityDescription["materials"]["hologram"] = "holoprint_hologram";
entityDescription["materials"]["hologram.wrong_block_overlay"] = "holoprint_hologram.wrong_block_overlay";
entityDescription["textures"]["hologram.overlay"] = "textures/entity/overlay";
entityDescription["textures"]["hologram.save_icon"] = "textures/particle/save_icon";
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.spawn_animation"] = "controller.animation.armor_stand.hologram.spawn_animation";
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["animations"]["controller.hologram.saving_backup_particles"] = "controller.animation.armor_stand.hologram.saving_backup_particles";
entityDescription["scripts"]["animate"] ??= [];
entityDescription["scripts"]["animate"].push("hologram.align", "hologram.offset", "hologram.wrong_block_overlay", "controller.hologram.spawn_animation", "controller.hologram.layers", "controller.hologram.bounding_box", "controller.hologram.block_validation", "controller.hologram.saving_backup_particles");
entityDescription["scripts"]["should_update_bones_and_effects_offscreen"] = true; // makes backups work when offscreen (from my testing it helps a bit). this also makes it render when you're facing away, removing the need for visible_bounds_width/visible_bounds_height in the geometry file. (when should_update_effects_offscreen is set, it renders when facing away, but doesn't seem to have access to v. variables.)
entityDescription["scripts"]["initialize"] ??= [];
entityDescription["scripts"]["initialize"].push(functionToMolang(entityScripts.armorStandInitialization, {
structureSize: structureSizes[0],
defaultTextureIndex,
singleLayerMode: HOLOGRAM_LAYER_MODES.SINGLE,
structureCount: structureFiles.length
}));
entityDescription["scripts"]["pre_animation"] ??= [];
entityDescription["scripts"]["pre_animation"].push(functionToMolang(entityScripts.armorStandPreAnimation, {
textureBlobsCount: textureBlobs.length,
totalBlocksToValidate: arrayToMolang(totalBlocksToValidateByStructure, "v.hologram.structure_index"),
totalBlocksToValidateByLayer: array2DToMolang(totalBlocksToValidateByStructureByLayer, "v.hologram.structure_index", "v.hologram.layer"),
backupSlotCount: config.BACKUP_SLOT_COUNT,
structureWMolang,
structureHMolang,
structureDMolang,
toggleRendering: itemCriteriaToMolang(config.CONTROLS.TOGGLE_RENDERING),
changeOpacity: itemCriteriaToMolang(config.CONTROLS.CHANGE_OPACITY),
toggleTint: itemCriteriaToMolang(config.CONTROLS.TOGGLE_TINT),
toggleValidating: itemCriteriaToMolang(config.CONTROLS.TOGGLE_VALIDATING),
changeLayer: itemCriteriaToMolang(config.CONTROLS.CHANGE_LAYER),
decreaseLayer: itemCriteriaToMolang(config.CONTROLS.DECREASE_LAYER),
changeLayerMode: itemCriteriaToMolang(config.CONTROLS.CHANGE_LAYER_MODE),
rotateHologram: itemCriteriaToMolang(config.CONTROLS.ROTATE_HOLOGRAM),
disablePlayerControls: itemCriteriaToMolang(config.CONTROLS.DISABLE_PLAYER_CONTROLS),
backupHologram: itemCriteriaToMolang(config.CONTROLS.BACKUP_HOLOGRAM),
singleLayerMode: HOLOGRAM_LAYER_MODES.SINGLE
}));
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.hologram.rendering"
}, {
"controller.render.armor_stand.hologram.wrong_block_overlay": "v.hologram.show_wrong_block_overlay"
}, {
"controller.render.armor_stand.hologram.valid_structure_overlay": "v.hologram.validating && v.wrong_blocks == 0"
}, "controller.render.armor_stand.hologram.particle_alignment");
entityDescription["particle_effects"] ??= {};
entityDescription["particle_effects"]["bounding_box_outline"] = "holoprint:bounding_box_outline";
entityDescription["particle_effects"]["saving_backup"] = "holoprint:saving_backup";
textureBlobs.forEach(([textureName]) => {
entityDescription["textures"][textureName] = `textures/entity/${textureName}`;
hologramRenderControllers["render_controllers"]["controller.render.armor_stand.hologram"]["arrays"]["textures"]["Array.textures"].push(`Texture.${textureName}`);
});
let tintColorChannels = hexColorToClampedTriplet(config.TINT_COLOR);
hologramRenderControllers["render_controllers"]["controller.render.armor_stand.hologram"]["overlay_color"] = {
"r": +tintColorChannels[0].toFixed(4),
"g": +tintColorChannels[1].toFixed(4),
"b": +tintColorChannels[2].toFixed(4),
"a": `v.hologram.show_tint? ${config.TINT_OPACITY} : 0`
};
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"] ?? 0;
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
}
})));
let highestItemCount = max(...finalisedMaterialList.map(({ count }) => count));
let longestItemNameLength = max(...finalisedMaterialList.map(({ translatedName }) => translatedName.length));
let longestCountLength = max(...finalisedMaterialList.map(({ partitionedCount }) => partitionedCount.length));
if(longestItemNameLength + longestCountLength >= 47) {
hudScreenUI["material_list"]["size"][0] = "50%"; // up from 40%
hudScreenUI["material_list"]["max_size"][0] = "50%";
}
hudScreenUI["material_list"]["size"][1] = finalisedMaterialList.length * 12 + 12; // 12px for each item + 12px for the heading
hudScreenUI["material_list_entry"]["controls"][0]["content"]["controls"][3]["item_name"]["size"][0] += `${round(longestCountLength * 4.2 + 10)}px`;
manifest["header"]["name"] = packName;
manifest["header"]["uuid"] = crypto.randomUUID();
let packVersion = VERSION.match(/^v(\d+)\.(\d+)\.(\d+)$/)?.slice(1)?.map(x => +x) ?? [1, 0, 0];
manifest["header"]["version"] = packVersion;
manifest["modules"][0]["uuid"] = crypto.randomUUID();
manifest["modules"][0]["version"] = packVersion;
manifest["metadata"]["generated_with"]["holoprint"] = [packVersion.join(".")];
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 = await 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 packFileWriter = new BlobWriter();
let pack = new ZipWriter(packFileWriter);
let packFiles = [];
if(structureFiles.length == 1) {
packFiles.push([".mcstructure", structureFiles[0], structureFiles[0].name]);
} else {
packFiles.push(...structureFiles.map((structureFile, i) => [`${i}.mcstructure`, structureFile, structureFile.name]));
}
packFiles.push(["manifest.json", JSON.stringify(manifest)]);
packFiles.push(["pack_icon.png", packIcon]);
packFiles.push(["entity/armor_stand.entity.json", JSON.stringify(entityFile).replaceAll("HOLOGRAM_INITIAL_ACTIVATION", true)]);
packFiles.push(["subpacks/punch_to_activate/entity/armor_stand.entity.json", JSON.stringify(entityFile).replaceAll("HOLOGRAM_INITIAL_ACTIVATION", false)]);
packFiles.push(["render_controllers/armor_stand.hologram.render_controllers.json", JSON.stringify(hologramRenderControllers)]);
packFiles.push(["render_controllers/player.render_controllers.json", JSON.stringify(playerRenderControllers)]);
packFiles.push(["models/entity/armor_stand.hologram.geo.json", stringifyWithFixedDecimals(hologramGeo)]);
packFiles.push(["materials/entity.material", JSON.stringify(hologramMaterial)]);
packFiles.push(["animation_controllers/armor_stand.hologram.animation_controllers.json", JSON.stringify(hologramAnimationControllers)]);
packFiles.push(["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
packFiles.push([`particles/${particleName}.json`, JSON.stringify(particle)]);
});
packFiles.push(["particles/saving_backup.json", JSON.stringify(savingBackupParticle)]);
packFiles.push(["textures/particle/single_white_pixel.png", await singleWhitePixelTexture.toBlob()]);
packFiles.push(["textures/particle/exclamation_mark.png", await exclamationMarkTexture.toBlob()]);
packFiles.push(["textures/particle/save_icon.png", await saveIconTexture.toBlob()]);
packFiles.push(["textures/entity/overlay.png", await overlayTexture.toBlob()]);
packFiles.push(["animations/armor_stand.hologram.animation.json", JSON.stringify(hologramAnimations)]);
textureBlobs.forEach(([textureName, blob]) => {
packFiles.push([`textures/entity/${textureName}.png`, blob]);
});
packFiles.push(["ui/hud_screen.json", JSON.stringify(hudScreenUI)]);
if(highestItemCount >= 1728) {
packFiles.push(["font/glyph_E2.png", await customEmojiFont.toBlob()]);
}
packFiles.push(["texts/languages.json", JSON.stringify(languagesDotJson)]);
languageFiles.forEach(([language, languageFile]) => {
packFiles.push([`texts/${language}.lang`, languageFile]);
});
await Promise.all(packFiles.map(([fileName, fileContents, comment]) => {
/** @type {import("@zip.js/zip.js").ZipWriterAddDataOptions} */
let options = {
comment,
level: config.COMPRESSION_LEVEL
};
if(fileContents instanceof Blob) {
return pack.add(fileName, new BlobReader(fileContents), options);
} else {
return pack.add(fileName, new TextReader(fileContents), options);
}
}));
let zippedPack = await pack.close();
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
});
if(structureFiles.length == 1) {
p.dataset.translate = "preview.click_to_view";
} else {
p.dataset.translate = "preview.click_to_view_multiple";
}
message.appendChild(p);
message.onEvent("click", () => {
message.remove();
showPreview();
});
previewCont.appendChild(message);
}
}
return new File([zippedPack], `${packName}.holoprint.mcpack`, {
type: "application/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 packFileReader = new BlobReader(resourcePack);
let packFolder = new ZipReader(packFileReader);
let structureFileEntries = (await packFolder.getEntries()).filter(entry => entry.filename.endsWith(".mcstructure"));
packFolder.close();
let structureBlobs = await Promise.all(structureFileEntries.map(entry => entry.getData(new BlobWriter())));
let packName = resourcePack.name.slice(0, resourcePack.name.indexOf("."));
if(structureBlobs.length == 1) {
return [new File([structureBlobs[0]], structureFileEntries[0].comment || `${packName}.mcstructure`)];
} else {
return await Promise.all(structureBlobs.map(async (structureBlob, i) => new File([structureBlob], structureFileEntries[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)}`
}
if(defaultName.trim() == "") {
defaultName = "HoloPrint";
}
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}
*/
export function addDefaultConfig(config) {
return Object.freeze({
...{ // defaults
IGNORED_BLOCKS: [],
IGNORED_MATERIAL_LIST_BLOCKS: [],
SCALE: 0.95,
OPACITY: 0.9,
MULTIPLE_OPACITIES: true,
TINT_COLOR: "#579EFA",
TINT_OPACITY: 0.2,
MINI_SCALE: 0.125, // size of ghost blocks when in the mini view for layers
TEXTURE_OUTLINE_WIDTH: 0.25, // pixels, x ∈ [0, 1], x ∈ 2^ℝ
TEXTURE_OUTLINE_COLOR: "#00F",
TEXTURE_OUTLINE_OPACITY: 0.65,
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: {},
BACKUP_SLOT_COUNT: 10,
MATERIAL_LIST_LANGUAGE: "en_US",
PACK_NAME: undefined,
PACK_ICON_BLOB: undefined,
AUTHORS: [],
DESCRIPTION: undefined,
COMPRESSION_LEVEL: 5, // level 9 was 8 bytes larger than level 5 when I tested... :0
PREVIEW_BLOCK_LIMIT: 500,
SHOW_PREVIEW_SKYBOX: true
},
...config,
...{ // overrides (applied after)
IGNORED_BLOCKS: IGNORED_BLOCKS.concat(config.IGNORED_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}`), path);
});
Object.entries(stuff.resources).forEach(([name, path]) => {
filePromises[name] = getResponseContents(resourcePackStack.fetchResource(path), path);
});
Object.assign(filePromises, stuff.otherFiles);
let dataPromises = {};
Object.entries(stuff.data).forEach(([name, path]) => {
dataPromises[name] = getResponseContents(resourcePackStack.fetchData(path), 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
* @param {String} filePath
* @returns {Promise<String|Blob|Object|HTMLImageElement>}
*/
async function getResponseContents(resPromise, filePath) {
let res = await resPromise;
if(res.status >= 400) {
throw new Error(`HTTP error ${res.status} for ${res.url}`);
}
let fileExtension = filePath.slice(filePath.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>] }}
*/
async 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
let blockUpdater = new BlockUpdater(true);
let updatedBlocks = 0;
for(let [i, block] of Object.entries(palette)) {
blockVersions.add(+block["version"]);
if(blockUpdater.blockNeedsUpdating(block)) {
if(await blockUpdater.update(block)) {
updatedBlocks++;
}
}
block["name"] = block["name"].replace(/^minecraft:/, ""); // remove namespace here, right at the start
if(ignoredBlocks.includes(block["name"])) {
delete palette[i];
continue;
}
delete block["version"];
if(!Object.keys(block["states"]).length) {
delete block["states"]; // easier viewing
}
}
let blockVersionsStringified = [...blockVersions].map(v => BlockUpdater.parseBlockVersion(v).join("."));
if(updatedBlocks > 0) {
console.info(`Updated ${updatedBlocks} block${updatedBlocks > 1? "s" : ""} from ${blockVersionsStringified.join(", ")} to ${BlockUpdater.parseBlockVersion(BlockUpdater.LATEST_VERSION).join(".")}!`);
console.info(`Note: Updated blocks may not be 100% accurate! If there are some errors, try loading the structure in the latest version of Minecraft then saving it again, so all blocks are up to date.`);
}
console.log("Block versions:", [...blockVersions], blockVersionsStringified);
// 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 = [
`v.size = ${structureSize[0] / 2}; v.dir = 0; v.r = 1; v.g = 0; v.b = 0;`,
`v.size = ${structureSize[1] / 2}; v.dir = 1; v.r = 1 / 255; v.g = 1; v.b = 0;`,
`v.size = ${structureSize[2] / 2}; v.dir = 2; v.r = 0; v.g = 162 / 255; v.b = 1;`,
`v.size = ${structureSize[0] / 2}; v.dir = 0; v.y = ${structureSize[1]}; v.r = 1; v.g = 1; v.b = 1;`,
`v.size = ${structureSize[0] / 2}; v.dir = 0; v.z = ${structureSize[2]}; v.r = 1; v.g = 1; v.b = 1;`,
`v.size = ${structureSize[0] / 2}; v.dir = 0; v.y = ${structureSize[1]}; v.z = ${structureSize[2]}; v.r = 1; v.g = 1; v.b = 1;`,
`v.size = ${structureSize[1] / 2}; v.dir = 1; v.x = ${structureSize[0]}; v.r = 1; v.g = 1; v.b = 1;`,
`v.size = ${structureSize[1] / 2}; v.dir = 1; v.z = ${structureSize[2]}; v.r = 1; v.g = 1; v.b = 1;`,
`v.size = ${structureSize[1] / 2}; v.dir = 1; v.x = ${structureSize[0]}; v.z = ${structureSize[2]}; v.r = 1; v.g = 1; v.b = 1;`,
`v.size = ${structureSize[2] / 2}; v.dir = 2; v.x = ${structureSize[0]}; v.r = 1; v.g = 1; v.b = 1;`,
`v.size = ${structureSize[2] / 2}; v.dir = 2; v.y = ${structureSize[1]}; v.r = 1; v.g = 1; v.b = 1;`,
`v.size = ${structureSize[2] / 2}; v.dir = 2; v.x = ${structureSize[0]}; v.y = ${structureSize[1]}; v.r = 1; v.g = 1; v.b = 1;`
];
let boundingBoxAnimation = {
"particle_effects": [],
"transitions": [
{
"hidden": `!v.hologram.rendering || v.hologram.structure_index != ${structureI}`
}
]
};
outlineParticleSettings.forEach(particleMolang => {
boundingBoxAnimation["particle_effects"].push({
"effect": "bounding_box_outline",
"locator": "hologram_root",
"pre_effect_script": particleMolang.replaceAll(/\s/g, "")
});
});
let animationStateName = `visible_${structureI}`;
hologramAnimationControllers["animation_controllers"]["controller.animation.armor_stand.hologram.bounding_box"]["states"][animationStateName] = boundingBoxAnimation;
hologramAnimationControllers["animation_controllers"]["controller.animation.armor_stand.hologram.bounding_box"]["states"]["hidden"]["transitions"].push({