just took a big shit on that thing, packer complete, please god kill me 1000+ changes :))))))))))

This commit is contained in:
2026-10-22 11:38:48 +02:00
parent 379b6203cd
commit 1a4fd6b31e
556 changed files with 10810 additions and 462 deletions
+685
View File
@@ -0,0 +1,685 @@
/**
* config-gen.ts — merge scan + encode results + user overrides into a
* final CharacterConfig.
*
* The output shape matches the shimejic library's `CharacterConfig` type.
* Every field is either explicit (from user's `character.config.json`),
* inferred from the folder structure (scan result), or defaulted with a
* warning.
*
* Atlas URLs point at the encoded WebP filenames:
*
* atlases/<atlasId>.<atlasHash>.webp
*
* Consumers fetch `<config>`, then resolve atlas URLs relative to the
* config file's location.
*
* Frame names within clips match the original filename (with extension
* for state frames, without for icons). Consumers look up frames by
* these names in the atlas definition.
*
* Errors are accumulated, not thrown. Missing required config (look
* distance, bubble dimensions) errors. Missing optional config (voice,
* text, timing) uses library defaults silently.
*/
import type {
AtlasDefinition,
BubbleDefinition,
CharacterConfig,
ClipDefinition,
EventDefinition,
FrameRegion,
IconDefinition,
LookDefinition,
LookSectorDefinition,
StateDefinition,
TextDefinition,
TimingDefinition,
VoiceDefinition,
} from "shimejic";
import type { EncodedAtlas } from "./encode.js";
import type { ScanResult, ScannedState } from "./scan.js";
/* ------------------------------------------------------------------ */
/* Packer input config (character.config.json) */
/* ------------------------------------------------------------------ */
export interface StateConfig {
base?: {
framerate?: number;
loop?: boolean;
};
look?: {
pivot: { x: number; y: number };
distance: { min: number; max: number };
hysteresis?: number;
sectors?: Record<
string,
{
minAngle: number;
maxAngle: number;
minDistance?: number;
maxDistance?: number;
}
>;
};
events?: Record<
string,
{
framerate?: number;
chance?: number;
interval?: [number, number];
cooldown?: number;
weight?: number;
interrupt?: "cut" | "finish";
chatter?: Array<{
at: number;
unit: "frame" | "ms";
text: string;
}>;
}
>;
}
export interface BubblePackConfig {
width: number;
height: number;
framerate?: number;
anchorX?: number;
anchorY?: number;
frameMode?: "loop" | "hold" | "reverse-on-dismiss";
text?: Partial<TextDefinition>;
}
export interface PackerConfig {
id?: string;
initialState?: string;
spawnState?: string;
defaults?: {
framerate?: number;
clipLoop?: boolean;
};
states?: Record<string, StateConfig>;
bubbles?: Record<string, BubblePackConfig>;
text?: Partial<TextDefinition>;
timing?: Partial<TimingDefinition>;
voice?: VoiceDefinition;
}
/* ------------------------------------------------------------------ */
/* Constants */
/* ------------------------------------------------------------------ */
const COMPASS_ANGLES: Record<string, [number, number]> = {
t: [337.5, 22.5],
tr: [22.5, 67.5],
r: [67.5, 112.5],
br: [112.5, 157.5],
b: [157.5, 202.5],
bl: [202.5, 247.5],
l: [247.5, 292.5],
tl: [292.5, 337.5],
up: [337.5, 22.5],
"up-right": [22.5, 67.5],
right: [67.5, 112.5],
"down-right": [112.5, 157.5],
down: [157.5, 202.5],
"down-left": [202.5, 247.5],
left: [247.5, 292.5],
"up-left": [292.5, 337.5],
};
const DEFAULT_FRAMERATE = 8;
const DEFAULT_CLIP_LOOP = true;
const DEFAULT_HYSTERESIS = 1;
const DEFAULT_EVENT_CHANCE = 0.4;
const DEFAULT_EVENT_INTERVAL: [number, number] = [4, 10];
const DEFAULT_EVENT_COOLDOWN = 6;
const DEFAULT_EVENT_WEIGHT = 1;
const DEFAULT_EVENT_INTERRUPT = "cut" as const;
/* ------------------------------------------------------------------ */
/* Result types */
/* ------------------------------------------------------------------ */
export interface ConfigGenInput {
scanned: ScanResult;
encoded: Map<string, EncodedAtlas>;
overrides: PackerConfig | null;
/** Fallback id if overrides don't specify one. Typically the input folder's basename. */
fallbackId: string;
}
export interface ConfigGenResult {
config: CharacterConfig | null;
warnings: string[];
errors: Array<{ path: string; message: string }>;
}
/* ------------------------------------------------------------------ */
/* Main entry */
/* ------------------------------------------------------------------ */
export function generateConfig(input: ConfigGenInput): ConfigGenResult {
const warnings: string[] = [];
const errors: Array<{ path: string; message: string }> = [];
// Scanned errors propagate directly
for (const err of input.scanned.errors) {
errors.push({ path: err.path, message: err.message });
}
warnings.push(...input.scanned.warnings);
if (errors.length > 0) {
return { config: null, warnings, errors };
}
const overrides = input.overrides ?? {};
const defaults = {
framerate: overrides.defaults?.framerate ?? DEFAULT_FRAMERATE,
clipLoop: overrides.defaults?.clipLoop ?? DEFAULT_CLIP_LOOP,
};
const id = overrides.id ?? input.fallbackId;
const initialState = resolveInitialState(input.scanned, overrides, warnings, errors);
if (initialState === null) {
return { config: null, warnings, errors };
}
const spawnState = resolveSpawnState(input.scanned, overrides, errors);
const atlases = buildAtlases(input.scanned, input.encoded, errors);
const states = buildStates(input.scanned, overrides, defaults, atlases, warnings, errors);
const bubbles = buildBubbles(input.scanned, overrides, input.encoded, errors);
const icons = buildIcons(input.scanned);
if (errors.length > 0) {
return { config: null, warnings, errors };
}
const config: CharacterConfig = {
version: 1,
id,
initialState,
atlases,
states,
bubbles,
...(spawnState !== null && { spawnState }),
...(icons !== undefined && { icons }),
...(overrides.text !== undefined && { text: overrides.text }),
...(overrides.timing !== undefined && { timing: overrides.timing }),
...(overrides.voice !== undefined && { voice: overrides.voice }),
};
return { config, warnings, errors };
}
/* ------------------------------------------------------------------ */
/* Top-level resolution */
/* ------------------------------------------------------------------ */
function resolveInitialState(
scanned: ScanResult,
overrides: PackerConfig,
warnings: string[],
errors: Array<{ path: string; message: string }>,
): string | null {
if (overrides.initialState !== undefined) {
if (!scanned.states.has(overrides.initialState)) {
errors.push({
path: "initialState",
message: `Config refers to unknown state "${overrides.initialState}". Available states: ${[...scanned.states.keys()].join(", ") || "(none)"}.`,
});
return null;
}
return overrides.initialState;
}
const stateNames = [...scanned.states.keys()].sort();
if (stateNames.length === 0) {
errors.push({
path: "states",
message: "No states found. Character must have at least one state.",
});
return null;
}
const first = stateNames[0]!;
warnings.push(
`initialState defaulted to "${first}" (first alphabetically). Set "initialState" in character.config.json to override.`,
);
return first;
}
function resolveSpawnState(
scanned: ScanResult,
overrides: PackerConfig,
errors: Array<{ path: string; message: string }>,
): string | null {
if (overrides.spawnState === undefined) return null;
if (!scanned.states.has(overrides.spawnState)) {
errors.push({
path: "spawnState",
message: `Config refers to unknown state "${overrides.spawnState}".`,
});
return null;
}
return overrides.spawnState;
}
/* ------------------------------------------------------------------ */
/* Atlases */
/* ------------------------------------------------------------------ */
function buildAtlases(
scanned: ScanResult,
encoded: Map<string, EncodedAtlas>,
errors: Array<{ path: string; message: string }>,
): Record<string, AtlasDefinition> {
const result: Record<string, AtlasDefinition> = {};
for (const [id, scannedAtlas] of scanned.atlases) {
const encodedAtlas = encoded.get(id);
if (encodedAtlas === undefined) {
errors.push({
path: scannedAtlas.sourcePath,
message: `Atlas "${id}" was scanned but failed to encode.`,
});
continue;
}
const frames: Record<string, FrameRegion> = {};
for (const frame of scannedAtlas.frames) {
// For state frames, name includes .png extension (as it appears
// on disk). For icons, name has no extension (semantic identifier).
frames[frame.name] = {
x: 0, // placeholder — filled below from packed frames
y: 0,
w: frame.width,
h: frame.height,
};
}
// Overwrite with actual packed positions from the packed atlas.
// We don't have direct access to PackedAtlas here — only EncodedAtlas,
// which has dimensions and hash but not per-frame positions. So we
// recompute positions using the same grid math as pack.ts.
//
// Both pack.ts and config-gen use the same formula, so they stay
// in sync as long as the formula is stable. If pack.ts ever gains
// a new strategy (MaxRects for trim), this duplication must be
// eliminated by threading the PackedAtlas through.
const n = scannedAtlas.frames.length;
const cols = Math.ceil(Math.sqrt(n));
const cellW = scannedAtlas.width;
const cellH = scannedAtlas.height;
for (let i = 0; i < scannedAtlas.frames.length; i++) {
const frame = scannedAtlas.frames[i]!;
const col = i % cols;
const row = Math.floor(i / cols);
frames[frame.name] = {
x: col * cellW,
y: row * cellH,
w: cellW,
h: cellH,
};
}
result[id] = {
url: `atlases/${id}.${encodedAtlas.atlasHash}.webp`,
width: encodedAtlas.width,
height: encodedAtlas.height,
frames,
};
}
return result;
}
/* ------------------------------------------------------------------ */
/* States */
/* ------------------------------------------------------------------ */
interface Defaults {
framerate: number;
clipLoop: boolean;
}
function buildStates(
scanned: ScanResult,
overrides: PackerConfig,
defaults: Defaults,
atlases: Record<string, AtlasDefinition>,
warnings: string[],
errors: Array<{ path: string; message: string }>,
): Record<string, StateDefinition> {
const result: Record<string, StateDefinition> = {};
for (const [stateName, scannedState] of scanned.states) {
const stateOverrides = overrides.states?.[stateName] ?? {};
const built = buildState(stateName, scannedState, stateOverrides, defaults, atlases, scanned, warnings, errors);
if (built !== null) {
result[stateName] = built;
}
}
return result;
}
function buildState(
stateName: string,
scannedState: ScannedState,
stateOverrides: StateConfig,
defaults: Defaults,
atlases: Record<string, AtlasDefinition>,
scanned: ScanResult,
warnings: string[],
errors: Array<{ path: string; message: string }>,
): StateDefinition | null {
const baseAtlas = atlases[scannedState.baseAtlasId];
if (baseAtlas === undefined) {
errors.push({
path: `states.${stateName}.base`,
message: `Atlas "${scannedState.baseAtlasId}" is missing from encoded atlases.`,
});
return null;
}
const baseFrames = Object.keys(baseAtlas.frames);
const baseClip: ClipDefinition = {
atlas: scannedState.baseAtlasId,
frames: baseFrames,
framerate: stateOverrides.base?.framerate ?? defaults.framerate,
loop: stateOverrides.base?.loop ?? defaults.clipLoop,
};
const state: StateDefinition = { base: baseClip };
// Look sectors
if (scannedState.lookSectors.size > 0) {
const look = buildLook(stateName, scannedState, stateOverrides.look, atlases, baseFrames.length, errors);
if (look !== null) state.look = look;
}
// Events
if (scannedState.events.size > 0) {
const events = buildEvents(stateName, scannedState, stateOverrides.events, defaults, atlases, errors);
if (events.length > 0) state.events = events;
}
return state;
}
function buildLook(
stateName: string,
scannedState: ScannedState,
lookOverrides: StateConfig["look"],
atlases: Record<string, AtlasDefinition>,
baseFrameCount: number,
errors: Array<{ path: string; message: string }>,
): LookDefinition | null {
if (lookOverrides === undefined) {
errors.push({
path: `states.${stateName}.look`,
message: `State "${stateName}" has look sectors on disk but no "look" config. Add "states.${stateName}.look" with pivot and distance to character.config.json.`,
});
return null;
}
if (typeof lookOverrides.pivot?.x !== "number" || typeof lookOverrides.pivot?.y !== "number") {
errors.push({
path: `states.${stateName}.look.pivot`,
message: `"look.pivot" must have numeric x and y.`,
});
return null;
}
if (typeof lookOverrides.distance?.min !== "number" || typeof lookOverrides.distance?.max !== "number") {
errors.push({
path: `states.${stateName}.look.distance`,
message: `"look.distance" must have numeric min and max.`,
});
return null;
}
const sectors: LookSectorDefinition[] = [];
for (const [sectorName, sectorAtlasId] of scannedState.lookSectors) {
const sectorAtlas = atlases[sectorAtlasId];
if (sectorAtlas === undefined) {
errors.push({
path: `states.${stateName}.look.sectors.${sectorName}`,
message: `Atlas "${sectorAtlasId}" for sector "${sectorName}" is missing.`,
});
continue;
}
const frames = Object.keys(sectorAtlas.frames);
const explicitAngles = lookOverrides.sectors?.[sectorName];
const compassAngles = COMPASS_ANGLES[sectorName];
const angles = explicitAngles
? ([explicitAngles.minAngle, explicitAngles.maxAngle] as [number, number])
: compassAngles;
if (angles === undefined) {
errors.push({
path: `states.${stateName}.look.sectors.${sectorName}`,
message: `Sector "${sectorName}" has no angles in config, and "${sectorName}" is not a compass direction (t, tr, r, br, b, bl, l, tl or up, up-right, etc.). Add angles to character.config.json.`,
});
continue;
}
const sector: LookSectorDefinition = {
minAngle: angles[0],
maxAngle: angles[1],
folder: sectorName,
atlas: sectorAtlasId,
frames,
};
if (explicitAngles?.minDistance !== undefined || explicitAngles?.maxDistance !== undefined) {
if (explicitAngles?.minDistance === undefined || explicitAngles?.maxDistance === undefined) {
errors.push({
path: `states.${stateName}.look.sectors.${sectorName}`,
message: `Sector "${sectorName}" specifies only one of minDistance/maxDistance. Both must be set or both omitted.`,
});
continue;
}
if (explicitAngles.minDistance > explicitAngles.maxDistance) {
errors.push({
path: `states.${stateName}.look.sectors.${sectorName}`,
message: `Sector "${sectorName}" has minDistance (${explicitAngles.minDistance}) greater than maxDistance (${explicitAngles.maxDistance}).`,
});
continue;
}
sector.minDistance = explicitAngles.minDistance;
sector.maxDistance = explicitAngles.maxDistance;
}
sectors.push(sector);
}
// One final check: base frame count matches sector frame counts
for (const sector of sectors) {
if (sector.frames.length !== baseFrameCount) {
errors.push({
path: `states.${stateName}.look.sectors.${sector.folder}`,
message: `Sector "${sector.folder}" has ${sector.frames.length} frames, base has ${baseFrameCount}. Frame counts must match.`,
});
}
}
return {
pivot: lookOverrides.pivot,
distance: lookOverrides.distance,
hysteresis: lookOverrides.hysteresis ?? DEFAULT_HYSTERESIS,
sectors,
};
}
function buildEvents(
stateName: string,
scannedState: ScannedState,
eventOverrides: StateConfig["events"],
defaults: Defaults,
atlases: Record<string, AtlasDefinition>,
errors: Array<{ path: string; message: string }>,
): EventDefinition[] {
const result: EventDefinition[] = [];
for (const [eventName, eventAtlasId] of scannedState.events) {
const eventAtlas = atlases[eventAtlasId];
if (eventAtlas === undefined) {
errors.push({
path: `states.${stateName}.events.${eventName}`,
message: `Atlas "${eventAtlasId}" for event "${eventName}" is missing.`,
});
continue;
}
const overrides = eventOverrides?.[eventName] ?? {};
const event: EventDefinition = {
name: eventName,
atlas: eventAtlasId,
frames: Object.keys(eventAtlas.frames),
framerate: overrides.framerate ?? defaults.framerate,
chance: overrides.chance ?? DEFAULT_EVENT_CHANCE,
interval: overrides.interval ?? DEFAULT_EVENT_INTERVAL,
cooldown: overrides.cooldown ?? DEFAULT_EVENT_COOLDOWN,
weight: overrides.weight ?? DEFAULT_EVENT_WEIGHT,
};
if (overrides.interrupt !== undefined) {
event.interrupt = overrides.interrupt;
} else {
event.interrupt = DEFAULT_EVENT_INTERRUPT;
}
if (overrides.chatter !== undefined) {
event.chatter = overrides.chatter;
}
result.push(event);
}
return result;
}
/* ------------------------------------------------------------------ */
/* Bubbles and icons */
/* ------------------------------------------------------------------ */
function buildBubbles(
scanned: ScanResult,
overrides: PackerConfig,
encoded: Map<string, EncodedAtlas>,
errors: Array<{ path: string; message: string }>,
): Record<string, BubbleDefinition> {
const result: Record<string, BubbleDefinition> = {};
if (scanned.defaultBubbleAtlasId !== null) {
const atlas = encoded.get(scanned.defaultBubbleAtlasId);
if (atlas !== undefined) {
const packOverrides = overrides.bubbles?.default;
if (packOverrides === undefined) {
errors.push({
path: "bubbles.default",
message: `Default bubble pack has no dimensions in config. Add "bubbles.default" with width and height to character.config.json.`,
});
} else {
const bubble: BubbleDefinition = {
atlas: scanned.defaultBubbleAtlasId,
frames: getAtlasFrameNames(scanned, scanned.defaultBubbleAtlasId),
width: packOverrides.width,
height: packOverrides.height,
};
applyBubbleExtras(bubble, packOverrides);
result.default = bubble;
}
}
}
for (const [packName, pack] of scanned.bubblePacks) {
const atlas = encoded.get(pack.atlasId);
if (atlas === undefined) continue;
const packOverrides = overrides.bubbles?.[packName];
if (packOverrides === undefined) {
errors.push({
path: `bubbles.${packName}`,
message: `Bubble pack "${packName}" has no dimensions in config. Add "bubbles.${packName}" with width and height to character.config.json.`,
});
continue;
}
const bubble: BubbleDefinition = {
atlas: pack.atlasId,
frames: getAtlasFrameNames(scanned, pack.atlasId),
width: packOverrides.width,
height: packOverrides.height,
};
applyBubbleExtras(bubble, packOverrides);
result[packName] = bubble;
}
return result;
}
function applyBubbleExtras(bubble: BubbleDefinition, overrides: BubblePackConfig): void {
if (overrides.framerate !== undefined) bubble.framerate = overrides.framerate;
if (overrides.anchorX !== undefined) bubble.anchorX = overrides.anchorX;
if (overrides.anchorY !== undefined) bubble.anchorY = overrides.anchorY;
if (overrides.frameMode !== undefined) bubble.frameMode = overrides.frameMode;
if (overrides.text !== undefined) bubble.text = overrides.text;
}
function buildIcons(scanned: ScanResult): Record<string, IconDefinition> | undefined {
const result: Record<string, IconDefinition> = {};
let hasAny = false;
// Shared icons → key = icon name (e.g. "heart")
if (scanned.sharedIconAtlasId !== null) {
const atlas = scanned.atlases.get(scanned.sharedIconAtlasId);
if (atlas !== undefined) {
for (const frame of atlas.frames) {
result[frame.name] = {
atlas: scanned.sharedIconAtlasId,
frames: [frame.name],
};
hasAny = true;
}
}
}
// Per-pack icons → key = "<pack>/<icon>" (e.g. "sneeze/sparkle")
for (const [packName, pack] of scanned.bubblePacks) {
if (pack.iconAtlasId === null) continue;
const atlas = scanned.atlases.get(pack.iconAtlasId);
if (atlas === undefined) continue;
for (const frame of atlas.frames) {
result[`${packName}/${frame.name}`] = {
atlas: pack.iconAtlasId,
frames: [frame.name],
};
hasAny = true;
}
}
return hasAny ? result : undefined;
}
/* ------------------------------------------------------------------ */
/* Helpers */
/* ------------------------------------------------------------------ */
function getAtlasFrameNames(scanned: ScanResult, atlasId: string): string[] {
const atlas = scanned.atlases.get(atlasId);
if (atlas === undefined) return [];
return atlas.frames.map(f => f.name);
}