import { Builder, parseDelimiters, resolve } from "./string_utils.js";
import { createCharacterName as ccn } from "./create_character_name.js";
import { logger } from "./utils.js";
import { mapLoader, percentTable, rarityTable } from "./data_loaders.js";
import { random, roll, test } from "./random_utils.js";
import RarityTable from "./tables/rarity_table.js";
import Table from "./tables/table.js";
const REF_STRING = "ref-";
const SEQ_STRING = "seq-";
// refer to a sequence, but do not increment it
const REF_REGEX = /\{ref-[^\}]+\}/g;
// refer to a sequence, and then increment it
const SEQ_REGEX = /\{seq-[^\}]+\}/g;
const map = await mapLoader("location.names.data");
const GEO_FEATURE_TYPES = {
Depression: map.get("features.depression"),
Prairie: map.get("features.prairie"),
Hill: map.get("features.hill"),
Water: map.get("features.water"),
Lake: map.get("features.lake"),
River: map.get("features.river"),
Junction: map.get("features.junction"),
Forest: map.get("features.forest"),
};
const RIVER_FORKS = map.get("features.river.forks");
const NATURAL_PLACE_NOUN = map.get("natural.place.noun");
const NATURAL_PLACE_ADJECTIVES = map.get("natural.place.adjectives");
const CTY_DESCRIPTORS = map.get("city.descriptors");
const CTY_NAMES = map.get("city.names");
const COMMUNITY_SUFFIXES = map.get("community.suffixes");
const COMMUNITY_PLACE_NAME = map.get("community.names");
const STREET_TYPES = map.get("street.types");
const DIRS = map.get("street.dirs");
const LOC_TYPE_NAMES = map.get("location.types");
const LODGING_NAMES = map.get("lodging.names");
const CORP_NAMES_1 = map.get("corp.names.1");
const CORP_NAMES_2 = map.get("corp.names.2");
const CORP_NAMES_3 = map.get("corp.names.3");
const CORP_NAMES_4 = map.get("corp.names.4");
const CORP_NAMES_5 = map.get("corp.names.5");
const BAR_NAMES = Object.freeze({
"clientele:lobrow": map.get("bars.lobrow.names"),
"clientele:nobrow": map.get("bars.nobrow.names"),
"clientele:hibrow": map.get("bars.hibrow.names"),
});
const BAR_TYPES = Object.freeze({
"clientele:lobrow": map.get("bars.lobrow.types"),
"clientele:nobrow": map.get("bars.nobrow.types"),
"clientele:hibrow": map.get("bars.hibrow.types"),
});
const RESTAURANT_NAMES = map.get("restaurant.names");
const RESTAURANT_TYPES = rarityTable(map.get("restaurant.types"));
const RESTAURANTS = new RarityTable()
.add("common", () => `${random(RESTAURANT_NAMES)}`)
.add("common", () => `${random(RESTAURANT_NAMES)} ${RESTAURANT_TYPES.get()}`)
.add("rare", ({ owner }) => `${fullOrPartialName(owner, true)} ${RESTAURANT_TYPES.get()}`);
const HOTEL_TYPES = rarityTable(map.get("hotel.types"));
const MOTEL_TYPES = rarityTable(map.get("motel.types"));
const CLIENTELE = Object.freeze(Object.keys(BAR_NAMES));
// RANDOMIZATION TABLES
const NATURAL_AREAS = new RarityTable()
// East Pond
.add("common", () => random(NATURAL_PLACE_ADJECTIVES))
// Red Hollow
.add("common", () => random(NATURAL_PLACE_NOUN))
// Williams Crossing
.add("uncommon", () => getName())
// West Bison Lake
.add("uncommon", (loc) => regionByLocation(loc) + " " + random(NATURAL_PLACE_NOUN))
// Ford Trail Pond
.add("rare", () => (test(50) ? random(NATURAL_PLACE_NOUN) : getName()) + " Trail")
// Alfalfa
.add("rare", () => random(CTY_NAMES))
// West Anderson Junction
.add("rare", (loc) => regionByLocation(loc) + " " + getName());
const MOTELS = new Table();
MOTELS.add(70, () => `${random(LODGING_NAMES)} ${MOTEL_TYPES.get()}`);
MOTELS.add(15, () => `${MOTEL_TYPES.get()} ${random(LODGING_NAMES)}`);
MOTELS.add(10, ({ owner }) => `${fullOrPartialName(owner, false)} ${MOTEL_TYPES.get()}`);
MOTELS.add(5, ({ owner }) => `${fullOrPartialName(owner, true)} ${MOTEL_TYPES.get()}`);
const HOTELS = new Table();
HOTELS.add(70, () => `${random(LODGING_NAMES)} ${HOTEL_TYPES.get()}`);
HOTELS.add(15, () => `${HOTEL_TYPES.get()} ${random(LODGING_NAMES)}`);
HOTELS.add(10, ({ owner }) => `${fullOrPartialName(owner, false)} ${HOTEL_TYPES.get()}`);
HOTELS.add(5, ({ owner }) => `${fullOrPartialName(owner, true)} ${HOTEL_TYPES.get()}`);
const MOBILE_PARK_TYPES = percentTable(map.get("mobile.park.types"));
// add suburban names too
const CORP_1 = new Table();
CORP_1.add(10, () => random(CORP_NAMES_1));
CORP_1.add(10, () => random(CORP_NAMES_2));
CORP_1.add(50, () => `${random(CORP_NAMES_1)} ${random(CORP_NAMES_2)}`);
CORP_1.add(15, (o) => `${o.family} ${random(CORP_NAMES_2)}`);
CORP_1.add(15, (o) => o.family);
const CORP_2 = new Table();
CORP_2.add(25, () => ` ${random(CORP_NAMES_3)}`);
CORP_2.add(25, () => ` ${random(CORP_NAMES_4)}`);
CORP_2.add(50, () => ` ${random(CORP_NAMES_3)} ${random(CORP_NAMES_4)}`);
const CORP_3 = new Table();
CORP_3.add(90, () => `${CORP_1.get()} ${CORP_2.get()}`);
CORP_3.add(10, () => `${random(CORP_NAMES_5)} ${random(CORP_NAMES_4)}`);
const RESEARCH_FACILITY_TYPE = "{Research|Lab|Labs}{| Facility| Facilities| Division}";
const BARS = new Table({ outFunction: (f) => f() });
BARS.add(5, () => `${createPlaceName()} ${random(BAR_TYPES["clientele:nobrow"])}`);
BARS.add(5, () => `The ${fullOrPartialName(ccn(), true)} ${random(BAR_TYPES["clientele:nobrow"])}`);
BARS.add(
10,
() => `The ${fullOrPartialName(ccn(), false)} ${random(BAR_TYPES["clientele:nobrow"])}`,
);
BARS.add(
80,
() => `${random(BAR_NAMES[random(CLIENTELE)])} ${random(BAR_TYPES["clientele:nobrow"])}`,
);
function getBarName(parent) {
if (parent.type === "Casino") {
return `${random(BAR_NAMES[random("clientele:hibrow")])} ${random(
BAR_TYPES["clientele:hibrow"],
)}`;
}
return BARS.get();
}
const STREET_NAMES = new Table({ outFunction: (f) => f() });
STREET_NAMES.add(80, () => `${random(CTY_DESCRIPTORS)} ${random(STREET_TYPES)}`);
STREET_NAMES.add(20, () => `${random(CTY_DESCRIPTORS)} ${random(STREET_TYPES)} ${random(DIRS)}`);
// UTILITIES
function regionByLocation(location) {
return random(location === "River" && test(70) ? RIVER_FORKS : NATURAL_PLACE_ADJECTIVES);
}
function getName() {
const name = ccn();
return test(10) ? name.given : name.family;
}
function fullOrPartialName(owner, possessive) {
const p = /[sz]$/.test(owner.toString()) ? "’" : "’s";
const name = test(70) ? owner.family : owner.toString();
return possessive ? name + p : name;
}
function nameHierarchy(start, defaultFunc) {
let array = [];
for (let n = start; n != null; n = n.parent) {
if (n.name) {
array.push(n.name);
}
}
if (array.length === 0) {
array.push(defaultFunc());
}
return array;
}
// EXPORT FUNCTIONS
export function getLocationNameTypes() {
return LOC_TYPE_NAMES;
}
function geoFeature({ type = random(Object.keys(GEO_FEATURE_TYPES)) } = {}) {
return random(GEO_FEATURE_TYPES[type]);
}
function createHousingTractName() {
const b = new Builder();
b.if(test(80), random(CTY_DESCRIPTORS), geoFeature());
b.if(test(30), random(COMMUNITY_SUFFIXES));
b.if(test(20), " " + geoFeature());
b.if(test(70), " " + random(COMMUNITY_PLACE_NAME));
b.preIf(test(30) && b.toString().includes("*"), "The ");
b.if(b.length === 1, random(COMMUNITY_SUFFIXES));
return b.toString().replace("*", "");
}
function createStreetName() {
return STREET_NAMES.get();
}
function createHouseName({ parent } = {}) {
const names = nameHierarchy(parent, createStreetName);
if (!parent.streetNumber) {
parent.streetNumber = roll("1d20") * random([100, 100]) + roll("1d9*10");
}
parent.streetNumber += random([2, 3, 4, 5]);
return `${parent.streetNumber} ${names[0]}`;
}
function createPlaceName({ type = random(Object.keys(GEO_FEATURE_TYPES)) } = {}) {
let name = random(NATURAL_AREAS.get());
if (name.startsWith("*")) {
return name.substring(1);
}
return name + " " + random(GEO_FEATURE_TYPES[type]);
}
function createCorporateName({ owner }) {
let oneName = null;
do {
oneName = CORP_3.get()(owner);
} while (oneName.split(" ").length > 4);
return oneName.replace(/_/g, " ");
}
function createHighway() {
// Interstate 50, Interstate 60, Interstate 23, Interstate 27
// "U.S. Route {50|60|23|27}"
return resolve("{Highway|U.S. Route} {2|3|4|5|6|7|8|9}{0|1|2|3|4|5|6|7|8|9}");
}
function createLocationNameByType({ type = random(getLocationNameTypes()), parent = {} } = {}) {
switch (type) {
case "prairie": // TODO: REMOVEME?
throw new Error("Why is this here?");
break;
case "Forest":
case "Prairie":
case "Hill":
case "Lake":
case "River":
return createPlaceName({ type });
case "Highway":
return createHighway();
case "Mobile Home Park":
return random(LODGING_NAMES) + " " + MOBILE_PARK_TYPES.get();
case "Motel":
return MOTELS.get()({ owner: ccn() });
case "Hotel":
return HOTELS.get()({ owner: ccn() });
case "Restaurant":
return RESTAURANTS.get()({ owner: ccn() });
case "Bar":
case "Post Bar":
return getBarName(parent);
case "Business Headquarters":
return createCorporateName({ owner: ccn() });
case "Industrial Research Facility":
return createCorporateName({ owner: ccn() }) + " " + random(RESEARCH_FACILITY_TYPE);
case "Housing Tract":
return createHousingTractName();
case "Street":
return createStreetName();
case "House":
return createHouseName({ parent });
default:
return null;
}
}
function nameInSequence(child) {
let selfName = child.name;
// e.g. "{pigsty|hogswallow}" takes precedence over a sequence information demarcated with braces
if (selfName.includes("|")) {
return resolve(selfName);
}
selfName = replaceSeq(child, selfName, REF_STRING);
selfName = replaceSeq(child, selfName, SEQ_STRING);
// don't do the inline sequence if we've managed to replace a sequence in the string
if (selfName === child.name) {
selfName = replaceInlineSeq(child, selfName);
}
return selfName;
}
function replaceSeq(child, selfName, indicator) {
// work through all indicators for references or sequences
while (selfName.includes(`{${indicator}`)) {
const regexp = indicator === REF_STRING ? REF_REGEX : SEQ_REGEX;
// get all syntax for the types
const allI = selfName.match(regexp);
allI.forEach((i) => {
// extract the id from the reference, e.g r8 == id of 8
const id = i.split("-")[1].replace("}", "");
const seqData = getSequence(child, id);
// If there's no sequence data, we will substitute in the type, if it's not already part of
// the name (if it's part of the name, we remove the sequence information by just replacing
// the whole name string with the type.
if (!seqData) {
if (selfName.indexOf(child.type) === -1) {
selfName = selfName.replace(i, child.type);
} else {
selfName = child.type;
}
return;
}
const seq =
map.get("seq." + seqData.seqType) || seqData.seqType.split(",").map((s) => s.trim());
// nonsense around matching the right index and/or advancing for the s case. If the index is -1,
// the sequence hasn't been referenced in that path of location creation, so we can use the value
// "" for it. This is a little too magical but currently works where we use it.
const index = indicator === REF_STRING ? seqData.index - 1 : seqData.index;
const seqValue = index === -1 ? "" : seq[index % seq.length];
selfName = selfName.replace(i, seqValue);
if (indicator === SEQ_STRING) {
seqData.index++;
}
});
}
return selfName;
}
// The sequence was defined alongside the definition of child nodes, and is in the sequence itself.
function replaceInlineSeq(child, selfName) {
const seqData = child.parent?.sequences?.find((seq) => seq.id === child.type);
if (!seqData || !seqData.options) {
return selfName;
}
selfName = seqData.options[seqData.index % seqData.options.length];
seqData.index++;
return selfName;
}
/**
* Generates a name for a location node based on its type and its position in the location hierarchy.
* Supports sequence-based naming (e.g. "Room 1", "Room 2") and type-specific name generation
* (e.g. street names, building names, geographic features).
*
* @param {Object} [options={}] - Location name options
* @param {Object} options.child - The location node to name, with `type` (string) and `parent` (Object)
* properties representing its place in the location hierarchy.
* @returns {string} A generated name for the location node
*/
export function createLocationName({ child } = {}) {
logger.start("createLocationName", { child });
let name =
createLocationNameByType({ type: child.type, parent: child.parent }) || nameInSequence(child);
return logger.end(name);
}
function getSequence(location, id) {
for (let n = location; n != null; n = n.parent) {
if (n.sequences?.length && n.sequences.some((seq) => seq.id === id)) {
return n.sequences.find((seq) => seq.id === id);
}
}
return null;
}