Refactoring round 7: split BehaviorSystem, fewer copies (#85)
Recurring cleanup round over the code since round 6 (056a622), 105
commits. Behaviour is unchanged. Duplicated code in src went from 29
clones with 229 lines (0.32 %) to 14 clones with 109 lines (0.15 %),
measured with jscpd and the same settings as round 6.
- BehaviorSystem.ts shrinks from 941 to 589 lines. Collecting the
pulses (keys, timers, collisions, animations) moved to
behaviorPulses.ts. The NodeContext the nodes receive moved to
behaviorContext.ts. Imports from outside stay the same, TimeScaled
is still exported from BehaviorSystem.ts.
- PointKindButton and drawPointGrip replace the "Point:" button with
its menu and the point and handle drawing that the curve and the
vector art tab each had on their own.
- lerpVec, cubicAt and splitCubic in src/core/util/vec.ts replace four
copies of the cubic curve and two de Casteljau splits.
- mapNested in Properties.ts is the one walk over lists and structs
that liveObjects and objectRefs did separately. withFieldRenamed
and withoutField replace three copies of renaming a struct field
and two of removing one.
- jsonBody and staleRevision build the JSON body and turn a 409 into
StaleRevisionError for all stores. The auth store turns a 401 into
its error in one place.
- Smaller helpers: structAssetFrom for the two "Make struct type"
commands, shownObject in the inspector, selectedItem for the size
gizmo and the polygon corners, solidTiles in the tilemap collision,
requireVariablesAsset and requireBehaviorVariable.
- Left as is on purpose: the plain forwarding from the collision and
physics systems to Solids, the pointer wiring of the canvases and
the identical last lines of the two make commands.
- Removed unused code: tilemapTileIds and tilemapsUsing were never
called since #128 and #131. EditorState.runtimeProject became unused
with GameRun in #266. The assetId getter of the make commands was
read only by a test.
- 60 values used only in their own file lost their export. The shader
and particle node catalogues stay exported as in round 6.
- Five comments that told history now describe the current state. The
doc comment of BehaviorSystem sits on the class again.
- README lists the struct, clip area and curve assets and mentions the
game link from #266.
Findings:
- Deleting a tile that is painted on a tilemap leaves its cells in
place, and they draw nothing. The delete dialog does not mention the
tilemaps. That was probably the job of the unused tilemapsUsing.
Left as is, because fixing it changes behaviour.
- The solid filter for tile surfaces was untested. A bent filter
stayed green. A new test in tests/core/surface.test.ts now fails
against it.
Tests:
- ./check.sh: 195 files, 2815 tests, exit 0 (one test removed with
tilemapsUsing, one added for tile surfaces).
- Full e2e run: ALL PASSED, 1580 checks.
- Smokes jumprun, tetris, actor: 24, 19 and 21 checks, all passed.
The example project files were restored byte for byte afterwards.
- Counter-checks, 12, all fail as expected: 10 in unit tests (among
them mapNested, splitCubic, cubicAt, staleRevision, the stay pulse,
the late timer and the time scale), 2 in the browser (Point button
always enabled fails 47, selectedItem without a hit fails 29).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
dded62b9f9
commit
bc688f3efc
93 files changed
+914
-902
No files matched your search
@@ -15,7 +15,7 @@ import { DEFAULT_PALETTE, PIXEL_CANVAS_DEFAULT } from '../model/pixelart';
|
||||
import { isSoundFile } from '../model/sound';
|
||||
import { removeSubtrees } from '../model/hierarchy';
|
||||
import type { PropertyBag, PropertyValue } from '../model/Properties';
|
||||
import { findAssetOf, objectHolders, type Project } from '../model/Project';
|
||||
import { objectHolders, type Project } from '../model/Project';
|
||||
import {
|
||||
type Scope,
|
||||
scopeOf,
|
||||
@@ -29,7 +29,7 @@ import { isTextureFile } from '../model/texture';
|
||||
import { coerceValue, defaultsFor, initialOf, initialPropsFor } from '../properties/PropertySchema';
|
||||
import { type Removed, removeById, removeFirst, restoreAt } from '../util/list';
|
||||
import { type Command, CommandError } from './Command';
|
||||
import { requireAsset, requirePropDef, requireStateMachine } from './require';
|
||||
import { requireAsset, requirePropDef, requireStateMachine, requireVariablesAsset } from './require';
|
||||
import { SetBagValueCommand } from './SetBagValueCommand';
|
||||
|
||||
export function buildAsset(type: AssetType, name: string, id = newId()): Asset {
|
||||
@@ -314,19 +314,13 @@ export class SetVariablesPersistentCommand implements Command {
|
||||
}
|
||||
|
||||
execute(project: Project): void {
|
||||
const asset = this.target(project);
|
||||
const asset = requireVariablesAsset(project, this.assetId);
|
||||
this.previous = asset.persistent === true;
|
||||
setPersistent(asset, this.persistent);
|
||||
}
|
||||
|
||||
undo(project: Project): void {
|
||||
setPersistent(this.target(project), this.previous);
|
||||
}
|
||||
|
||||
private target(project: Project): VariablesAsset {
|
||||
const asset = findAssetOf(project, this.assetId, 'variables');
|
||||
if (!asset) throw new CommandError(`Variables ${this.assetId} not found`);
|
||||
return asset;
|
||||
setPersistent(requireVariablesAsset(project, this.assetId), this.previous);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -353,7 +347,7 @@ export class SetVariablesScopeCommand implements Command {
|
||||
}
|
||||
|
||||
execute(project: Project): void {
|
||||
const asset = this.target(project);
|
||||
const asset = requireVariablesAsset(project, this.assetId);
|
||||
this.previous = sharedScopeOf(asset);
|
||||
this.wasPersistent = asset.persistent === true;
|
||||
setSharedScope(asset, this.scope);
|
||||
@@ -361,16 +355,10 @@ export class SetVariablesScopeCommand implements Command {
|
||||
}
|
||||
|
||||
undo(project: Project): void {
|
||||
const asset = this.target(project);
|
||||
const asset = requireVariablesAsset(project, this.assetId);
|
||||
setSharedScope(asset, this.previous);
|
||||
setPersistent(asset, this.wasPersistent);
|
||||
}
|
||||
|
||||
private target(project: Project): VariablesAsset {
|
||||
const asset = findAssetOf(project, this.assetId, 'variables');
|
||||
if (!asset) throw new CommandError(`Variables ${this.assetId} not found`);
|
||||
return asset;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
TilemapAsset,
|
||||
TilemapLayer,
|
||||
VariableOwnerAsset,
|
||||
VariablesAsset,
|
||||
VectorArtAsset,
|
||||
VectorShape,
|
||||
} from '../model/Asset';
|
||||
@@ -131,6 +132,12 @@ export function requireCurve(project: Project, assetId: string): CurveAsset {
|
||||
return asset;
|
||||
}
|
||||
|
||||
export function requireVariablesAsset(project: Project, assetId: string): VariablesAsset {
|
||||
const asset = findAssetOf(project, assetId, 'variables');
|
||||
if (!asset) throw new CommandError(`Variables ${assetId} not found`);
|
||||
return asset;
|
||||
}
|
||||
|
||||
export function requireStateMachine(project: Project, assetId: string): StateMachineAsset {
|
||||
const asset = findAssetOf(project, assetId, 'statemachine');
|
||||
if (!asset) throw new CommandError(`State machine ${assetId} not found`);
|
||||
|
||||
@@ -197,6 +197,18 @@ function variableOfField(field: StructFieldDef, value: PropertyValue | undefined
|
||||
return def;
|
||||
}
|
||||
|
||||
/** A new Struct asset declaring `fields`, each at the value `values` holds for it, named after `name`. */
|
||||
function structAssetFrom(
|
||||
project: Project,
|
||||
fields: readonly StructFieldDef[],
|
||||
values: Readonly<Record<string, PropertyValue>>,
|
||||
name: string,
|
||||
): StructAsset {
|
||||
const variables = fields.map((f) => variableOfField(f, values[f.key]));
|
||||
const props = Object.fromEntries(variables.map((v) => [v.key, v.default]));
|
||||
return { id: newId(), type: 'struct', name: nextAssetName(project, name), props, variables };
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns the fields a struct holds by itself into a Struct asset, and types the struct with it. The
|
||||
* value it holds now becomes the asset's defaults, so the place reads exactly as before.
|
||||
@@ -212,11 +224,6 @@ export class MakeStructTypeCommand implements Command {
|
||||
private readonly path: readonly string[],
|
||||
) {}
|
||||
|
||||
/** The asset made, once the command ran – for the caller to select it. */
|
||||
get assetId(): string {
|
||||
return this.asset?.id ?? '';
|
||||
}
|
||||
|
||||
execute(project: Project): void {
|
||||
const owner = requireVariableOwner(project, this.ownerId);
|
||||
const def = requireStructVariable(project, this.ownerId, this.key);
|
||||
@@ -226,11 +233,8 @@ export class MakeStructTypeCommand implements Command {
|
||||
throw new CommandError('This struct has a type already');
|
||||
if (!this.asset) {
|
||||
const value = valueAt(owner.props[def.key] ?? def.default, this.path);
|
||||
const fields = isStruct(value) ? value : {};
|
||||
const variables = at.fields.map((f) => variableOfField(f, fields[f.key]));
|
||||
const props = Object.fromEntries(variables.map((v) => [v.key, v.default]));
|
||||
const name = nextAssetName(project, this.path.at(-1) ?? this.key);
|
||||
this.asset = { id: newId(), type: 'struct', name, props, variables };
|
||||
const values = isStruct(value) ? value : {};
|
||||
this.asset = structAssetFrom(project, at.fields, values, this.path.at(-1) ?? this.key);
|
||||
}
|
||||
project.assets.push(this.asset);
|
||||
this.rec = new Recorder();
|
||||
@@ -325,10 +329,6 @@ export class MakeListItemTypeCommand implements Command {
|
||||
|
||||
constructor(private readonly target: ListTarget) {}
|
||||
|
||||
get assetId(): string {
|
||||
return this.asset?.id ?? '';
|
||||
}
|
||||
|
||||
execute(project: Project): void {
|
||||
const { def, decl } = requireListDecl(project, this.target);
|
||||
if (decl.itemType && structAssetOf(project, decl.itemType))
|
||||
@@ -344,10 +344,7 @@ export class MakeListItemTypeCommand implements Command {
|
||||
values[field.key] = item[field.key]!;
|
||||
fields.push(field);
|
||||
}
|
||||
const variables = fields.map((f) => variableOfField(f, values[f.key]));
|
||||
const props = Object.fromEntries(variables.map((v) => [v.key, v.default]));
|
||||
const name = nextAssetName(project, this.target.path.at(-1) ?? this.target.key);
|
||||
this.asset = { id: newId(), type: 'struct', name, props, variables };
|
||||
this.asset = structAssetFrom(project, fields, values, this.target.path.at(-1) ?? this.target.key);
|
||||
}
|
||||
project.assets.push(this.asset);
|
||||
this.rec = new Recorder();
|
||||
@@ -370,7 +367,6 @@ function itemFieldDefs(item: StructValue): StructFieldDef[] {
|
||||
return { key, kind, fields: itemFieldDefs(value), ...(typeId ? { structType: typeId } : {}) };
|
||||
}
|
||||
if (kind === 'struct') return { key, kind, fields: [] };
|
||||
if (kind === 'list') return { key, kind };
|
||||
return { key, kind };
|
||||
});
|
||||
}
|
||||
@@ -4,8 +4,11 @@ import {
|
||||
type PropertyBag,
|
||||
type PropertyValue,
|
||||
type StructValue,
|
||||
withFieldRenamed,
|
||||
withoutField,
|
||||
} from '../model/Properties';
|
||||
import {
|
||||
type BehaviorAsset,
|
||||
isKeptVariable,
|
||||
isPrivateVariable,
|
||||
setKeptVariable,
|
||||
@@ -180,6 +183,13 @@ export class RenameVariableCommand extends RenameCommand {
|
||||
}
|
||||
}
|
||||
|
||||
/** The behavior, once it is known to declare `key`. */
|
||||
function requireBehaviorVariable(project: Project, assetId: string, key: string): BehaviorAsset {
|
||||
const asset = requireBehavior(project, assetId);
|
||||
if (!asset.variables.some((v) => v.key === key)) throw new CommandError(`Variable "${key}" not found`);
|
||||
return asset;
|
||||
}
|
||||
|
||||
/** Whether a behavior's variable carries on from one `Run behavior` call to the next (#229). */
|
||||
export class SetVariableKeptCommand implements Command {
|
||||
readonly label: string;
|
||||
@@ -194,9 +204,7 @@ export class SetVariableKeptCommand implements Command {
|
||||
}
|
||||
|
||||
execute(project: Project): void {
|
||||
const asset = requireBehavior(project, this.assetId);
|
||||
if (!asset.variables.some((v) => v.key === this.key))
|
||||
throw new CommandError(`Variable "${this.key}" not found`);
|
||||
const asset = requireBehaviorVariable(project, this.assetId, this.key);
|
||||
this.previous = isKeptVariable(asset, this.key);
|
||||
setKeptVariable(asset, this.key, this.kept);
|
||||
}
|
||||
@@ -224,9 +232,7 @@ export class SetVariablePrivateCommand implements Command {
|
||||
}
|
||||
|
||||
execute(project: Project): void {
|
||||
const asset = requireBehavior(project, this.assetId);
|
||||
if (!asset.variables.some((v) => v.key === this.key))
|
||||
throw new CommandError(`Variable "${this.key}" not found`);
|
||||
const asset = requireBehaviorVariable(project, this.assetId, this.key);
|
||||
this.previous = isPrivateVariable(asset, this.key);
|
||||
setPrivateVariable(asset, this.key, this.hidden);
|
||||
this.overrides = this.hidden ? takeOverrides(project, this.assetId, this.key) : [];
|
||||
@@ -362,19 +368,6 @@ function bagHolder(id: string, optional: boolean, bag: PropertyBag, key: string)
|
||||
return { id, optional, read: () => bag[key], write: (value: PropertyValue) => (bag[key] = value) };
|
||||
}
|
||||
|
||||
function withoutField(value: StructValue, key: string): StructValue {
|
||||
const next: Record<string, FieldValue> = { ...value };
|
||||
delete next[key];
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Rebuilt rather than reassigned, so the field keeps its place in the value as well. */
|
||||
function renameField(value: StructValue, from: string, to: string): StructValue {
|
||||
const next: Record<string, FieldValue> = {};
|
||||
for (const [key, item] of Object.entries(value)) next[key === from ? to : key] = item;
|
||||
return next;
|
||||
}
|
||||
|
||||
export class AddStructFieldCommand implements Command {
|
||||
readonly label: string;
|
||||
|
||||
@@ -471,6 +464,6 @@ export class RenameStructFieldCommand extends RenameCommand {
|
||||
if (fields.some((f) => f.key === to)) throw new CommandError(`Field "${to}" already exists`);
|
||||
owner.setFields(fields.map((f) => (f.key === from ? { ...f, key: to } : f)));
|
||||
for (const site of structSites(project, this.assetId, this.key, this.path))
|
||||
site.write(renameField(site.read(), from, to));
|
||||
site.write(withFieldRenamed(site.read(), from, to));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
isList,
|
||||
isStruct,
|
||||
mapNested,
|
||||
NO_OBJECT,
|
||||
type PropertyBag,
|
||||
type PropertyValue,
|
||||
@@ -111,16 +112,9 @@ function mapObjects(
|
||||
swap: (held: EntityHandle) => unknown,
|
||||
place?: (at: PropertyValue) => unknown,
|
||||
): unknown {
|
||||
if (isEntity(value as Value)) return swap(value as EntityHandle);
|
||||
if (place && tagOf(value) === 'object') return place(value as PropertyValue);
|
||||
if (isList(value)) {
|
||||
const items = value.map((item) => mapObjects(item, swap, place));
|
||||
return items.some((item, i) => item !== value[i]) ? items : value;
|
||||
}
|
||||
if (isStruct(value) && tagOf(value) === undefined) {
|
||||
const entries = Object.entries(value);
|
||||
const mapped = entries.map(([key, field]) => [key, mapObjects(field, swap, place)] as const);
|
||||
return mapped.some(([, field], i) => field !== entries[i]![1]) ? Object.fromEntries(mapped) : value;
|
||||
}
|
||||
return value;
|
||||
return mapNested(value, (part) => {
|
||||
if (isEntity(part as Value)) return swap(part as EntityHandle);
|
||||
if (place && tagOf(part) === 'object') return place(part as PropertyValue);
|
||||
return undefined;
|
||||
});
|
||||
}
|
||||
@@ -22,7 +22,7 @@ export const BEHAVIOR_END = 'BehaviorEnd';
|
||||
export const RUN_BEHAVIOR = 'RunBehavior';
|
||||
export const VARIABLES = 'Variables';
|
||||
export const PROPERTIES = 'Properties';
|
||||
export const ON_START = 'OnStart';
|
||||
const ON_START = 'OnStart';
|
||||
|
||||
export const BEHAVIOR_PARAM = 'behavior';
|
||||
export const VARIABLES_PARAM = 'variablesAsset';
|
||||
|
||||
@@ -26,7 +26,7 @@ const loopPort = (): PortDef => ({
|
||||
* A boolean arriving over an edge is taken literally, which is what wiring a comparison or a
|
||||
* variable into this input is for.
|
||||
*/
|
||||
export function loopChoice(value: Value | undefined): boolean | undefined {
|
||||
function loopChoice(value: Value | undefined): boolean | undefined {
|
||||
if (typeof value === 'boolean') return value;
|
||||
const text = asString(value);
|
||||
if (text === 'true') return true;
|
||||
|
||||
@@ -47,7 +47,7 @@ export const contactOutputs = (): PortDef[] => [
|
||||
export const keyParam: PropertyDef = { key: 'key', label: 'Key', kind: 'key', default: 'ArrowRight' };
|
||||
|
||||
/** No `assetTypes`: any placeable asset is a valid answer here. */
|
||||
export const assetParam: PropertyDef = { key: 'asset', label: 'Asset', kind: 'asset', default: '' };
|
||||
const assetParam: PropertyDef = { key: 'asset', label: 'Asset', kind: 'asset', default: '' };
|
||||
|
||||
/**
|
||||
* The `asset` input of `Spawn` and `Is asset`; unconnected, it shows the asset picker. The key is the
|
||||
|
||||
@@ -14,7 +14,7 @@ export const OBJECT_BEHAVIOR_PARAM = 'objectBehavior';
|
||||
* What a Properties node offers ports from. Textures and scenes are not objects in a running game,
|
||||
* so there is nothing to hand the node for them.
|
||||
*/
|
||||
export const PROPERTY_TARGETS = [
|
||||
const PROPERTY_TARGETS = [
|
||||
'any',
|
||||
'sprite',
|
||||
'text',
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { MachineState, MachineTransition, StateMachine } from './lookup';
|
||||
import type { NodeDef, PortDef, PortSource } from './NodeRegistry';
|
||||
|
||||
export const STATE = 'State';
|
||||
export const STATE_MACHINE = 'StateMachine';
|
||||
const STATE_MACHINE = 'StateMachine';
|
||||
export const STATE_TRANSITION = 'StateTransition';
|
||||
export const STATE_NAME_PARAM = 'name';
|
||||
/** The input naming the machine on `State branch` and `Set state`. */
|
||||
|
||||
@@ -113,7 +113,7 @@ export function findGraphAsset(project: Project, assetId: string): GraphAsset |
|
||||
*/
|
||||
export type ObjectHolder = SceneAsset | ContainerAsset;
|
||||
|
||||
export function isObjectHolder(asset: Asset): asset is ObjectHolder {
|
||||
function isObjectHolder(asset: Asset): asset is ObjectHolder {
|
||||
return asset.type === 'scene' || asset.type === 'container';
|
||||
}
|
||||
|
||||
|
||||
@@ -60,6 +60,38 @@ export function withItemType(value: StructValue, typeId: string): StructValue {
|
||||
return typeId ? { ...fields, [ITEM_TYPE_KEY]: typeId } : fields;
|
||||
}
|
||||
|
||||
export function withoutField(value: StructValue, key: string): StructValue {
|
||||
const { [key]: _dropped, ...rest } = value;
|
||||
return rest;
|
||||
}
|
||||
|
||||
/** Rebuilt rather than reassigned, so the field keeps its place in the value. */
|
||||
export function withFieldRenamed(value: StructValue, from: string, to: string): StructValue {
|
||||
const next: Record<string, FieldValue> = {};
|
||||
for (const [key, item] of Object.entries(value)) next[key === from ? to : key] = item;
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* `value` with each part `swap` answers for replaced by the answer, through lists and untagged
|
||||
* structs to any depth; `undefined` keeps a part and looks inside it. What is untouched keeps its
|
||||
* identity, so a caller can tell whether anything changed.
|
||||
*/
|
||||
export function mapNested(value: unknown, swap: (part: unknown) => unknown): unknown {
|
||||
const swapped = swap(value);
|
||||
if (swapped !== undefined) return swapped;
|
||||
if (isList(value)) {
|
||||
const items = value.map((item) => mapNested(item, swap));
|
||||
return items.some((item, i) => item !== value[i]) ? items : value;
|
||||
}
|
||||
if (isStruct(value) && tagOf(value) === undefined) {
|
||||
const entries = Object.entries(value);
|
||||
const mapped = entries.map(([key, field]) => [key, mapNested(field, swap)] as const);
|
||||
return mapped.some(([, field], i) => field !== entries[i]![1]) ? Object.fromEntries(mapped) : value;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/** The value as a run holds it: every item-type mark taken out, at any depth. */
|
||||
export function withoutItemTypes<T extends PropertyValue | undefined>(value: T): T {
|
||||
if (isList(value)) return (value.some(holdsItemType) ? value.map(withoutItemTypes) : value) as T;
|
||||
|
||||
@@ -20,7 +20,7 @@ import type { SceneObject } from './SceneObject';
|
||||
import { mixColor } from '../util/color';
|
||||
|
||||
/** `once` holds the last value when it ends, `once-reset` puts back what was there before it started. */
|
||||
export const PLAYBACKS = ['loop', 'once', 'once-reset', 'pingpong'] as const;
|
||||
const PLAYBACKS = ['loop', 'once', 'once-reset', 'pingpong'] as const;
|
||||
export type Playback = (typeof PLAYBACKS)[number];
|
||||
|
||||
/** What an animation can be built over: something placed, or a whole scene. */
|
||||
|
||||
@@ -45,7 +45,7 @@ export function easeCurve(shape: EasingShape, direction: EasingDirection): Vecto
|
||||
return curveFromEase((t) => easedShare(interpolation, t));
|
||||
}
|
||||
|
||||
export function curveFromEase(ease: (t: number) => number): VectorPoint[] {
|
||||
function curveFromEase(ease: (t: number) => number): VectorPoint[] {
|
||||
let at = [0, 1];
|
||||
let points = traced(ease, at);
|
||||
for (let round = 0; round < MAX_ROUNDS; round++) {
|
||||
|
||||
@@ -54,7 +54,7 @@ export function removeSubtrees(tree: ObjectTree, rootIds: readonly string[]): Re
|
||||
}
|
||||
|
||||
/** An object and every parent above it, nearest first. */
|
||||
export function chainOf(tree: ObjectTree, object: SceneObject): SceneObject[] {
|
||||
function chainOf(tree: ObjectTree, object: SceneObject): SceneObject[] {
|
||||
return [...parentChain(object, (o) => parentOf(tree, o))];
|
||||
}
|
||||
|
||||
|
||||
@@ -70,7 +70,7 @@ function mergeEdits(
|
||||
};
|
||||
}
|
||||
|
||||
export function containerAssetOf(project: Project, object: SceneObject): ContainerAsset | undefined {
|
||||
function containerAssetOf(project: Project, object: SceneObject): ContainerAsset | undefined {
|
||||
return findAssetOf(project, object.assetId, 'container');
|
||||
}
|
||||
|
||||
|
||||
@@ -90,7 +90,7 @@ export function angleOf(m: Mat): number {
|
||||
return Math.atan2(m.b, m.a);
|
||||
}
|
||||
|
||||
export function isMirrored(m: Mat): boolean {
|
||||
function isMirrored(m: Mat): boolean {
|
||||
return determinant(m) < 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
import { findAsset, type Project } from './Project';
|
||||
import { treeOrder, type ObjectTree } from './hierarchy';
|
||||
import { resolveObjects } from './instance';
|
||||
import { isList, isStruct, type PropertyBag, type PropertyValue, tagged, tagOf, untag } from './Properties';
|
||||
import { mapNested, type PropertyBag, type PropertyValue, tagged, tagOf, untag } from './Properties';
|
||||
import type { SceneObject } from './SceneObject';
|
||||
import { Recorder } from '../util/recorder';
|
||||
|
||||
@@ -108,19 +108,10 @@ export function anchorReferences(objects: readonly SceneObject[]): void {
|
||||
* keep their identity, so a caller can tell whether anything changed.
|
||||
*/
|
||||
function withReferences(value: PropertyValue, swap: (ref: string) => string | undefined): PropertyValue {
|
||||
if (tagOf(value) === 'object') {
|
||||
const ref = referencedId(value);
|
||||
return mapNested(value, (part) => {
|
||||
if (tagOf(part) !== 'object') return undefined;
|
||||
const ref = referencedId(part as PropertyValue);
|
||||
const next = ref ? swap(ref) : undefined;
|
||||
return next === undefined || next === ref ? value : objectReference(next);
|
||||
}
|
||||
if (isList(value)) {
|
||||
const items = value.map((item) => withReferences(item, swap));
|
||||
return items.some((item, i) => item !== value[i]) ? items : value;
|
||||
}
|
||||
if (isStruct(value) && tagOf(value) === undefined) {
|
||||
const entries = Object.entries(value);
|
||||
const mapped = entries.map(([key, field]) => [key, withReferences(field, swap)] as const);
|
||||
return mapped.some(([, field], i) => field !== entries[i]![1]) ? Object.fromEntries(mapped) : value;
|
||||
}
|
||||
return value;
|
||||
return next === undefined || next === ref ? part : objectReference(next);
|
||||
}) as PropertyValue;
|
||||
}
|
||||
@@ -16,7 +16,7 @@ export const GAME_SCALE_STEPS = [0.25, 0.5, 1, 2, 3, 4, 5, 6];
|
||||
|
||||
export const DEFAULT_GAME_SCALE: GameScale = 1;
|
||||
|
||||
export function isGameScale(value: unknown): value is GameScale {
|
||||
function isGameScale(value: unknown): value is GameScale {
|
||||
return value === 'auto' || value === 'fit' || GAME_SCALE_STEPS.includes(value as number);
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ export function visibilityParts(type: PlaceableAssetType): VisibilityPart[] {
|
||||
}
|
||||
|
||||
/** What a type shows until it is switched: all of it, except a name nothing showed before. */
|
||||
export function defaultVisibility(type: PlaceableAssetType): TypeVisibility {
|
||||
function defaultVisibility(type: PlaceableAssetType): TypeVisibility {
|
||||
return { symbol: true, label: hasSceneIcon(type), shape: true };
|
||||
}
|
||||
|
||||
|
||||
@@ -49,12 +49,13 @@ import {
|
||||
type StructValue,
|
||||
tagOf,
|
||||
textOf,
|
||||
withFieldRenamed,
|
||||
withItemType,
|
||||
} from './Properties';
|
||||
import { findAsset, findAssetOf, type Project } from './Project';
|
||||
|
||||
export const PACK_STRUCT = 'PackStruct';
|
||||
export const EXPAND_STRUCT = 'ExpandStruct';
|
||||
const PACK_STRUCT = 'PackStruct';
|
||||
const EXPAND_STRUCT = 'ExpandStruct';
|
||||
|
||||
/** Deeper than this only a cycle written by hand can go; it is cut there. */
|
||||
const MAX_DEPTH = 32;
|
||||
@@ -72,7 +73,7 @@ export function nodeStructType(node: GraphNode): string {
|
||||
}
|
||||
|
||||
/** A declared variable as the struct field it becomes in every value of the type. */
|
||||
export function fieldOfVariable(def: PropertyDef): StructFieldDef | undefined {
|
||||
function fieldOfVariable(def: PropertyDef): StructFieldDef | undefined {
|
||||
if (def.kind === 'struct')
|
||||
return {
|
||||
key: def.key,
|
||||
@@ -90,7 +91,7 @@ export function typeFields(asset: StructAsset): StructFieldDef[] {
|
||||
}
|
||||
|
||||
/** A new value of the type: every field at the default the asset declares for it. */
|
||||
export function typeDefault(asset: StructAsset): StructValue {
|
||||
function typeDefault(asset: StructAsset): StructValue {
|
||||
return structOf(typeFields(asset), asset.props);
|
||||
}
|
||||
|
||||
@@ -196,7 +197,7 @@ function holdersOf(
|
||||
* `value` in the shape of `fields`: what it has keeps its value (brought to the field's kind), what
|
||||
* it lacks takes the type's default, and what the type does not declare falls away.
|
||||
*/
|
||||
export function shapedStruct(
|
||||
function shapedStruct(
|
||||
project: Project,
|
||||
fields: readonly StructFieldDef[],
|
||||
value: PropertyValue | undefined,
|
||||
@@ -280,7 +281,7 @@ function renamedItems(project: Project, value: PropertyValue, rename: FieldRenam
|
||||
const path = [...inside, ...rename.path];
|
||||
const at = valueAt(next, path);
|
||||
if (isStruct(at) && rename.from in at)
|
||||
next = withValueAt(next, path, renamedKey(at, rename.from, rename.to)) ?? next;
|
||||
next = withValueAt(next, path, withFieldRenamed(at, rename.from, rename.to)) ?? next;
|
||||
}
|
||||
const out: Record<string, PropertyValue> = {};
|
||||
for (const [key, item] of Object.entries(next as StructValue))
|
||||
@@ -375,12 +376,6 @@ export interface FieldRename {
|
||||
to: string;
|
||||
}
|
||||
|
||||
function renamedKey(value: StructValue, from: string, to: string): StructValue {
|
||||
const next: Record<string, FieldValue> = {};
|
||||
for (const [key, item] of Object.entries(value)) next[key === from ? to : key] = item;
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Carries a renamed field's values over, before the shapes are rebuilt – which would drop them. */
|
||||
function applyRename(project: Project, rec: Recorder, rename: FieldRename): void {
|
||||
const { from, to } = rename;
|
||||
@@ -391,7 +386,7 @@ function applyRename(project: Project, rec: Recorder, rename: FieldRename): void
|
||||
const value = holder.read();
|
||||
const at = valueAt(value, path);
|
||||
if (!isStruct(at) || !(from in at)) continue;
|
||||
holder.write(withValueAt(value, path, renamedKey(at, from, to)) ?? value!);
|
||||
holder.write(withValueAt(value, path, withFieldRenamed(at, from, to)) ?? value!);
|
||||
}
|
||||
}
|
||||
for (const variable of everyVariable(project))
|
||||
|
||||
@@ -175,14 +175,6 @@ export function tilemapLayerNames(project: Project): string[] {
|
||||
return [...new Set(names)];
|
||||
}
|
||||
|
||||
/** The tiles a tilemap paints with, in the order they first appear – its palette in use. */
|
||||
export function tilemapTileIds(asset: { layers: TilemapLayer[] }): string[] {
|
||||
const ids: string[] = [];
|
||||
for (const layer of asset.layers)
|
||||
for (const id of Object.values(layer.cells)) if (id && !ids.includes(id)) ids.push(id);
|
||||
return ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* The cell a point in the tilemap's own frame falls into. The grid is centred on the object's
|
||||
* position, as every footprint is, so the top-left corner lies half a map up and to the left.
|
||||
|
||||
@@ -244,6 +244,15 @@ function passesFilter(tile: TileAsset, oneWay: OneWayFilter, material?: TileMate
|
||||
return oneWay === true || tileOneWayAngle(tile) === oneWay;
|
||||
}
|
||||
|
||||
/** The solid tiles painted on the map, each once, in the order the layers first name them. */
|
||||
function solidTiles(project: Project, asset: TilemapAsset): TileAsset[] {
|
||||
const ids = new Set(asset.layers.flatMap((layer) => cellsTileIds(layer.cells)));
|
||||
return [...ids].flatMap((id) => {
|
||||
const tile = findAssetOf(project, id, 'tile');
|
||||
return tile && isTileSolid(tile) ? [tile] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** The surfaces of the solid tiles painted on the map that pass `oneWay`, each once. */
|
||||
export function tileMaterials(
|
||||
project: Project,
|
||||
@@ -251,30 +260,17 @@ export function tileMaterials(
|
||||
oneWay: OneWayFilter = false,
|
||||
): TileMaterial[] {
|
||||
const materials: TileMaterial[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const layer of asset.layers)
|
||||
for (const tileId of cellsTileIds(layer.cells)) {
|
||||
if (seen.has(tileId)) continue;
|
||||
seen.add(tileId);
|
||||
const tile = findAssetOf(project, tileId, 'tile');
|
||||
if (!tile || !isTileSolid(tile) || !passesFilter(tile, oneWay)) continue;
|
||||
const material = tileMaterial(tile);
|
||||
if (!materials.some((known) => sameMaterial(known, material))) materials.push(material);
|
||||
}
|
||||
for (const tile of solidTiles(project, asset)) {
|
||||
if (!passesFilter(tile, oneWay)) continue;
|
||||
const material = tileMaterial(tile);
|
||||
if (!materials.some((known) => sameMaterial(known, material))) materials.push(material);
|
||||
}
|
||||
return materials.sort((a, b) => a.friction - b.friction || a.bounciness - b.bounciness);
|
||||
}
|
||||
|
||||
/** The angles of the solid one-way tiles painted on the map, each once, smallest first. */
|
||||
export function oneWayAngles(project: Project, asset: TilemapAsset): number[] {
|
||||
const angles = new Set<number>();
|
||||
const seen = new Set<string>();
|
||||
for (const layer of asset.layers)
|
||||
for (const tileId of cellsTileIds(layer.cells)) {
|
||||
if (seen.has(tileId)) continue;
|
||||
seen.add(tileId);
|
||||
const tile = findAssetOf(project, tileId, 'tile');
|
||||
if (tile && isTileSolid(tile) && isTileOneWay(tile)) angles.add(tileOneWayAngle(tile));
|
||||
}
|
||||
const angles = new Set(solidTiles(project, asset).filter(isTileOneWay).map(tileOneWayAngle));
|
||||
return [...angles].sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
import { isKindWith } from '../properties/kinds';
|
||||
import { schemaForAsset } from '../properties/PropertySchema';
|
||||
import { referencesAny, trackDef } from './animation';
|
||||
import type { AnimationAsset, Asset, TileAsset, TilemapAsset } from './Asset';
|
||||
import type { AnimationAsset, Asset, TileAsset } from './Asset';
|
||||
import { overrideSites } from './instance';
|
||||
import { type ObjectHolder, objectHolders, type Project } from './Project';
|
||||
import type { SceneObject } from './SceneObject';
|
||||
@@ -68,15 +68,6 @@ export function tilesUsing(project: Project, ids: readonly string[]): TileAsset[
|
||||
);
|
||||
}
|
||||
|
||||
/** The tilemaps painted with any of these tiles – intrinsic data, like a tile's pictures. */
|
||||
export function tilemapsUsing(project: Project, ids: readonly string[]): TilemapAsset[] {
|
||||
const wanted = new Set(ids);
|
||||
return project.assets.filter(
|
||||
(a): a is TilemapAsset =>
|
||||
a.type === 'tilemap' && a.layers.some((l) => Object.values(l.cells).some((id) => wanted.has(id))),
|
||||
);
|
||||
}
|
||||
|
||||
/** The animations keying any of these ids – intrinsic data, which `findPropertyUsages` does not see. */
|
||||
export function animationsUsing(project: Project, ids: readonly string[]): AnimationAsset[] {
|
||||
const wanted = new Set(ids);
|
||||
|
||||
@@ -17,6 +17,7 @@ import { ClipType, FillRule, type PathD, type PathsD } from 'clipper2-ts/dist/Co
|
||||
import { ClipperD, type PolyPathD, PolyTreeD } from 'clipper2-ts/dist/Engine.js';
|
||||
import type { VectorRing, VectorShape } from './Asset';
|
||||
import type { Vec2 } from './Properties';
|
||||
import { cubicAt } from '../util/vec';
|
||||
import { handleAt, isDrawableRing } from './vectorart';
|
||||
import {
|
||||
addCurve,
|
||||
@@ -162,12 +163,3 @@ function curveSteps(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2): number {
|
||||
);
|
||||
return Math.min(MAX_CURVE_STEPS, Math.max(1, Math.ceil(Math.sqrt((0.75 * m) / FLATTEN_TOLERANCE))));
|
||||
}
|
||||
|
||||
function cubicAt(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2, t: number): Vec2 {
|
||||
const u = 1 - t;
|
||||
const a = u * u * u;
|
||||
const b = 3 * u * u * t;
|
||||
const c = 3 * u * t * t;
|
||||
const d = t * t * t;
|
||||
return { x: a * p0.x + b * p1.x + c * p2.x + d * p3.x, y: a * p0.y + b * p1.y + c * p2.y + d * p3.y };
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
*/
|
||||
import type { VectorPoint } from './Asset';
|
||||
import type { Vec2 } from './Properties';
|
||||
import { cubicAt, splitCubic } from '../util/vec';
|
||||
|
||||
/** How far a sampled curve may stray from the true one, in canvas pixels. */
|
||||
export const FLATTEN_TOLERANCE = 0.2;
|
||||
@@ -149,10 +150,11 @@ function edgeOn(from: PointOnCurve[], to: PointOnCurve[], table: CurveTable): Cu
|
||||
|
||||
/** Whether the piece of `segment` from `t0` to `t1` hugs the straight line between its two ends. */
|
||||
function staysOnCurve(segment: CurveSegment, t0: number, t1: number): boolean {
|
||||
const a = cubicAt(segment, t0);
|
||||
const b = cubicAt(segment, t1);
|
||||
const at = (t: number) => cubicAt(segment.p0, segment.p1, segment.p2, segment.p3, t);
|
||||
const a = at(t0);
|
||||
const b = at(t1);
|
||||
for (let step = 1; step < 4; step++) {
|
||||
const point = cubicAt(segment, t0 + (t1 - t0) * (step / 4));
|
||||
const point = at(t0 + (t1 - t0) * (step / 4));
|
||||
const along = onChord(a, b, point);
|
||||
if (!along || along.gap > CHORD_SLACK) return false;
|
||||
}
|
||||
@@ -203,31 +205,6 @@ function build(
|
||||
function subCurve(segment: CurveSegment, t0: number, t1: number): Vec2[] {
|
||||
if (t0 > t1) return subCurve(segment, t1, t0).reverse();
|
||||
const whole = [segment.p0, segment.p1, segment.p2, segment.p3];
|
||||
const left = t1 >= 1 ? whole : split(whole, t1).left;
|
||||
return t1 <= 0 ? left : split(left, t0 / t1).right;
|
||||
}
|
||||
|
||||
/** de Casteljau: the cubic cut in two at `t`, both halves as control points. */
|
||||
function split(p: Vec2[], t: number): { left: Vec2[]; right: Vec2[] } {
|
||||
const a = lerp(p[0]!, p[1]!, t);
|
||||
const b = lerp(p[1]!, p[2]!, t);
|
||||
const c = lerp(p[2]!, p[3]!, t);
|
||||
const d = lerp(a, b, t);
|
||||
const e = lerp(b, c, t);
|
||||
const mid = lerp(d, e, t);
|
||||
return { left: [p[0]!, a, d, mid], right: [mid, e, c, p[3]!] };
|
||||
}
|
||||
|
||||
function lerp(a: Vec2, b: Vec2, t: number): Vec2 {
|
||||
return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
|
||||
}
|
||||
|
||||
function cubicAt(segment: { p0: Vec2; p1: Vec2; p2: Vec2; p3: Vec2 }, t: number): Vec2 {
|
||||
const u = 1 - t;
|
||||
const a = u * u * u;
|
||||
const b = 3 * u * u * t;
|
||||
const c = 3 * u * t * t;
|
||||
const d = t * t * t;
|
||||
const { p0, p1, p2, p3 } = segment;
|
||||
return { x: a * p0.x + b * p1.x + c * p2.x + d * p3.x, y: a * p0.y + b * p1.y + c * p2.y + d * p3.y };
|
||||
const left = t1 >= 1 ? whole : splitCubic(whole, t1).left;
|
||||
return t1 <= 0 ? left : splitCubic(left, t0 / t1).right;
|
||||
}
|
||||
@@ -23,7 +23,7 @@ export interface LiveRange {
|
||||
to: number;
|
||||
}
|
||||
|
||||
export const NO_PARTICLES: LiveRange = { from: 0, to: -1 };
|
||||
const NO_PARTICLES: LiveRange = { from: 0, to: -1 };
|
||||
|
||||
/**
|
||||
* When particle `index` was born, in seconds since the source started. A continuous source emits on
|
||||
|
||||
@@ -280,7 +280,7 @@ export const SORT_WITH_PARENT_KEY = 'sortWithParent';
|
||||
* Whether a child is drawn in its parent's place instead of on its own (#232, see `drawSlots`).
|
||||
* A project stored before it reads as off, so it draws as it did; a new asset starts with it on.
|
||||
*/
|
||||
export const SORT_PROPS: PropertySchema = [
|
||||
const SORT_PROPS: PropertySchema = [
|
||||
{ key: SORT_WITH_PARENT_KEY, label: 'Sort with parent', kind: 'boolean', default: false, initial: true },
|
||||
];
|
||||
|
||||
@@ -295,7 +295,7 @@ const CONTAINER_SORT_PROPS: PropertySchema = [
|
||||
/** A tilemap has no single place in the draw order, and the other types are not drawn at all. */
|
||||
const SORT_TYPES: ReadonlySet<AssetType> = new Set(['sprite', 'text', 'particles', 'container']);
|
||||
|
||||
export function hasSortProps(type: AssetType): boolean {
|
||||
function hasSortProps(type: AssetType): boolean {
|
||||
return SORT_TYPES.has(type);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ export interface ClipNode {
|
||||
}
|
||||
|
||||
/** The area's own rectangle in world units. */
|
||||
export function clipCorners(props: PropertyBag, m: Mat): Vec2[] {
|
||||
function clipCorners(props: PropertyBag, m: Mat): Vec2[] {
|
||||
return footprintCorners('clip', props, m);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,9 +4,9 @@ import { flatDef, type FlatDef, type PropertyDef } from './PropertySchema';
|
||||
|
||||
/** The params of a `Property` node in a shader or particle graph: its name and the row it declares. */
|
||||
export const PROPERTY_NAME_PARAM = 'name';
|
||||
export const PROPERTY_DEFAULT_PARAM = 'default';
|
||||
export const PROPERTY_MIN_PARAM = 'min';
|
||||
export const PROPERTY_MAX_PARAM = 'max';
|
||||
const PROPERTY_DEFAULT_PARAM = 'default';
|
||||
const PROPERTY_MIN_PARAM = 'min';
|
||||
const PROPERTY_MAX_PARAM = 'max';
|
||||
|
||||
/** The params of a `Property` node, the same in both graphs but for the step of their number fields. */
|
||||
export function propertyNodeParams(step: number): PropertyDef[] {
|
||||
|
||||
@@ -31,7 +31,7 @@ export function propertyName(node: GraphNode): string {
|
||||
* rows the sprite brings itself: both rows would share the key and the uniform would read the
|
||||
* sprite's width instead of the declared default (#63). The compiler names which of the two it is.
|
||||
*/
|
||||
export function isValidPropertyName(name: string): boolean {
|
||||
function isValidPropertyName(name: string): boolean {
|
||||
return isValidFieldName(name) && !isSpriteProp(name);
|
||||
}
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ export interface LocalTransform {
|
||||
mirrorY: boolean;
|
||||
}
|
||||
|
||||
export const NEUTRAL: LocalTransform = { rotation: 0, scale: 1, mirrorX: false, mirrorY: false };
|
||||
const NEUTRAL: LocalTransform = { rotation: 0, scale: 1, mirrorX: false, mirrorY: false };
|
||||
|
||||
export function transformOf(props: PropertyBag): LocalTransform {
|
||||
return {
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
import { type AuthStore, roleOf, type SignedIn, WrongCredentialsError } from './AuthStore';
|
||||
import { apiRequest } from './http';
|
||||
import { apiRequest, jsonBody } from './http';
|
||||
|
||||
/**
|
||||
* A wrong password is the expected answer of a login screen, not a breakdown: it gets its own type
|
||||
* so the screen can say one thing about it and another about a server that is down. Changing the
|
||||
* password answers the same way when the current one was wrong; a 422 (too short) carries the
|
||||
* server's wording and stays generic.
|
||||
*/
|
||||
function wrongCredentials(status: number, data: unknown): Error | undefined {
|
||||
return status === 401 ? new WrongCredentialsError((data as { error?: string } | null)?.error) : undefined;
|
||||
}
|
||||
|
||||
export class HttpAuthStore implements AuthStore {
|
||||
constructor(private readonly endpoint: string) {}
|
||||
@@ -18,14 +28,8 @@ export class HttpAuthStore implements AuthStore {
|
||||
this.endpoint,
|
||||
'POST',
|
||||
'auth/login',
|
||||
{
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password }),
|
||||
},
|
||||
// A wrong password is the expected answer of a login screen, not a breakdown: it gets its
|
||||
// own type so the screen can say one thing about it and another about a server that is down.
|
||||
(status, data) =>
|
||||
status === 401 ? new WrongCredentialsError((data as { error?: string } | null)?.error) : undefined,
|
||||
jsonBody({ username, password }),
|
||||
wrongCredentials,
|
||||
);
|
||||
return { user: body.user, role: roleOf(body.role) };
|
||||
}
|
||||
@@ -39,14 +43,8 @@ export class HttpAuthStore implements AuthStore {
|
||||
this.endpoint,
|
||||
'POST',
|
||||
'auth/password',
|
||||
{
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ currentPassword, newPassword }),
|
||||
},
|
||||
// Same split as `logIn`: a 401 here means the current password was wrong, which the dialog
|
||||
// says in its own words. A 422 (too short) carries the server's wording and stays generic.
|
||||
(status, data) =>
|
||||
status === 401 ? new WrongCredentialsError((data as { error?: string } | null)?.error) : undefined,
|
||||
jsonBody({ currentPassword, newPassword }),
|
||||
wrongCredentials,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,6 @@
|
||||
import type { Project } from '../model/Project';
|
||||
import { apiRequest } from './http';
|
||||
import {
|
||||
type LoadedProject,
|
||||
type ProjectStore,
|
||||
type ProjectSummary,
|
||||
StaleRevisionError,
|
||||
} from './ProjectStore';
|
||||
import { apiRequest, jsonBody } from './http';
|
||||
import { type LoadedProject, type ProjectStore, type ProjectSummary, staleRevision } from './ProjectStore';
|
||||
import { deserializeProject, serializeProject } from './serialize';
|
||||
|
||||
export class HttpProjectStore implements ProjectStore {
|
||||
@@ -47,18 +42,6 @@ export class HttpProjectStore implements ProjectStore {
|
||||
}
|
||||
|
||||
private async request<T>(method: string, route: string, payload?: unknown): Promise<T> {
|
||||
return apiRequest<T>(
|
||||
this.endpoint,
|
||||
method,
|
||||
route,
|
||||
{
|
||||
headers: payload !== undefined ? { 'Content-Type': 'application/json' } : {},
|
||||
body: payload !== undefined ? JSON.stringify(payload) : undefined,
|
||||
},
|
||||
(status, data) =>
|
||||
status === 409
|
||||
? new StaleRevisionError((data as { revision?: number } | null)?.revision ?? -1)
|
||||
: undefined,
|
||||
);
|
||||
return apiRequest<T>(this.endpoint, method, route, jsonBody(payload), staleRevision);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { apiRequest } from './http';
|
||||
import { StaleRevisionError } from './ProjectStore';
|
||||
import { apiRequest, jsonBody } from './http';
|
||||
import { staleRevision } from './ProjectStore';
|
||||
import type { SnapshotStore, SnapshotSummary } from './SnapshotStore';
|
||||
|
||||
export class HttpSnapshotStore implements SnapshotStore {
|
||||
@@ -26,19 +26,7 @@ export class HttpSnapshotStore implements SnapshotStore {
|
||||
}
|
||||
|
||||
private request<T>(method: string, path: string, payload?: unknown): Promise<T> {
|
||||
return apiRequest<T>(
|
||||
this.endpoint,
|
||||
method,
|
||||
path,
|
||||
{
|
||||
headers: payload !== undefined ? { 'Content-Type': 'application/json' } : {},
|
||||
body: payload !== undefined ? JSON.stringify(payload) : undefined,
|
||||
},
|
||||
(status, data) =>
|
||||
status === 409
|
||||
? new StaleRevisionError((data as { revision?: number } | null)?.revision ?? -1)
|
||||
: undefined,
|
||||
);
|
||||
return apiRequest<T>(this.endpoint, method, path, jsonBody(payload), staleRevision);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { type Role, roleOf } from './AuthStore';
|
||||
import { apiRequest } from './http';
|
||||
import { apiRequest, jsonBody } from './http';
|
||||
import type { Account, AccountChange, UsersStore } from './UsersStore';
|
||||
|
||||
/** A refusal of the API (4xx with an `{error}`) as its bare sentence, without route and status around it. */
|
||||
@@ -17,18 +17,14 @@ export class HttpUsersStore implements UsersStore {
|
||||
}
|
||||
|
||||
async create(username: string, password: string, role: Role): Promise<void> {
|
||||
await apiRequest(this.endpoint, 'POST', 'users', this.json({ username, password, role }), refusal);
|
||||
await apiRequest(this.endpoint, 'POST', 'users', jsonBody({ username, password, role }), refusal);
|
||||
}
|
||||
|
||||
async update(username: string, change: AccountChange): Promise<void> {
|
||||
await apiRequest(this.endpoint, 'PATCH', `users/${username}`, this.json(change), refusal);
|
||||
await apiRequest(this.endpoint, 'PATCH', `users/${username}`, jsonBody(change), refusal);
|
||||
}
|
||||
|
||||
async remove(username: string): Promise<void> {
|
||||
await apiRequest<void>(this.endpoint, 'DELETE', `users/${username}`, {}, refusal);
|
||||
}
|
||||
|
||||
private json(body: object): { headers: Record<string, string>; body: string } {
|
||||
return { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) };
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,13 @@ export class StaleRevisionError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** The API's 409, with the revision the server holds, as a `StaleRevisionError` (see `apiRequest`). */
|
||||
export function staleRevision(status: number, data: unknown): Error | undefined {
|
||||
return status === 409
|
||||
? new StaleRevisionError((data as { revision?: number } | null)?.revision ?? -1)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export interface ProjectStore {
|
||||
list(): Promise<ProjectSummary[]>;
|
||||
/**
|
||||
|
||||
@@ -27,7 +27,7 @@ export interface ReleaseStore {
|
||||
}
|
||||
|
||||
/** The page a released game is played on, next to the editor's own. */
|
||||
export const PLAY_PAGE = '/game-maker/play.html';
|
||||
const PLAY_PAGE = '/game-maker/play.html';
|
||||
|
||||
export function releaseUrl(origin: string, token: string): string {
|
||||
return `${origin}${PLAY_PAGE}?game=${token}`;
|
||||
|
||||
@@ -14,10 +14,17 @@ const STATUS_MESSAGES: Record<number, string> = {
|
||||
504: 'Server timed out',
|
||||
};
|
||||
|
||||
export function statusMessage(status: number, statusText: string): string {
|
||||
function statusMessage(status: number, statusText: string): string {
|
||||
return STATUS_MESSAGES[status] ?? (statusText || `HTTP ${status}`);
|
||||
}
|
||||
|
||||
/** The request part of a JSON payload; nothing at all without one. */
|
||||
export function jsonBody(payload?: unknown): Pick<RequestInit, 'headers' | 'body'> {
|
||||
return payload === undefined
|
||||
? {}
|
||||
: { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) };
|
||||
}
|
||||
|
||||
/**
|
||||
* One call against the PHP API. Routing goes through the `r` query parameter because the site's
|
||||
* nginx config does not pass PATH_INFO to PHP; `query` adds further parameters beside it, which is
|
||||
|
||||
@@ -11,3 +11,28 @@ export function closestOnSegment(p: Vec2, a: Vec2, b: Vec2): Vec2 {
|
||||
const t = length > 0 ? Math.min(1, Math.max(0, dot({ x: p.x - a.x, y: p.y - a.y }, ab) / length)) : 0;
|
||||
return { x: a.x + ab.x * t, y: a.y + ab.y * t };
|
||||
}
|
||||
|
||||
export function lerpVec(a: Vec2, b: Vec2, t: number): Vec2 {
|
||||
return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
|
||||
}
|
||||
|
||||
/** The point at `t` of the cubic Bezier with these control points. */
|
||||
export function cubicAt(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2, t: number): Vec2 {
|
||||
const u = 1 - t;
|
||||
const a = u * u * u;
|
||||
const b = 3 * u * u * t;
|
||||
const c = 3 * u * t * t;
|
||||
const d = t * t * t;
|
||||
return { x: a * p0.x + b * p1.x + c * p2.x + d * p3.x, y: a * p0.y + b * p1.y + c * p2.y + d * p3.y };
|
||||
}
|
||||
|
||||
/** de Casteljau: the cubic cut in two at `t`, both halves as control points. */
|
||||
export function splitCubic(p: readonly Vec2[], t: number): { left: Vec2[]; right: Vec2[] } {
|
||||
const a = lerpVec(p[0]!, p[1]!, t);
|
||||
const b = lerpVec(p[1]!, p[2]!, t);
|
||||
const c = lerpVec(p[2]!, p[3]!, t);
|
||||
const d = lerpVec(a, b, t);
|
||||
const e = lerpVec(b, c, t);
|
||||
const mid = lerpVec(d, e, t);
|
||||
return { left: [p[0]!, a, d, mid], right: [mid, e, c, p[3]!] };
|
||||
}
|
||||
Reference in new issue
Block a user