-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdata.ts
More file actions
2325 lines (2149 loc) · 73.6 KB
/
data.ts
File metadata and controls
2325 lines (2149 loc) · 73.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Core data layer for Cataclysm: Bright Nights game data.
*
* ARCHITECTURE:
* - **Singleton pattern**: `CBNData` is instantiated once per loaded data context
* - **Data identity changes reload**: Build version, locale, and active mods
* replace the dataset with a full navigation because they point at different
* payloads (see `docs/routing.md`, ADR-002)
* - **Display preferences stay soft**: Tileset changes are presentation-only and
* are handled by SPA navigation without rebuilding the data singleton
* - **Incremental Mod Resolution**: Mods are resolved via top-to-bottom
* unfurling during flattening (see ADR-003)
* - **Immutable after construction**: All data is frozen after initial load
* (~30MB, 30K+ objects)
* - **Caching**: Maps and WeakMaps never need invalidation because their
* lifetime matches the published data instance
*
* This split is intentional: route changes that select different source data
* rebuild the singleton, while display-only navigation keeps the existing
* instance alive.
*/
import { writable } from "svelte/store";
import * as perf from "./utils/perf";
import { isTesting } from "./utils/env";
import type {
Bionic,
DamageInstance,
DamageUnit,
Item,
ItemGroup,
ItemGroupData,
ItemGroupEntry,
Mapgen,
ModData,
ModInfo,
Monster,
MonsterBlacklist,
MonsterWhitelist,
OvermapSpecial,
QualityRequirement,
Recipe,
Requirement,
RequirementData,
SupportedTypeMapped,
SupportedTypesWithMapped,
Translation,
Trap,
UseFunction,
Vehicle,
VehicleMountedPartDefinition,
} from "./types";
import type { Loot } from "./types/item/spawnLocations";
import {
furnitureByOMSAppearance,
lootByOMSAppearance,
terrainByOMSAppearance,
} from "./types/item/spawnLocations";
import { cleanText, parseMass, parseVolume } from "./utils/format";
import { yieldUntilIdle } from "./utils/idle";
import { asArray } from "./utils/collections";
import {
applyLocaleJSON,
byName,
gameSingularName,
resetI18n,
} from "./i18n/game-locale";
import { loadRawDataset } from "./data-loader";
import { DEFAULT_LOCALE } from "./constants";
const typeMappings = new Map<string, keyof SupportedTypesWithMapped>([
["AMMO", "item"],
["GUN", "item"],
["ARMOR", "item"],
["PET_ARMOR", "item"],
["TOOL", "item"],
["TOOLMOD", "item"],
["TOOL_ARMOR", "item"],
["BOOK", "item"],
["COMESTIBLE", "item"],
["CONTAINER", "item"],
["ENGINE", "item"],
["WHEEL", "item"],
["GUNMOD", "item"],
["MAGAZINE", "item"],
["BATTERY", "item"],
["GENERIC", "item"],
["BIONIC_ITEM", "item"],
["MONSTER", "monster"],
["city_building", "overmap_special"],
]);
export const mapType = (
type: keyof SupportedTypesWithMapped,
): keyof SupportedTypesWithMapped => typeMappings.get(type) ?? type;
const DIRECTION_SUFFIX_REGEX = /_(north|south|east|west)$/;
/**
* Central data store for the application.
* Handles loading, indexing, and accessing game data.
* Implements lazy flattening of objects (resolving inheritance).
*/
export class CBNData {
_raw: any[];
/**
* A record containing mods data, where each key is a string identifier for a specific mod
* and the value is an object representing the corresponding mod's data.
*
* @property {string} key - The unique identifier for the mod.
* @property {ModData} value - The data object containing configuration and metadata for the mod.
*/
_rawModsJSON: Record<string, ModData>;
/** Concrete build number from the game data (e.g., "v0.9.1") */
_buildVersion: string;
/** Original version slug used for fetching (e.g., "stable", "nightly") */
_fetchVersion: string;
/** Ordered active non-core mod ids. */
_activeMods: string[];
/** Effective locale actually loaded and applied to the i18n singleton. */
_locale: string;
_byType: Map<string, any[]> = new Map();
_byTypeById: Map<string, Map<string, any>> = new Map();
_abstractsByType: Map<string, Map<string, any>> = new Map();
_overrides: Map<any, any> = new Map();
_toolReplacements: Map<string, string[]> = new Map();
_craftingPseudoItems: Map<string, string[]> = new Map();
_migrations: Map<string, string> = new Map();
_flattenCache: Map<any, any> = new Map();
_nestedMapgensById: Map<string, Mapgen[]> = new Map();
_byTypeCache: Map<keyof SupportedTypesWithMapped, SupportedTypeMapped[]> =
new Map();
/**
* Cached monster policy selectors resolved from MONSTER_BLACKLIST and
* MONSTER_WHITELIST policies.
*
* @internal
*/
_monsterVisibilityPolicy?: {
explicitBlacklisted: Set<string>;
blacklistedSpecies: Set<string>;
blacklistedCategories: Set<string>;
explicitWhitelisted: Set<string>;
whitelistedSpecies: Set<string>;
whitelistedCategories: Set<string>;
hasExclusiveWhitelist: boolean;
};
constructor(
rawJSON: unknown[],
buildVersion: string,
fetchVersion: string,
locale: string,
localeJSON: unknown | undefined,
pinyinJSON: unknown | undefined,
activeMods: string[],
rawModsJSON: Record<string, ModData>,
) {
const p = perf.mark("CBNData.constructor");
const raw = rawJSON as any[];
this._buildVersion = buildVersion;
this._fetchVersion = fetchVersion;
this._activeMods = activeMods;
this._locale = locale;
this._rawModsJSON = rawModsJSON;
// Apply locale to the shared i18n singleton before any data method runs.
if (locale !== DEFAULT_LOCALE) {
try {
applyLocaleJSON(localeJSON, pinyinJSON ?? null, this._locale);
} catch (e) {
console.warn("Failed to apply locale JSON in CBNData constructor:", e);
resetI18n(DEFAULT_LOCALE);
this._locale = DEFAULT_LOCALE;
}
}
// For some reason O—G has the string "mapgen" as one of its objects.
this._raw = raw.filter((x) => typeof x === "object");
for (const obj of raw) {
if (!Object.hasOwnProperty.call(obj, "type")) continue;
if (obj.type === "MIGRATION") {
for (const id of typeof obj.id === "string" ? [obj.id] : obj.id) {
const { replace } = obj;
this._migrations.set(id, replace);
}
continue;
}
const mappedType = mapType(obj.type);
if (!this._byType.has(mappedType)) this._byType.set(mappedType, []);
this._byType.get(mappedType)!.push(obj);
if (Object.hasOwnProperty.call(obj, "id")) {
if (!this._byTypeById.has(mappedType))
this._byTypeById.set(mappedType, new Map());
if (typeof obj.id === "string") {
const byTypeById = this._byTypeById.get(mappedType)!;
const previous = byTypeById.get(obj.id);
if (previous) {
this._overrides.set(obj, previous);
}
byTypeById.set(obj.id, obj);
} else if (Array.isArray(obj.id))
for (const id of obj.id)
this._byTypeById.get(mappedType)!.set(id, obj);
// TODO: proper alias handling. We want to e.g. be able to collapse them in loot tables.
if (Array.isArray(obj.alias))
for (const id of obj.alias)
this._byTypeById.get(mappedType)!.set(id, obj);
else if (typeof obj.alias === "string")
this._byTypeById.get(mappedType)!.set(obj.alias, obj);
}
// recipes are id'd by their result
if (
(mappedType === "recipe" || mappedType === "uncraft") &&
Object.hasOwnProperty.call(obj, "result")
) {
if (!this._byTypeById.has(mappedType))
this._byTypeById.set(mappedType, new Map());
const id = obj.result + (obj.id_suffix ? "_" + obj.id_suffix : "");
this._byTypeById.get(mappedType)!.set(id, obj);
}
if (
mappedType === "monstergroup" &&
Object.hasOwnProperty.call(obj, "name")
) {
if (!this._byTypeById.has(mappedType))
this._byTypeById.set(mappedType, new Map());
const id = obj.name;
this._byTypeById.get(mappedType)!.set(id, obj);
}
if (Object.hasOwnProperty.call(obj, "abstract")) {
if (!this._abstractsByType.has(mappedType))
this._abstractsByType.set(mappedType, new Map());
// Track previous abstract if it exists (mod override pattern)
const previous = this._abstractsByType
.get(mappedType)!
.get(obj.abstract);
if (previous) {
this._overrides.set(obj, previous);
}
this._abstractsByType.get(mappedType)!.set(obj.abstract, obj);
}
if (Object.hasOwnProperty.call(obj, "crafting_pseudo_item")) {
for (const pseudoId of asArray(obj.crafting_pseudo_item)) {
if (!this._craftingPseudoItems.has(pseudoId)) {
this._craftingPseudoItems.set(pseudoId, []);
}
const providers = this._craftingPseudoItems.get(pseudoId)!;
if (!providers.includes(obj.id)) providers.push(obj.id);
}
}
if (Object.hasOwnProperty.call(obj, "nested_mapgen_id")) {
if (!this._nestedMapgensById.has(obj.nested_mapgen_id))
this._nestedMapgensById.set(obj.nested_mapgen_id, []);
this._nestedMapgensById.get(obj.nested_mapgen_id)!.push(obj);
}
// Build tool replacements index inline (TOOL items with 'sub' field)
if (obj.type === "TOOL" && obj.sub) {
if (!this._toolReplacements.has(obj.sub))
this._toolReplacements.set(obj.sub, []);
this._toolReplacements.get(obj.sub)!.push(obj.id);
}
}
this._byTypeById
.get("item_group")
?.set("EMPTY_GROUP", { id: "EMPTY_GROUP", entries: [] });
p.finish();
}
_getVisibilityPolicy() {
if (this._monsterVisibilityPolicy) return this._monsterVisibilityPolicy;
const explicitBlacklisted = new Set<string>();
const blacklistedSpecies = new Set<string>();
const blacklistedCategories = new Set<string>();
const explicitWhitelisted = new Set<string>();
const whitelistedSpecies = new Set<string>();
const whitelistedCategories = new Set<string>();
let hasExclusiveWhitelist = false;
const blacklists =
(this._byType.get("MONSTER_BLACKLIST") as MonsterBlacklist[]) ?? [];
const whitelists =
(this._byType.get("MONSTER_WHITELIST") as MonsterWhitelist[]) ?? [];
for (const policy of blacklists) {
for (const id of asArray(policy.monsters)) explicitBlacklisted.add(id);
for (const species of asArray(policy.species))
blacklistedSpecies.add(species);
for (const category of asArray(policy.categories)) {
blacklistedCategories.add(category);
}
}
for (const policy of whitelists) {
if (policy.mode === "EXCLUSIVE") hasExclusiveWhitelist = true;
for (const id of asArray(policy.monsters)) explicitWhitelisted.add(id);
for (const species of asArray(policy.species))
whitelistedSpecies.add(species);
for (const category of asArray(policy.categories)) {
whitelistedCategories.add(category);
}
}
this._monsterVisibilityPolicy = {
explicitBlacklisted,
blacklistedSpecies,
blacklistedCategories,
explicitWhitelisted,
whitelistedSpecies,
whitelistedCategories,
hasExclusiveWhitelist,
};
return this._monsterVisibilityPolicy;
}
/**
* Checks if a monster ID is visible according to the loaded policy.
*
* @param mon The monster to check
* @returns true if visible (default), false if blacklisted/not whitelisted.
*/
isMonsterVisible(
mon: Pick<Monster, "id" | "species" | "categories">,
): boolean {
const policy = this._getVisibilityPolicy();
const monCategories = asArray(mon.categories);
const monSpecies = asArray(mon.species);
const isWhitelisted =
policy.explicitWhitelisted.has(mon.id) ||
monSpecies.some((entry) => policy.whitelistedSpecies.has(entry)) ||
monCategories.some((entry) => policy.whitelistedCategories.has(entry));
const isBlacklisted =
policy.explicitBlacklisted.has(mon.id) ||
monSpecies.some((entry) => policy.blacklistedSpecies.has(entry)) ||
monCategories.some((entry) => policy.blacklistedCategories.has(entry));
return policy.hasExclusiveWhitelist
? isWhitelisted
: isWhitelisted || !isBlacklisted;
}
#dissectedFromIndex = new ReverseIndex(this, "monster", (monster) => {
if (!monster.harvest) return [];
const harvest = this.byIdMaybe("harvest", monster.harvest);
if (!harvest?.entries) return [];
return harvest.entries.flatMap((entry) => {
if (entry.type === "bionic" || entry.type === "bionic_faulty") {
return [entry.drop];
}
if (entry.type === "bionic_group") {
const group = this.byIdMaybe("item_group", entry.drop);
return group
? this.flattenTopLevelItemGroup(group).map((x) => x.id)
: [];
}
return [];
});
});
/**
* Returns a list of monsters that provide the given item (or group) via dissection.
*
* @param id The item ID or item group ID to search for.
* @returns A list of monsters.
*/
dissectedFrom(id: string): Monster[] {
return this.#dissectedFromIndex.lookup(id);
}
/**
* Retrieves an object by type and ID, resolving inheritance.
* Returns undefined if the object is not found.
*
* @param type The type of the object (e.g., 'item', 'monster').
* @param id The ID of the object.
* @returns The flattened object or undefined.
*/
byIdMaybe<TypeName extends keyof SupportedTypesWithMapped>(
type: TypeName,
id: string,
): (SupportedTypesWithMapped[TypeName] & { __filename: string }) | undefined {
if (typeof id !== "string") {
throw new Error(
`Requested non-string id. Current id is of type: ${typeof id}`,
);
}
const byId = this._byTypeById.get(type);
if (type === "item" && !byId?.has(id) && this._migrations.has(id))
return this.byIdMaybe(type, this._migrations.get(id)!);
const obj = byId?.get(id);
if (obj) {
const flattened = this._flatten(
obj,
) as SupportedTypesWithMapped[TypeName];
if (type === "monster") {
if (!this.isMonsterVisible(flattened as Monster)) {
return undefined;
}
}
return flattened as SupportedTypesWithMapped[TypeName] & {
__filename: string;
};
}
}
/**
* Retrieves an object by type and ID, resolving inheritance.
* Throws an error if the object is not found.
*
* @param type The type of the object.
* @param id The ID of the object.
* @returns The flattened object.
* @throws {Error} If the object is not found.
*/
byId<TypeName extends keyof SupportedTypesWithMapped>(
type: TypeName,
id: string,
): SupportedTypesWithMapped[TypeName] & { __filename: string } {
const ret = this.byIdMaybe(type, id);
if (!ret)
throw new Error('unknown object "' + id + '" of type "' + type + '"');
return ret;
}
/**
* Retrieves all objects of a given type.
* For keyed object families, mod overrides are collapsed so each canonical key
* appears once (later entries win, stable order preserved).
*
* @param type The type of objects to retrieve.
* @returns An array of flattened objects.
*/
//TODO review the whole fun
byType<TypeName extends keyof SupportedTypesWithMapped>(
type: TypeName,
): SupportedTypesWithMapped[TypeName][] {
const cached = this._byTypeCache.get(type);
if (cached) return cached.slice() as SupportedTypesWithMapped[TypeName][];
const snapshot = this._buildByTypeSnapshot(type);
this._byTypeCache.set(type, snapshot as SupportedTypeMapped[]);
return snapshot.slice() as SupportedTypesWithMapped[TypeName][];
}
_buildByTypeSnapshot<TypeName extends keyof SupportedTypesWithMapped>(
type: TypeName,
): SupportedTypesWithMapped[TypeName][] {
const raws = this._byType.get(type) ?? [];
const canonicalRaws: unknown[] = [];
const keyedIndex = new Map<string, number>();
for (const raw of raws) {
const key = this._provenanceKeyForObject(type, raw);
if (key == null) {
canonicalRaws.push(raw);
continue;
}
const existingIndex = keyedIndex.get(key);
if (existingIndex == null) {
keyedIndex.set(key, canonicalRaws.length);
canonicalRaws.push(raw);
} else {
// Keep stable order but replace earlier entry with later override.
canonicalRaws[existingIndex] = raw;
}
}
const flattened = canonicalRaws.map((x) =>
this._flatten(x),
) as SupportedTypesWithMapped[TypeName][];
if (type !== "monster") return flattened;
return flattened.filter((monster) => {
return this.isMonsterVisible(monster as Monster);
});
}
abstractById<TypeName extends keyof SupportedTypesWithMapped>(
type: TypeName,
id: string,
): object | undefined /* abstracts don't have ids, for instance */ {
if (typeof id !== "string") throw new Error("Requested non-string id");
const obj = this._abstractsByType.get(type)?.get(id);
if (obj) return this._flatten(obj);
}
replacementTools(type: string): string[] {
if (!this._toolReplacements) {
const p = perf.mark("CBNData.replacementTools.build");
this._toolReplacements = new Map();
for (const obj of this.byType("item")) {
if (
obj.type === "TOOL" &&
Object.hasOwnProperty.call(obj, "sub") &&
obj.sub
) {
if (!this._toolReplacements.has(obj.sub))
this._toolReplacements.set(obj.sub, []);
this._toolReplacements.get(obj.sub)!.push(obj.id);
}
}
p.finish();
}
return this._toolReplacements.get(type) ?? [];
}
craftingPseudoItems(id: string): string[] {
return this._craftingPseudoItems.get(id) ?? [];
}
nestedMapgensById(id: string): Mapgen[] | undefined {
return this._nestedMapgensById.get(id);
}
all(): SupportedTypeMapped[] {
return this._raw;
}
allMods() {
return this._rawModsJSON;
}
activeMods() {
return this._activeMods;
}
buildVersion(): string {
return this._buildVersion;
}
locale(): string {
return this._locale;
}
fetchVersion(): string {
return this._fetchVersion;
}
/**
* Builds the canonical provenance key for a raw object in a mapped type family.
*
* Important:
* - `recipe` / `uncraft` are keyed by `result + optional id_suffix`.
* - `monstergroup` is keyed by `name`.
* - other families use `id`, falling back to `abstract`.
*
* This aligns provenance lookups with the same key strategy used by `_byTypeById`
* for non-`id` keyed object families.
*/
_provenanceKeyForObject(
mappedType: keyof SupportedTypesWithMapped,
obj: unknown,
): string | null {
if (typeof obj !== "object" || obj === null) return null;
const raw = obj as Record<string, unknown>;
if (mappedType === "recipe" || mappedType === "uncraft") {
if (typeof raw.result === "string") {
return `${raw.result}${
typeof raw.id_suffix === "string" ? `_${raw.id_suffix}` : ""
}`;
}
return typeof raw.abstract === "string" ? raw.abstract : null;
}
if (mappedType === "monstergroup") {
return typeof raw.name === "string"
? raw.name
: typeof raw.id === "string"
? raw.id
: typeof raw.abstract === "string"
? raw.abstract
: null;
}
if (typeof raw.id === "string") return raw.id;
if (typeof raw.abstract === "string") return raw.abstract;
return null;
}
/**
* Returns the current raw object for a mapped type + provenance key.
* Supports both concrete keyed objects and abstract templates.
* Handles item migrations if the key is missing from the main maps.
*
* ARCHITECTURE: Follows ADR-005 (Robust inheritance: Migrations and Self-Copy Handling)
* traversal of migration maps.
*
* @param mappedType Mapped type family to search in.
* @param key Provenance key (identifier or abstract).
* @returns The raw game object or null if entries are missing.
*/
_objectForProvenanceKey(
mappedType: keyof SupportedTypesWithMapped,
key: string,
): Record<string, unknown> | null {
// Follow item migrations to the final ID
if (
mappedType === "item" &&
!this._byTypeById.get("item")?.has(key) &&
this._migrations.has(key)
) {
return this._objectForProvenanceKey("item", this._migrations.get(key)!);
}
return (
this._byTypeById.get(mappedType)?.get(key) ??
this._abstractsByType.get(mappedType)?.get(key) ??
null
);
}
/**
* ARCHITECTURE: ADR-005 (Robust inheritance: Migrations and Self-Copy Handling).
* Resolves the parent object for a given object, specifically handling
* "self-copy" overrides by looking up the previous version in the override stack.
*/
_resolveCopyFromParent(obj: any): any | null {
if (!("copy-from" in obj)) return null;
const parentId = obj["copy-from"];
const mappedType = mapType(obj.type);
let parent = this._objectForProvenanceKey(mappedType, parentId);
// For "self-looking" copy-from patterns in layered mod overrides, use the
// previous object for this id instead of resolving to self.
if (
typeof obj.id === "string" &&
typeof parentId === "string" &&
obj.id === parentId &&
this._overrides.has(obj)
) {
parent = this._overrides.get(obj);
} else if (
typeof obj.abstract === "string" &&
typeof parentId === "string" &&
obj.abstract === parentId &&
this._overrides.has(obj)
) {
// For abstract self-copies in layered mod overrides, use the previous object
parent = this._overrides.get(obj);
} else if (parent === obj && this._overrides.has(obj)) {
parent = this._overrides.get(obj);
}
return parent;
}
/**
* Resolves a single inherited field by walking the `copy-from` chain until a
* concrete value is found.
*
* Returns `undefined` when the field is absent across the full inheritance
* chain or when a cycle is encountered.
*/
resolveOne(obj: any, key: string): any {
let current = obj;
const visited = new Set<any>();
while (current) {
if (visited.has(current)) {
console.warn("Cycle detected while resolving inherited field:", key);
break;
}
visited.add(current);
if (Object.prototype.hasOwnProperty.call(current, key)) {
return current[key];
}
current = this._resolveCopyFromParent(current);
}
return undefined;
}
/**
* Internal method to flatten an object by resolving its 'copy-from' inheritance.
* Applies relative, proportional, extend, and delete modifiers.
* Caches the result.
*
* ARCHITECTURE: Leverages top-down unfurling for performance (see ADR-003 and ADR-004)
*
* @param _obj The raw object to flatten.
* @param stack Recursion stack for inheritance cycle detection.
* @returns The flattened object.
*/
_flatten<T = any>(_obj: T, stack: Set<any> = new Set()): T {
const obj: any = _obj;
if (this._flattenCache.has(obj)) {
return this._flattenCache.get(obj);
}
if (stack.has(obj)) {
console.warn("Cycle detected in copy-from inheritance:", obj);
return obj;
}
stack.add(obj);
const parent = this._resolveCopyFromParent(obj);
if ("copy-from" in obj && !parent)
console.warn(
`Missing parent in ${
obj.id ?? obj.abstract ?? obj.result ?? JSON.stringify(obj)
}`,
);
if (parent === obj) {
// Working around bad data upstream, see: https://github.com/CleverRaven/Cataclysm-DDA/pull/53930
console.warn("Object copied from itself:", obj);
this._flattenCache.set(obj, obj);
stack.delete(obj);
return obj;
}
if (!parent) {
this._flattenCache.set(obj, obj);
stack.delete(obj);
return obj;
}
const { abstract, ...parentProps } = this._flatten(parent, stack);
stack.delete(obj);
const ret = { ...parentProps, ...obj };
if (parentProps.vitamins && obj.vitamins) {
ret.vitamins = [
...parentProps.vitamins.filter(
(x: any) => !obj.vitamins.some((y: any) => y[0] === x[0]),
),
...obj.vitamins,
];
}
if (obj.type === "vehicle" && parentProps.parts && obj.parts) {
ret.parts = [...parentProps.parts, ...obj.parts];
}
for (const k of Object.keys(ret.relative ?? {})) {
if (k === "melee_damage" && ret.type === "MONSTER") {
// Monster melee_damage is loaded directly in BN, not via assign(), so
// relative modifiers do not apply.
continue;
}
if (typeof ret.relative[k] === "number") {
if (k === "weight") {
ret[k] = (parseMass(ret[k]) ?? 0) + ret.relative[k];
} else if (k === "volume") {
ret[k] = (parseVolume(ret[k]) ?? 0) + ret.relative[k];
} else {
ret[k] = (ret[k] ?? 0) + ret.relative[k];
}
} else if (
(k === "damage" || k === "ranged_damage") &&
ret[k] &&
isDamageInstanceLike(ret[k]) &&
isDamageInstanceLike(ret.relative[k])
) {
// See docs/copy-from-modifiers.md for which fields support this
ret[k] = applyRelativeDamageInstance(ret[k], ret.relative[k]);
} else if (k === "armor" && ret.type === "MONSTER" && ret[k]) {
ret[k] = { ...ret[k] };
for (const k2 of Object.keys(ret.relative[k])) {
ret[k][k2] = (ret[k][k2] ?? 0) + ret.relative[k][k2];
}
} else if (k === "qualities") {
ret[k] = cloneQualities(ret[k]);
for (const [q, l] of ret.relative[k]) {
const existing = ret[k].find((x: any) => x[0] === q);
existing[1] += l;
}
}
// TODO: vitamins, mass, volume, time
}
delete ret.relative;
for (const k of Object.keys(ret.proportional ?? {})) {
if (k === "melee_damage" && ret.type === "MONSTER") {
// Monster melee_damage is loaded directly in BN, not via assign(), so
// proportional modifiers do not apply.
continue;
}
if (typeof ret.proportional[k] === "number") {
if (k === "attack_cost" && !(k in ret)) ret[k] = 100;
if (typeof ret[k] === "string") {
const m = /^\s*(\d+)\s*(.+)$/.exec(ret[k]);
if (m) {
const [, num, unit] = m;
ret[k] = `${Number(num) * ret.proportional[k]} ${unit}`;
}
} else {
ret[k] *= ret.proportional[k];
ret[k] = ret[k] | 0; // most things are ints.. TODO: what keys are float?
}
} else if (
(k === "damage" || k === "ranged_damage") &&
ret[k] &&
isDamageInstanceLike(ret[k]) &&
isDamageInstanceLike(ret.proportional[k])
) {
// See docs/copy-from-modifiers.md for which fields support this
ret[k] = applyProportionalDamageInstance(ret[k], ret.proportional[k]);
} else if (k === "armor" && ret.type === "MONSTER" && ret[k]) {
ret[k] = { ...ret[k] };
for (const k2 of Object.keys(ret.proportional[k])) {
ret[k][k2] *= ret.proportional[k][k2];
ret[k][k2] = ret[k][k2] | 0; // most things are ints.. TODO: what keys are float?
}
}
// TODO: mass, volume, time (need to check the base value's type)
}
delete ret.proportional;
for (const k of Object.keys(ret.extend ?? {})) {
if (Array.isArray(ret.extend[k])) {
if (k === "flags")
// Unique
ret[k] = (ret[k] ?? []).concat(
ret.extend[k].filter((x: any) => !ret[k]?.includes(x)),
);
else ret[k] = (ret[k] ?? []).concat(ret.extend[k]);
}
}
delete ret.extend;
for (const k of Object.keys(ret.delete ?? {})) {
if (Array.isArray(ret.delete[k])) {
// Some 'delete' entries delete qualities, which are arrays. As a rough
// heuristic, compare recursively.
const isEqual = (x: any, y: any): boolean =>
x === y ||
(Array.isArray(x) &&
Array.isArray(y) &&
x.length === y.length &&
x.every((j, i) => isEqual(j, y[i])));
ret[k] = (ret[k] ?? []).filter(
(x: any) => !ret.delete[k].some((y: any) => isEqual(y, x)),
);
} else {
// For non-array properties (like objects), delete the entire property
delete ret[k];
}
}
delete ret.delete;
this._flattenCache.set(obj, ret);
return ret;
}
_cachedDeathDrops: Map<string, Loot> = new Map();
flatDeathDrops(mon_id: string): Loot {
if (this._cachedDeathDrops.has(mon_id))
return this._cachedDeathDrops.get(mon_id)!;
const mon = this.byId("monster", mon_id);
const ret = mon.death_drops
? this.flattenItemGroupLoot(
this.normalizeItemGroup(mon.death_drops, "distribution") ?? {
subtype: "collection",
entries: [],
},
)
: new Map();
this._cachedDeathDrops.set(mon_id, ret);
return ret;
}
_cachedUncraftRecipes: Map<string, Recipe> | null = null;
uncraftRecipe(item_id: string): Recipe | undefined {
if (!this._cachedUncraftRecipes) {
this._cachedUncraftRecipes = new Map();
for (const recipe of this.byType("recipe"))
if (recipe.result && recipe.reversible)
this._cachedUncraftRecipes.set(recipe.result, recipe);
for (const recipe of this.byType("uncraft"))
if (recipe.result)
this._cachedUncraftRecipes.set(recipe.result, recipe);
}
return this._cachedUncraftRecipes.get(item_id);
}
// Top-level item groups can have the "old" subtype (which is the default if
// no other subtype is specified).
_convertedTopLevelItemGroups = new Map<ItemGroup, ItemGroupData>();
convertTopLevelItemGroup(group: ItemGroup): ItemGroupData {
if (group.subtype === "distribution" || group.subtype === "collection") {
return group;
} else if (
!("subtype" in group) ||
!group.subtype ||
group.subtype === "old"
) {
if (this._convertedTopLevelItemGroups.has(group))
return this._convertedTopLevelItemGroups.get(group)!;
// Convert old-style item groups to new-style
const normalizedEntries: ItemGroupEntry[] = [];
for (const item of group.items ?? [])
if (Array.isArray(item))
normalizedEntries.push({ item: item[0], prob: item[1] });
else normalizedEntries.push(item);
const ret: ItemGroupData = {
subtype: "distribution",
entries: normalizedEntries,
};
this._convertedTopLevelItemGroups.set(group, ret);
return ret;
} else throw new Error("unknown item group subtype: " + group.subtype);
}
flattenTopLevelItemGroup(group: ItemGroup) {
return this.flattenItemGroup(this.convertTopLevelItemGroup(group));
}
// This is a WeakMap because flattenItemGroup is sometimes called with temporary objects
_flattenItemGroupCache = new WeakMap<
ItemGroupData,
{ id: string; prob: number; expected: number; count: [number, number] }[]
>();
/**
* In the result, each |id| will be spawned with probability |prob|. If the item
* is spawned, it will be spawned between |count[0]| and |count[1]| times.
*/
flattenItemGroup(
group: ItemGroupData,
): { id: string; prob: number; expected: number; count: [number, number] }[] {
if (this._flattenItemGroupCache.has(group))
return this._flattenItemGroupCache.get(group)!;
const p = perf.mark(`CBNData.flattenItemGroup`, true);
const retMap = new Map<
string,
{ prob: number; expected: number; count: [number, number] }
>();
function addOne({
id,
prob,
count,
}: {
id: string;
prob: number;
count: [number, number];
}) {
if (id === "null") return;
const {
prob: prevProb,
count: prevCount,
expected: prevExpected,
} = retMap.get(id) ?? {
prob: 0,
count: [0, 0],
expected: 0,
};
const newProb = 1 - (1 - prevProb) * (1 - prob);
const newCount: [number, number] = [
count[0] + prevCount[0],
count[1] + prevCount[1],
];
const newExpected = prevExpected + (prob * (count[0] + count[1])) / 2;
retMap.set(id, { prob: newProb, expected: newExpected, count: newCount });
}
function add(
...args: { id: string; prob: number; count: [number, number] }[]
) {
args.forEach(addOne);
}
function normalizeContainerItem(id: string | { item: string }) {
return typeof id === "string" ? id : id.item;
}
if ("container-item" in group && group["container-item"])
add({
id: normalizeContainerItem(group["container-item"]),
prob: 1,
count: [1, 1],
});
let normalizedEntries: ItemGroupEntry[] = [];
for (const entry of "entries" in group && group.entries
? group.entries
: [])
if (Array.isArray(entry))
normalizedEntries.push({ item: entry[0], prob: entry[1] });
else normalizedEntries.push(entry);
for (const item of group.items ?? [])
if (Array.isArray(item))
normalizedEntries.push({ item: item[0], prob: item[1] });
else if (typeof item === "string")
normalizedEntries.push({ item, prob: 100 });
else normalizedEntries.push(item);
for (const g of "groups" in group && group.groups ? group.groups : [])