diff --git a/src/lib/modules/editor/components/AnimationPanel.svelte b/src/lib/modules/editor/components/AnimationPanel.svelte new file mode 100644 index 0000000..8463fae --- /dev/null +++ b/src/lib/modules/editor/components/AnimationPanel.svelte @@ -0,0 +1,129 @@ + + +
+ + {#if $layers.length} +
+ {#each $layers as l (l.id)} + + {/each} +
+ {:else} +

{$t.animNone}

+ {/if} +
+ + {#if $current && anim} + +
+ + +
+ {$t.animAt} + + {#if $value !== null} + {$t.animValue} + + {/if} +
+ +
+ {#if $current.locked} +

{$t.locked}

+ {/if} + +
+
+ {/if} +
+ + diff --git a/src/lib/modules/editor/components/SimPanel.svelte b/src/lib/modules/editor/components/SimPanel.svelte index 4818ea3..34aeb76 100644 --- a/src/lib/modules/editor/components/SimPanel.svelte +++ b/src/lib/modules/editor/components/SimPanel.svelte @@ -4,6 +4,7 @@ import { Select } from "$lib/shared/components/select"; import { Switch } from "$lib/shared/components/switch"; import { Icon } from "$lib/shared/components/icon"; + import { Button } from "$lib/shared/components/button"; import { ACCENT_PALETTE, ID_METRIC, @@ -106,6 +107,11 @@ >{$t.slotPlaceholders} + + {#if $ids.some(({ id }) => id === 0x99)}
{$t.theme} diff --git a/src/lib/modules/editor/components/TreePanel.svelte b/src/lib/modules/editor/components/TreePanel.svelte index 72137a6..c4b57f9 100644 --- a/src/lib/modules/editor/components/TreePanel.svelte +++ b/src/lib/modules/editor/components/TreePanel.svelte @@ -34,6 +34,7 @@ widgetAdded, numberAdded, imageAdded, + animatedAdded, deleteRequested, duplicateRequested, copyRequested, @@ -295,6 +296,11 @@ {$t.emptyImage} + + animatedAdded()}> + + {$t.animatedLayer} + numberAdded()}> diff --git a/src/lib/modules/editor/components/props/animation.svelte b/src/lib/modules/editor/components/props/animation.svelte new file mode 100644 index 0000000..76c8e60 --- /dev/null +++ b/src/lib/modules/editor/components/props/animation.svelte @@ -0,0 +1,318 @@ + + +{#if anim} +

{$t.animHint}

+ + {$t.animPresets} + {#each GROUPS as g (g)} + {$t.animGroup[g]} + + {/each} +

{$t.animNoFade}

+ {#if presetInfo} +

{presetInfo.proven ? $t.animProven : $t.animUntested}

+ {/if} + + {#if path.length > 1} + {$t.animPath} + + `${p.dx},${p.dy}`).join(" ")} + fill="none" + stroke="currentColor" + stroke-width="2" + stroke-linecap="round" + stroke-linejoin="round" + vector-effect="non-scaling-stroke" + /> + + + +

{$t.animTravel(Math.round(view.w), Math.round(view.h))}

+ {/if} + + {$t.animDirection} + { + if ((v === "rises") !== animRises(anim)) putSafe({ start: anim.end, end: anim.start }); + }} + /> + + {$t.animSpeed}: {(anim.duration / 1000).toFixed(1)} + putSafe({ duration: v })} + /> + + {#key shown} +
+ { + putSafe({ start: tenths(v) }); + shown++; + }} + /> + { + putSafe({ end: tenths(v) }); + shown++; + }} + /> +
+ {/key} + + +

{$t.animLoopHint}

+ + {#each issues as i (i)} +

{$t.animIssue[i]}

+ {/each} + + + +
+ {$t.animAdvanced} +

{$t.animAdvancedHint}

+ put({ duration: u16(v) })} + /> + {$t.animRaw} +
+ {#each RAW as f (f.key)} + put({ [f.key]: f.signed ? s16(v) : u16(v) })} + /> + {/each} + put({ flags: num(v) & 0xff })} + /> +
+
+{/if} + + diff --git a/src/lib/modules/editor/core/document/edits.ts b/src/lib/modules/editor/core/document/edits.ts index bcdd972..e0faee4 100644 --- a/src/lib/modules/editor/core/document/edits.ts +++ b/src/lib/modules/editor/core/document/edits.ts @@ -5,7 +5,7 @@ // here is keyed by NodeId, which is what makes the layer identity survive an immutable update: // the old code compared node objects, so any rebuilt parent silently invalidated `sel`. import { hex, TAG, unhex } from "../format"; -import { PANELS, procOf, RINGS, type Proc } from "./proc"; +import { PANELS, procOf, RINGS, withAnimBody, animOf, type Anim, type Proc } from "./proc"; import { framesOf, isPlaced, @@ -387,3 +387,15 @@ export function usedAssets(doc: Doc) { doc.screens.forEach((s) => walk(s.layers)); return out; } + +/** Change fields of a type 2 (animated) layer's 0x5c body; the rest of the body stays as found. */ +export function withAnim(doc: Doc, id: NodeId, patch: Partial): Doc { + const l = findLayer(doc, id); + + if (!l || !animOf(l)) return doc; + const extra = withAnimBody(l, patch); + + return !extra || extra === (l as { extra?: unknown }).extra + ? doc + : patchLayer(doc, id, { extra } as Partial); +} diff --git a/src/lib/modules/editor/core/document/factory.ts b/src/lib/modules/editor/core/document/factory.ts index 5c9a075..1023d1f 100644 --- a/src/lib/modules/editor/core/document/factory.ts +++ b/src/lib/modules/editor/core/document/factory.ts @@ -23,6 +23,7 @@ import { type WidgetMeta, } from "./doc"; import { TAG, hex, unhex, type Resource } from "../format"; +import { ANIM_SEED } from "./proc"; const META0: WidgetMeta = { w: 0, @@ -51,6 +52,21 @@ export const newImage = (frames: readonly ImageId[]): ImageLayer => ({ frames, }); +/** The animated image (0x82, type 2), seeded with Sun Circle's exact 0x5c body: a full-screen + * 466x466 layer that sweeps in on wake and stops where daylight % puts it. Starting from bytes a + * Watch Pro 2 is known to play means a new layer is as safe as the stock one; edit from there. */ +export const newAnimated = (frames: readonly ImageId[]): ImageLayer => ({ + ...base(), + tag: 0x82, + kind: "image", + x: 0, + y: 0, + meta: metaWith({ w: 466, h: 466, source: 0x82, max: 0x3c }), + refType: 1, + frames, + extra: [{ tag: TAG.proc, hex: ANIM_SEED }], +}); + /** One frame per battery percent, 0..100: the image widget draws frames[value % count]. */ export const PROGRESS_STEPS = 101; diff --git a/src/lib/modules/editor/core/document/proc.ts b/src/lib/modules/editor/core/document/proc.ts index c911897..ef17f45 100644 --- a/src/lib/modules/editor/core/document/proc.ts +++ b/src/lib/modules/editor/core/document/proc.ts @@ -1,7 +1,7 @@ // The Watch 3 Pro's procedural widgets as the document holds them: an image layer tagged 0x82 // whose 0x5c body (kept in `extra`) names the type. Types 0..3 are drawn like any image layer; // 4..7 draw themselves (core/render/proc.ts). -import { TAG, unhex } from "../format"; +import { TAG, hex, unhex } from "../format"; import type { Layer } from "./doc"; export const RINGS = 4; @@ -41,3 +41,219 @@ export function procSources(l: Layer): number[] { /** Whether any layer of the list, groups included, is a procedural widget of this type. */ export const hasProc = (layers: readonly Layer[], type: number): boolean => layers.some((l) => procOf(l)?.type === type || (l.kind === "group" && hasProc(l.children, type))); + +/** The animated image widget (0x82, type 2): a Watch Pro 2 plays it, so it stays an image layer. */ +export const ANIMATED = 2; +/** The fields end at byte 20; Sun Circle's body is 25 bytes, the rest zero padding. */ +export const ANIM_BODY = 21; +/** Sun Circle's sun body, as found on a Watch Pro 2 that plays it: what a new layer starts from. */ +export const ANIM_SEED = "0200d007efff000000000000550ac20ae90ee90e8800000000"; + +/** The type 2 body as a view. Fields the firmware reads but whose meaning isn't pinned down are + * kept raw (`rawA`..`rawE`, `flags`), named by offset, until tests on a watch settle them. */ +export interface Anim { + /** Offset 2: sweep duration, ms (inferred from the ~2 s seen on a watch). */ + duration: number; + /** Offset 12: angle at value 0, in 0.1 degrees (the parser wraps it into +-3600). */ + start: number; + /** Offset 14: angle at value 100, in 0.1 degrees. */ + end: number; + /** Offsets 4, 6, 8, 10 (s16). From the firmware, not yet confirmed on a watch: 4 and 6 are + * the base x and y (y is not used while orbiting), 8 and 10 a second point with no visible + * effect in 1.0.0.73. */ + raw4: number; + raw6: number; + raw8: number; + raw10: number; + /** Offsets 16, 18 (s16). From the firmware, not yet confirmed on a watch: 16 is the orbit + * radius in pixels, 18 a pivot y used only without orbit. */ + raw16: number; + raw18: number; + /** Offset 20: flags. Bits 7 and 3 together (0x88) orbit; bit 0 repeats the sweep. */ + flags: number; + /** Bytes from 21 on (4 zeros in Sun Circle), kept as found. */ + tail: readonly number[]; +} + +const s16 = (v: Uint8Array, o: number) => ((v[o] | (v[o + 1] << 8)) << 16) >> 16; +const u16 = (v: Uint8Array, o: number) => v[o] | (v[o + 1] << 8); + +type Extra = { readonly tag: number; readonly hex: string }; +const extraOf = (l: Layer): readonly Extra[] | undefined => + l.kind === "group" || l.kind === "raw" ? undefined : l.extra; +const animBody = (l: Layer) => + l.kind === "group" || l.kind === "raw" || l.tag !== 0x82 + ? undefined + : extraOf(l)?.find((e) => e.tag === TAG.proc); + +/** The body of a type 2 layer, or null for anything else. */ +export function animOf(l: Layer): Anim | null { + const body = animBody(l); + + if (!body) return null; + const v = unhex(body.hex); + + if (v.length < ANIM_BODY || u16(v, 0) !== ANIMATED) return null; + return { + duration: u16(v, 2), + raw4: s16(v, 4), + raw6: s16(v, 6), + raw8: s16(v, 8), + raw10: s16(v, 10), + start: s16(v, 12), + end: s16(v, 14), + raw16: s16(v, 16), + raw18: s16(v, 18), + flags: v[20], + tail: [...v.subarray(ANIM_BODY)], + }; +} + +/** The bytes of an Anim: `encodeAnim(animOf(l))` reproduces what was read. */ +export function encodeAnim(a: Anim): Uint8Array { + const v = new Uint8Array(ANIM_BODY + a.tail.length); + const put = (o: number, n: number) => { + v[o] = n & 0xff; + v[o + 1] = (n >> 8) & 0xff; + }; + + put(0, ANIMATED); + put(2, a.duration); + put(4, a.raw4); + put(6, a.raw6); + put(8, a.raw8); + put(10, a.raw10); + put(12, a.start); + put(14, a.end); + put(16, a.raw16); + put(18, a.raw18); + v[20] = a.flags; + a.tail.forEach((b, i) => (v[21 + i] = b)); + return v; +} + +/** The layer's extras with the type 2 body rewritten, or undefined when it isn't one. */ +export function withAnimBody(l: Layer, patch: Partial): readonly Extra[] | undefined { + const a = animOf(l); + const body = animBody(l); + + if (!a || !body) return undefined; + const next = hex(encodeAnim({ ...a, ...patch })); + + // unchanged bytes hand back the very same array, so a no-op edit can be told by reference + return next === body.hex + ? extraOf(l) + : extraOf(l)!.map((e) => (e === body ? { ...e, hex: next } : e)); +} + +/** The animated images of a layer list, groups included, in tree order. */ +export const animatedIn = (layers: readonly Layer[]): Layer[] => + layers.flatMap((l) => (l.kind === "group" ? animatedIn(l.children) : animOf(l) ? [l] : [])); + +/** Values the firmware report says it handles badly or not at all, for the panel to point out. The + * editor still lets them through: these are what is known, not what is proven safe. */ +export type AnimIssue = "duration" | "flags" | "angle" | "radius"; + +export function animIssues(a: Anim): AnimIssue[] { + const out: AnimIssue[] = []; + const inRange = (t: number) => t / 10 > 180 && t / 10 <= 360; + + if (a.duration < 18) out.push("duration"); + if (a.flags !== 0x88 && a.flags !== 0x89) out.push("flags"); + if (!inRange(a.start) || !inRange(a.end)) out.push("angle"); + if (a.raw16 < 0 || a.raw16 > 8000 || Math.abs(a.raw4 + 2 * a.raw16) > 32767) out.push("radius"); + return out; +} + +/** What the simple controls may produce. Tighter than what the firmware reads: the angle range is + * the one its position code acts on (180 < a <= 360, in tenths 1801..3600), and the duration + * stays well inside a u16 and above the 18 ms floor below which it does not animate. The raw + * fields can still go past these; the simple controls cannot. */ +export const ANIM_LIMITS = { + durationMin: 100, + durationMax: 10_000, + angleMin: 1801, + angleMax: 3600, +} as const; + +const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, Math.round(v))); + +/** A patch with its duration and angles forced into ANIM_LIMITS. */ +export function safeAnim(patch: Partial): Partial { + const out = { ...patch }; + const { durationMin, durationMax, angleMin, angleMax } = ANIM_LIMITS; + + if (out.duration !== undefined) out.duration = clamp(out.duration, durationMin, durationMax); + if (out.start !== undefined) out.start = clamp(out.start, angleMin, angleMax); + if (out.end !== undefined) out.end = clamp(out.end, angleMin, angleMax); + return out; +} + +/** Bit 0 of the flags repeats the sweep (read from the firmware; 0x89 is not yet tried on a watch). */ +export const animLoops = (a: Anim) => (a.flags & 1) === 1; + +/** True when the angle grows from value 0 to value 100: Sun Circle's sun (2645 -> 2754), the one + * that rises. False for its moon, which has the two angles swapped. */ +export const animRises = (a: Anim) => a.start <= a.end; + +/** Ready-made effects: whole geometries, every one a position the ported firmware math (anim.ts) + * reaches. `proven` marks the two that are Sun Circle's own bytes, which play on a Watch Pro 2; + * the others only change values the firmware reads (angles, radius, offset, duration) and are + * unproven until the watch tests are back. The arcs use a small radius: from 180 to 360 degrees + * the image goes round half a circle of that radius, bulging left by R, (0, R) -> (-R, 0) -> + * (0, -R) relative to where it is placed; Sun Circle's radius of 3817 makes the same path a + * nearly straight vertical slide. + * ponytail: grow this list from tests on a watch, not from the firmware reading alone. */ +const geo = (R: number, start: number, end: number, duration = 2000) => ({ + duration, + start, + end, + raw4: R === 3817 ? -17 : -R, + raw6: 0, + raw8: 0, + raw10: 0, + raw16: R, + raw18: R, + flags: 0x88, +}); + +export const ANIM_PRESETS = [ + { id: "rise", group: "slide", proven: true, patch: geo(3817, 2645, 2754) }, + { id: "set", group: "slide", proven: true, patch: geo(3817, 2754, 2645) }, + { id: "riseSlow", group: "slide", proven: false, patch: geo(3817, 2645, 2754, 4000) }, + { id: "setSlow", group: "slide", proven: false, patch: geo(3817, 2754, 2645, 4000) }, + { id: "arcUp", group: "arc", proven: false, patch: geo(150, 1801, 3600) }, + { id: "arcDown", group: "arc", proven: false, patch: geo(150, 3600, 1801) }, + { id: "arcSmall", group: "arc", proven: false, patch: geo(80, 1801, 3600, 1500) }, + { id: "quarterUp", group: "arc", proven: false, patch: geo(200, 2700, 3600) }, + { id: "quarterDown", group: "arc", proven: false, patch: geo(200, 3600, 2700) }, + { id: "dropLong", group: "slide", proven: false, patch: geo(3817, 2600, 2800, 3000) }, +] as const satisfies readonly { + id: string; + group: "slide" | "arc"; + proven: boolean; + patch: Partial; +}[]; + +export type AnimPresetId = (typeof ANIM_PRESETS)[number]["id"]; + +/** The preset an animation currently matches on every field a preset sets, if any. */ +export const presetOf = (a: Anim): AnimPresetId | null => + ANIM_PRESETS.find((p) => + (Object.keys(p.patch) as (keyof typeof p.patch)[]).every((k) => p.patch[k] === a[k]), + )?.id ?? null; + +/** Sun Circle's sun, field by field: `encodeAnim(STOCK_ANIM)` is ANIM_SEED. What "reset" goes back to. */ +export const STOCK_ANIM: Anim = { + duration: 2000, + raw4: -17, + raw6: 0, + raw8: 0, + raw10: 0, + start: 2645, + end: 2754, + raw16: 3817, + raw18: 3817, + flags: 0x88, + tail: [0, 0, 0, 0], +}; diff --git a/src/lib/modules/editor/core/document/sources.ts b/src/lib/modules/editor/core/document/sources.ts index b7c3e8b..2b10db3 100644 --- a/src/lib/modules/editor/core/document/sources.ts +++ b/src/lib/modules/editor/core/document/sources.ts @@ -224,6 +224,11 @@ export interface Sim { /** The clip a tap started and when (type 5); no time = none played since it came to rest. */ clip: number; clipAt: number | null; + /** When the screen last "woke", for the animated image (0x82 type 2); null = at rest. */ + wakeAt: number | null; + /** The Animation tab's timeline: hold animated images at `ms` into the sweep, and at `value` + * (0..100, null = what their source reads). null = follow the clock and the simulator. */ + scrub: { ms: number; value: number | null } | null; // widget-slot (0x85) imgs[0] is an on-watch "tap to configure" placeholder — the real // device only draws it in its own edit mode, never during normal time-telling, so the // live sim skips it by default. This is an editor-only preview toggle, not real data. @@ -290,6 +295,8 @@ export function defaultSim(): Sim { touch: null, clip: 0, clipAt: null, + wakeAt: null, + scrub: null, showSlotPlaceholders: false, }; } @@ -308,6 +315,8 @@ export const previewSim = (sim: Sim): Sim => ({ touch: null, clip: 0, clipAt: null, + wakeAt: null, + scrub: null, overrides: {}, }); diff --git a/src/lib/modules/editor/core/render/anim.ts b/src/lib/modules/editor/core/render/anim.ts new file mode 100644 index 0000000..5e7c616 --- /dev/null +++ b/src/lib/modules/editor/core/render/anim.ts @@ -0,0 +1,141 @@ +// Where the Watch Pro 2's animated image (0x82, type 2) sits at a given value and moment. +// +// A port of the stock app firmware (1.0.0.73) read from a disassembly and checked against the +// firmware's own code run in an emulator. Which parts are read from code and which are inferred +// is marked; tests/doc-anim.test.ts compares this with the firmware's output, row by row. +// +// - Position from an angle (0x1004BAE0, CONFIRMED). The angle is a float32 in degrees. Only for +// 180 < a <= 360. Each branch takes its own base before scaling by the constant 3.14 (a +// double), so no single formula covers both: +// a <= 270: t = a - 180 x = off4 + R - trunc(R sin rad) y = trunc(R cos rad) +// a > 270: t = a - 270 x = off4 + R - trunc(R cos rad) y = -trunc(R sin rad) +// rad = (t * 3.14) / 180, R = off16 as s16; 270 -> (off4, 0); 360 -> (off4 + R, -R) +// trunc is toward zero and x and y are summed and stored as 16-bit integers. For any other +// angle nothing is written and the image keeps the position it had. The image is only moved, +// never rotated. +// - Value to end angle (parser 0x100DB31E, CONFIRMED): for a source other than 0 and |v| <= 99, +// end = start + (end - start) * |v| / 100, an integer division truncating toward zero; +// otherwise the full range. +// - The sweep (timer 0x100DF2EC, CONFIRMED): one step per callback and the first 12 do nothing. +// Step k (1..) of N = duration / 18 is, all in float32 (0x100DF39A): +// deg = ((float)((end - start) * k) / (float)N + (float)start) / 10 +// a fractional angle, not rounded to tenths; at k >= N it snaps to end / 10. No easing. Flags +// bit 0 repeats it. +// - Not known: the callback period, FRAME_MS. The firmware asks its timer for 10 ms, but a step +// runs once per LVGL timer pass, and a watch showed about 2 s for duration 2000, so a pass +// about every frame (18 ms) is assumed. INFERRED; the display service that drives it was not +// traced. +// - Orbit mode needs flags bits 7 and 3 (0x88). Other modes are not modelled: the image stays +// at (off4, off6). +import type { Anim } from "../document/proc"; + +export interface AnimPlace { + dx: number; + dy: number; +} + +export const FRAME_MS = 18; +const DELAY_TICKS = 12; +/** ms after wake at which the motion has run its last step: the start delay plus every step. */ +export const animEndMs = (a: Anim) => (Math.floor(a.duration / FRAME_MS) + DELAY_TICKS) * FRAME_MS; +const PI = 3.14; // the firmware's own constant, a double + +const f32 = Math.fround; +/** 16-bit two's complement, as the firmware stores x and y. */ +const s16 = (n: number) => (n << 16) >> 16; + +/** The parser wraps both angles into +-3600 by adding or subtracting a turn. */ +const wrap = (a: number) => { + while (a > 3600) a -= 3600; + while (a < -3600) a += 3600; + return a; +}; + +/** The firmware's position for an angle in degrees as a float32, relative to the layer; null for + * an angle it ignores. */ +export function orbitAtDeg(a: Anim, angle: number): AnimPlace | null { + const deg = f32(angle); + + if (!(deg > 180 && deg <= 360)) return null; + const R = a.raw16; + let r4: number; + let r3: number; + + if (deg <= 270) { + if (deg === 270) { + r4 = -R; + r3 = 0; + } else { + const rad = (f32(deg - 180) * PI) / 180; + + r4 = -Math.trunc(R * Math.sin(rad)); + r3 = -Math.trunc(R * Math.cos(rad)); + } + } else if (deg === 360) { + r4 = 0; + r3 = R; + } else { + const rad = (f32(deg - 270) * PI) / 180; + + r4 = -Math.trunc(R * Math.cos(rad)); + r3 = Math.trunc(R * Math.sin(rad)); + } + return { dx: s16((R & 0xffff) + (a.raw4 & 0xffff) + r4), dy: s16(-r3) }; +} + +/** The same for an angle in tenths of a degree (how the body stores them). */ +export const orbitAt = (a: Anim, tenths: number) => orbitAtDeg(a, f32(f32(tenths) / 10)); + +/** + * @param value what the layer's source reads, or null when it has none (source 0) + * @param sinceWake ms since the screen woke, or Infinity at rest + */ +export function animPlace(a: Anim, value: number | null, sinceWake: number): AnimPlace { + const initial = { dx: a.raw4, dy: a.raw6 }; + + if ((a.flags & 0x88) !== 0x88) return initial; + const start = wrap(a.start); + const full = wrap(a.end); + const v = value === null ? 100 : Math.abs(Math.trunc(value)); + const end = v <= 99 ? start + Math.trunc(((full - start) * v) / 100) : full; + const steps = Math.floor(a.duration / 18); + // the angle in degrees after step k: float32 throughout, as the timer callback computes it + const degAt = (k: number) => + k >= steps || steps <= 0 + ? f32(f32(end) / 10) + : k <= 0 + ? f32(f32(start) / 10) + : f32(f32(f32(f32((end - start) * k) / f32(steps)) + f32(start)) / 10); + let k = Math.floor(sinceWake / FRAME_MS) - DELAY_TICKS; + + if (a.flags & 1 && steps > 0 && Number.isFinite(k) && k > 0) k %= steps + 1; + const now = orbitAtDeg(a, degAt(k)); + + if (now) return now; + // an angle the watch ignores writes nothing: the image keeps the last position it was given, + // or where it was created (the start angle's, else off4 and off6) + for (let j = Math.min(k, steps) - 1; j > 0; j--) { + const was = orbitAtDeg(a, degAt(j)); + + if (was) return was; + } + return orbitAtDeg(a, degAt(0)) ?? initial; +} + +/** Where the image goes between value 0 and value 100 at full sweep: the firmware's position at + * `steps` + 1 evenly spaced angles from the start to the end angle, relative to the layer's place. + * Angles the watch ignores are left out, as it leaves the image where it was. Empty unless the + * flags orbit. A picture of the motion, not of its timing. */ +export function animPath(a: Anim, steps = 48): AnimPlace[] { + if ((a.flags & 0x88) !== 0x88) return []; + const out: AnimPlace[] = []; + const s = wrap(a.start); + const e = wrap(a.end); + + for (let i = 0; i <= steps; i++) { + const p = orbitAt(a, s + Math.trunc(((e - s) * i) / steps)); + + if (p) out.push(p); + } + return out; +} diff --git a/src/lib/modules/editor/core/render/pixels.ts b/src/lib/modules/editor/core/render/pixels.ts index 8e9bc84..bb1f775 100644 --- a/src/lib/modules/editor/core/render/pixels.ts +++ b/src/lib/modules/editor/core/render/pixels.ts @@ -98,8 +98,8 @@ export async function resourceFromFile(file: File, cf: number): Promise { - const r = encodePixels(new Uint8ClampedArray(w * h * 4), w, h, 5); +export async function blankFrame(w: number, h: number, cf = 5): Promise { + const r = encodePixels(new Uint8ClampedArray(w * h * 4), w, h, cf); r.bitmap = await bitmapOf(r); return r; diff --git a/src/lib/modules/editor/core/render/render.ts b/src/lib/modules/editor/core/render/render.ts index bc95007..1fdb56e 100644 --- a/src/lib/modules/editor/core/render/render.ts +++ b/src/lib/modules/editor/core/render/render.ts @@ -32,7 +32,8 @@ import { } from "./canvas"; import { FULL_BLEED_R, drawProceduralArc, drawSector, hexRGB, progressFrac } from "./arc"; import { CENTER, SCREEN } from "./screen"; -import { procOf } from "../document/proc"; +import { animOf, procOf } from "../document/proc"; +import { animPlace } from "./anim"; import { drawProc } from "./proc"; /** One layer drawn at a scale or angle it doesn't have yet — what a corner or rotate drag shows @@ -308,7 +309,17 @@ function drawPicked( idx = ((v % frames.length) + frames.length) % frames.length; } const b = bmpOf(env.store, frames[idx]); + const anim = animOf(l); + if (anim && b) { + const { scrub, wakeAt } = env.sim; + const since = scrub ? scrub.ms : wakeAt === null ? Infinity : Date.now() - wakeAt; + // source 0 always runs the full sweep on the watch, whatever the timeline says + const value = source ? (scrub?.value ?? idValue(source, env.sim, env.t)) : null; + const { dx, dy } = animPlace(anim, value, since); + + return blit(env, l, b, x + dx, y + dy); + } return b ? blit(env, l, b, x, y) : null; } diff --git a/src/lib/modules/editor/i18n-inspector.ts b/src/lib/modules/editor/i18n-inspector.ts index 8939c53..4c88ea5 100644 --- a/src/lib/modules/editor/i18n-inspector.ts +++ b/src/lib/modules/editor/i18n-inspector.ts @@ -71,6 +71,63 @@ const en = { `Watch 3 Pro widget (type ${type}): the watch lays it out itself. Replace its images; their count and size are fixed by the widget.`, panels: ["Weather", "Heart rate", "Blood oxygen", "Stress", "Sleep"], framesByValue: "frames · index = value", + animLayers: "animated images", + animNone: "No animated images on this screen. Add one from the layer menu: Animated layer.", + animSettings: "effect", + animTimeline: "timeline", + animPlay: "play", + animFollow: "follow simulator", + animAt: "time into the sweep, ms", + animValue: "value, % (the driving source)", + animIssue: { + duration: "Below 18 ms the watch does not animate; it jumps to the end.", + flags: + "Only flags 0x88 (and 0x89, which repeats) are known to orbit; other values are untested.", + angle: "The watch moves the image only for angles above 180° up to 360°.", + radius: "Outside 0..8000 px the position can wrap on the watch.", + }, + wakeScreen: "wake the screen", + animation: "Animation", + animDuration: "sweep duration, ms", + animStart: "start angle, ° (value 0)", + animEnd: "end angle, ° (value 100)", + animRaw: "raw fields", + animPresets: "effect", + animGroup: { + slide: "Slide", + arc: "Arc", + }, + animNoFade: + "This widget only moves the image: fades and other effects are not available on the watch.", + animPreset: { + rise: "Rise (stock sun)", + set: "Set (stock moon)", + riseSlow: "Slow rise", + setSlow: "Slow set", + arcUp: "Arc up", + arcDown: "Arc down", + arcSmall: "Small arc", + quarterUp: "Quarter arc up", + quarterDown: "Quarter arc down", + dropLong: "Long drop", + }, + animUntested: "Not yet tried on a Watch Pro 2.", + animProven: "Played on a Watch Pro 2.", + animSpeed: "sweep time, s", + animDirection: "direction", + animRises: "rises", + animSets: "sets", + animLoop: "repeat", + animLoopHint: "Repeating is read from the firmware; not yet tried on a watch.", + animReset: "reset to stock", + animAdvanced: "advanced", + animAdvancedHint: + "The firmware reads these, but what they do is not confirmed on a watch. A value out of range shows a warning; nothing is blocked.", + animFlags: "flags (+20)", + animPath: "motion path", + animTravel: (w: number, h: number) => `moves ${w} px sideways and ${h} px up or down`, + animHint: + "Watch Pro 2 animated image (type 2): it sweeps in each time the screen wakes and stops where the driving source says. Angles are read from the firmware; the raw fields are read by it too, but what they do isn't known yet, so they are kept as found.", ringArt: "ring art", useRingBitmap: "use a ring bitmap", ringArtHint: "a full ring, drawn at 100% — the watch clips it to the filled sector", @@ -292,6 +349,64 @@ export const t = dict(en, { `Виджет Watch 3 Pro (тип ${type}): часы сами его раскладывают. Изображения можно заменять, их число и размер задаёт виджет.`, panels: ["Погода", "Пульс", "Кислород в крови", "Стресс", "Сон"], framesByValue: "кадры · индекс = значение", + animLayers: "анимированные изображения", + animNone: + "На этом экране нет анимированных изображений. Добавьте через меню слоёв: Анимированный слой.", + animSettings: "эффект", + animTimeline: "таймлайн", + animPlay: "играть", + animFollow: "следовать симулятору", + animAt: "время развёртки, мс", + animValue: "значение, % (источник данных)", + animIssue: { + duration: "Меньше 18 мс часы не анимируют, а сразу прыгают в конец.", + flags: + "Известно, что орбиту задают только флаги 0x88 (и 0x89 с повтором); остальное не проверено.", + angle: "Часы двигают изображение только для углов больше 180° и до 360°.", + radius: "Вне 0..8000 пикс. позиция на часах может переполниться.", + }, + wakeScreen: "разбудить экран", + animation: "Анимация", + animDuration: "длительность, мс", + animStart: "начальный угол, ° (значение 0)", + animEnd: "конечный угол, ° (значение 100)", + animRaw: "сырые поля", + animPresets: "эффект", + animGroup: { + slide: "Скольжение", + arc: "Дуга", + }, + animNoFade: + "Этот виджет только перемещает изображение: затухание и другие эффекты на часах недоступны.", + animPreset: { + rise: "Восход (солнце из Sun Circle)", + set: "Закат (луна из Sun Circle)", + riseSlow: "Медленный восход", + setSlow: "Медленный закат", + arcUp: "Дуга вверх", + arcDown: "Дуга вниз", + arcSmall: "Малая дуга", + quarterUp: "Четверть дуги вверх", + quarterDown: "Четверть дуги вниз", + dropLong: "Длинный спуск", + }, + animUntested: "Ещё не проверено на Watch Pro 2.", + animProven: "Проверено на Watch Pro 2.", + animSpeed: "время развёртки, с", + animDirection: "направление", + animRises: "вверх", + animSets: "вниз", + animLoop: "повтор", + animLoopHint: "Повтор прочитан из прошивки; на часах ещё не проверен.", + animReset: "вернуть как в оригинале", + animAdvanced: "дополнительно", + animAdvancedHint: + "Прошивка читает эти поля, но что они делают, на часах не подтверждено. Значение вне диапазона даёт предупреждение; ничего не блокируется.", + animFlags: "флаги (+20)", + animPath: "траектория", + animTravel: (w, h) => `смещение: ${w} пикс. вбок и ${h} пикс. вверх или вниз`, + animHint: + "Анимированное изображение Watch Pro 2 (тип 2): выезжает при каждом пробуждении экрана и останавливается там, где указывает источник данных. Углы прочитаны из прошивки; сырые поля она тоже читает, но что они делают — пока неизвестно, поэтому они хранятся как есть.", ringArt: "графика кольца", useRingBitmap: "задать картинку кольца", ringArtHint: "полное кольцо на 100% — часы обрезают его до заполненного сектора", @@ -508,6 +623,64 @@ export const t = dict(en, { `Віджет Watch 3 Pro (тип ${type}): годинник сам його розкладає. Зображення можна замінювати, їхню кількість і розмір задає віджет.`, panels: ["Погода", "Пульс", "Кисень у крові", "Стрес", "Сон"], framesByValue: "кадри · індекс = значення", + animLayers: "анімовані зображення", + animNone: + "На цьому екрані немає анімованих зображень. Додайте через меню шарів: Анімований шар.", + animSettings: "ефект", + animTimeline: "таймлайн", + animPlay: "грати", + animFollow: "слідувати симулятору", + animAt: "час розгортання, мс", + animValue: "значення, % (джерело даних)", + animIssue: { + duration: "Менше 18 мс годинник не анімує, а одразу стрибає в кінець.", + flags: + "Відомо, що орбіту задають лише прапорці 0x88 (і 0x89 з повтором); решта не перевірена.", + angle: "Годинник рухає зображення лише для кутів понад 180° до 360°.", + radius: "Поза 0..8000 пікс. позиція на годиннику може переповнитися.", + }, + wakeScreen: "розбудити екран", + animation: "Анімація", + animDuration: "тривалість, мс", + animStart: "початковий кут, ° (значення 0)", + animEnd: "кінцевий кут, ° (значення 100)", + animRaw: "сирі поля", + animPresets: "ефект", + animGroup: { + slide: "Ковзання", + arc: "Дуга", + }, + animNoFade: + "Цей віджет лише переміщує зображення: згасання й інші ефекти на годиннику недоступні.", + animPreset: { + rise: "Схід (сонце з Sun Circle)", + set: "Захід (місяць з Sun Circle)", + riseSlow: "Повільний схід", + setSlow: "Повільний захід", + arcUp: "Дуга вгору", + arcDown: "Дуга вниз", + arcSmall: "Мала дуга", + quarterUp: "Чверть дуги вгору", + quarterDown: "Чверть дуги вниз", + dropLong: "Довгий спуск", + }, + animUntested: "Ще не перевірено на Watch Pro 2.", + animProven: "Перевірено на Watch Pro 2.", + animSpeed: "час розгортання, с", + animDirection: "напрямок", + animRises: "вгору", + animSets: "вниз", + animLoop: "повтор", + animLoopHint: "Повтор прочитано з прошивки; на годиннику ще не перевірено.", + animReset: "повернути як в оригіналі", + animAdvanced: "додатково", + animAdvancedHint: + "Прошивка читає ці поля, але що вони роблять, на годиннику не підтверджено. Значення поза діапазоном дає попередження; нічого не блокується.", + animFlags: "прапорці (+20)", + animPath: "траєкторія", + animTravel: (w, h) => `зсув: ${w} пікс. вбік і ${h} пікс. угору або вниз`, + animHint: + "Анімоване зображення Watch Pro 2 (тип 2): виїжджає щоразу, коли екран прокидається, і зупиняється там, куди вказує джерело даних. Кути прочитані з прошивки; сирі поля вона теж читає, але що вони роблять — поки невідомо, тому вони зберігаються як є.", ringArt: "графіка кільця", useRingBitmap: "задати зображення кільця", ringArtHint: "повне кільце на 100% — годинник обрізає його до заповненого сектора", @@ -724,6 +897,64 @@ export const t = dict(en, { `Widget del Watch 3 Pro (tipo ${type}): el reloj lo compone por sí mismo. Puedes reemplazar sus imágenes; el número y el tamaño los fija el widget.`, panels: ["Tiempo", "Frecuencia cardíaca", "Oxígeno en sangre", "Estrés", "Sueño"], framesByValue: "fotogramas · índice = valor", + animLayers: "imágenes animadas", + animNone: + "No hay imágenes animadas en esta pantalla. Añade una desde el menú de capas: Capa animada.", + animSettings: "efecto", + animTimeline: "línea de tiempo", + animPlay: "reproducir", + animFollow: "seguir el simulador", + animAt: "tiempo del barrido, ms", + animValue: "valor, % (la fuente de datos)", + animIssue: { + duration: "Por debajo de 18 ms el reloj no anima; salta al final.", + flags: + "Solo se sabe que los flags 0x88 (y 0x89, que repite) orbitan; el resto no está probado.", + angle: "El reloj solo mueve la imagen para ángulos mayores de 180° hasta 360°.", + radius: "Fuera de 0..8000 px la posición puede desbordarse en el reloj.", + }, + wakeScreen: "activar la pantalla", + animation: "Animación", + animDuration: "duración, ms", + animStart: "ángulo inicial, ° (valor 0)", + animEnd: "ángulo final, ° (valor 100)", + animRaw: "campos sin procesar", + animPresets: "efecto", + animGroup: { + slide: "Deslizamiento", + arc: "Arco", + }, + animNoFade: + "Este widget solo mueve la imagen: los fundidos y otros efectos no están disponibles en el reloj.", + animPreset: { + rise: "Salida (sol de Sun Circle)", + set: "Puesta (luna de Sun Circle)", + riseSlow: "Salida lenta", + setSlow: "Puesta lenta", + arcUp: "Arco arriba", + arcDown: "Arco abajo", + arcSmall: "Arco pequeño", + quarterUp: "Cuarto de arco arriba", + quarterDown: "Cuarto de arco abajo", + dropLong: "Caída larga", + }, + animUntested: "Aún no probado en un Watch Pro 2.", + animProven: "Probado en un Watch Pro 2.", + animSpeed: "duración del barrido, s", + animDirection: "dirección", + animRises: "sube", + animSets: "baja", + animLoop: "repetir", + animLoopHint: "La repetición se lee del firmware; aún no probada en un reloj.", + animReset: "restablecer al original", + animAdvanced: "avanzado", + animAdvancedHint: + "El firmware lee estos campos, pero lo que hacen no está confirmado en un reloj. Un valor fuera de rango muestra un aviso; no se bloquea nada.", + animFlags: "flags (+20)", + animPath: "trayectoria", + animTravel: (w, h) => `se mueve ${w} px de lado y ${h} px arriba o abajo`, + animHint: + "Imagen animada del Watch Pro 2 (tipo 2): entra cada vez que se activa la pantalla y se detiene donde indica la fuente de datos. Los ángulos se leen del firmware; los campos sin procesar también los lee, pero aún no se sabe qué hacen, así que se conservan tal cual.", ringArt: "imagen del anillo", useRingBitmap: "usar imagen de anillo", ringArtHint: "un anillo completo, al 100% — el reloj lo recorta al sector lleno", @@ -940,6 +1171,61 @@ export const t = dict(en, { `Watch 3 Pro विजेट (टाइप ${type}): घड़ी इसका लेआउट खुद बनाती है। इमेज बदली जा सकती हैं; उनकी संख्या और साइज़ विजेट तय करता है।`, panels: ["मौसम", "हृदय गति", "ब्लड ऑक्सीजन", "तनाव", "नींद"], framesByValue: "फ़्रेम · इंडेक्स = मान", + animLayers: "एनिमेटेड इमेज", + animNone: "इस स्क्रीन पर कोई एनिमेटेड इमेज नहीं है। लेयर मेनू से जोड़ें: एनिमेटेड लेयर।", + animSettings: "प्रभाव", + animTimeline: "टाइमलाइन", + animPlay: "चलाएँ", + animFollow: "सिमुलेटर का अनुसरण", + animAt: "स्वीप में समय, ms", + animValue: "मान, % (डेटा स्रोत)", + animIssue: { + duration: "18 ms से कम पर घड़ी एनिमेट नहीं करती; सीधे अंत पर पहुँचती है।", + flags: "केवल फ़्लैग 0x88 (और दोहराने वाला 0x89) का ऑर्बिट ज्ञात है; बाकी अपरीक्षित हैं।", + angle: "घड़ी इमेज को केवल 180° से ऊपर से 360° तक के कोणों पर हिलाती है।", + radius: "0..8000 px के बाहर घड़ी पर स्थिति ओवरफ़्लो हो सकती है।", + }, + wakeScreen: "स्क्रीन जगाएँ", + animation: "एनिमेशन", + animDuration: "अवधि, ms", + animStart: "प्रारंभ कोण, ° (मान 0)", + animEnd: "अंतिम कोण, ° (मान 100)", + animRaw: "रॉ फ़ील्ड", + animPresets: "प्रभाव", + animGroup: { + slide: "स्लाइड", + arc: "चाप", + }, + animNoFade: "यह विजेट केवल छवि को हिलाता है: फ़ेड और अन्य प्रभाव घड़ी पर उपलब्ध नहीं हैं।", + animPreset: { + rise: "उदय (Sun Circle का सूरज)", + set: "अस्त (Sun Circle का चाँद)", + riseSlow: "धीमा उदय", + setSlow: "धीमा अस्त", + arcUp: "चाप ऊपर", + arcDown: "चाप नीचे", + arcSmall: "छोटा चाप", + quarterUp: "चौथाई चाप ऊपर", + quarterDown: "चौथाई चाप नीचे", + dropLong: "लंबी गिरावट", + }, + animUntested: "Watch Pro 2 पर अभी आज़माया नहीं गया।", + animProven: "Watch Pro 2 पर चलकर देखा गया।", + animSpeed: "स्वीप समय, सेकंड", + animDirection: "दिशा", + animRises: "ऊपर", + animSets: "नीचे", + animLoop: "दोहराएँ", + animLoopHint: "दोहराव फ़र्मवेयर से पढ़ा गया है; घड़ी पर अभी आज़माया नहीं गया।", + animReset: "मूल पर लौटें", + animAdvanced: "उन्नत", + animAdvancedHint: + "फ़र्मवेयर ये फ़ील्ड पढ़ता है, पर इनका असर घड़ी पर पुष्ट नहीं है। सीमा से बाहर मान पर चेतावनी दिखती है; कुछ रोका नहीं जाता।", + animFlags: "फ़्लैग (+20)", + animPath: "गति पथ", + animTravel: (w, h) => `${w} px बग़ल में और ${h} px ऊपर या नीचे चलता है`, + animHint: + "Watch Pro 2 की एनिमेटेड इमेज (टाइप 2): हर बार स्क्रीन जागने पर अंदर आती है और डेटा स्रोत के बताए स्थान पर रुकती है। कोण फ़र्मवेयर से पढ़े गए हैं; रॉ फ़ील्ड भी वह पढ़ता है, पर वे क्या करते हैं यह अभी पता नहीं, इसलिए उन्हें जस का तस रखा गया है।", ringArt: "रिंग आर्ट", useRingBitmap: "रिंग इमेज लगाएं", ringArtHint: "पूरी रिंग, 100% पर — घड़ी इसे भरे हुए हिस्से तक काटती है", diff --git a/src/lib/modules/editor/i18n.ts b/src/lib/modules/editor/i18n.ts index e8e76ea..f18c314 100644 --- a/src/lib/modules/editor/i18n.ts +++ b/src/lib/modules/editor/i18n.ts @@ -84,6 +84,8 @@ export const t = dict( addLayer: "Add a layer", imageFile: "Image…", emptyImage: "Empty image", + animTab: "Animation", + animatedLayer: "Animated layer", handFile: "Hand…", progressLine: "Progress line", vProgressLine: "Vertical progress line", @@ -278,6 +280,8 @@ export const t = dict( addLayer: "Добавить слой", imageFile: "Изображение…", emptyImage: "Пустое изображение", + animTab: "Анимация", + animatedLayer: "Анимированный слой", handFile: "Стрелка…", progressLine: "Полоса прогресса", vProgressLine: "Вертикальная полоса прогресса", @@ -461,6 +465,8 @@ export const t = dict( addLayer: "Додати шар", imageFile: "Зображення…", emptyImage: "Порожнє зображення", + animTab: "Анімація", + animatedLayer: "Анімований шар", handFile: "Стрілка…", progressLine: "Смуга прогресу", vProgressLine: "Вертикальна смуга прогресу", @@ -643,6 +649,8 @@ export const t = dict( addLayer: "Añadir capa", imageFile: "Imagen…", emptyImage: "Imagen vacía", + animTab: "Animación", + animatedLayer: "Capa animada", handFile: "Manecilla…", progressLine: "Barra de progreso", vProgressLine: "Barra de progreso vertical", @@ -825,6 +833,8 @@ export const t = dict( addLayer: "लेयर जोड़ें", imageFile: "इमेज…", emptyImage: "खाली इमेज", + animTab: "एनिमेशन", + animatedLayer: "एनिमेटेड लेयर", handFile: "सुई…", progressLine: "प्रोग्रेस लाइन", vProgressLine: "खड़ी प्रोग्रेस लाइन", diff --git a/src/lib/modules/editor/model/create.model.ts b/src/lib/modules/editor/model/create.model.ts index e15246d..63a63f9 100644 --- a/src/lib/modules/editor/model/create.model.ts +++ b/src/lib/modules/editor/model/create.model.ts @@ -29,6 +29,7 @@ import { blankScreen, newGroup, newHand, + newAnimated, newImage, newNumber, newProgressLine, @@ -69,6 +70,8 @@ export const numberAdded = createEvent(); /** An image widget with no art yet: one transparent frame, replaced later by a dropped file or * the font generator — for when the picture doesn't exist at add time. */ export const imageAdded = createEvent(); +/** A Watch Pro 2 animated image (0x82, type 2), seeded from Sun Circle. */ +export const animatedAdded = createEvent(); export const slotAdded = createEvent(); /** A progress line: one pre-drawn frame per step of its source (see LINE_SOURCES). */ export const progressLineAdded = createEvent<{ dir: "horizontal" | "vertical"; on: LineSource }>(); @@ -152,6 +155,23 @@ const addImageFx = attach({ }, }); +// One transparent 466x466 frame: the art comes later. cf 5, not Sun Circle's cf 4 — cf 4 has no +// alpha, so a blank frame in it is an opaque black disc over the whole screen. +const addAnimatedFx = attach({ + source: $screen, + async effect(screen) { + const r = await blankFrame(466, 466); + const id = newImageId(); + + return { + screen, + assets: new Map([[id, { id, cf: r.cf, w: r.w, h: r.h, data: r.data }]]), + cache: new Map([[id, { bitmap: r.bitmap }]]), + layer: newAnimated([id]), + }; + }, +}); + // Ten transparent frames, one per digit: a number widget whose art comes later, from a font or // from PNGs dropped on the frames one at a time. The size is a placeholder — both paths bring // their own (replaceImageFx takes the file's, the generator the font cell's). @@ -395,6 +415,10 @@ sample({ clock: imageAdded, target: addImageFx, }); +sample({ + clock: animatedAdded, + target: addAnimatedFx, +}); sample({ clock: slotAdded, target: addSlotFx, @@ -407,6 +431,7 @@ sample({ clock: [ addWidgetFx.doneData, addImageFx.doneData, + addAnimatedFx.doneData, addNumberFx.doneData, addSlotFx.doneData, addProgressLineFx.doneData, @@ -421,6 +446,7 @@ sample({ clock: [ addWidgetFx.doneData, addImageFx.doneData, + addAnimatedFx.doneData, addNumberFx.doneData, addSlotFx.doneData, addProgressLineFx.doneData, @@ -433,6 +459,7 @@ sample({ clock: [ addWidgetFx.doneData, addImageFx.doneData, + addAnimatedFx.doneData, addNumberFx.doneData, addSlotFx.doneData, addProgressLineFx.doneData, @@ -610,6 +637,7 @@ sample({ clock: [ addWidgetFx.failData, addImageFx.failData, + addAnimatedFx.failData, addNumberFx.failData, glyphsFx.failData, addSlotFx.failData, diff --git a/src/lib/modules/editor/model/edit.model.ts b/src/lib/modules/editor/model/edit.model.ts index aff854b..f0de155 100644 --- a/src/lib/modules/editor/model/edit.model.ts +++ b/src/lib/modules/editor/model/edit.model.ts @@ -24,9 +24,11 @@ import { shiftLayer, siblingsOf, ungroup, + withAnim, withPanel, wrapInGroup, } from "../core/document/edits"; +import type { Anim } from "../core/document/proc"; import { newCondition, newGroup } from "../core/document/factory"; import { TIME_RING_RANGE, gaugeOnSource } from "../core/render/arc"; import { FRAME_LABELS } from "../core/document/sources"; @@ -109,6 +111,8 @@ export const panelSet = createEvent<{ id: NodeId; panel: number }>(); /** meta.source — the data a widget reads. Not a plain patch: value-indexed sources also fix the * widget's frame count. */ export const sourceIdSet = createEvent<{ id: NodeId; source: number }>(); +/** The Watch Pro 2 animated image's fields. Through `committed`, so a no-op keeps the undo step. */ +export const animPatched = createEvent<{ id: NodeId; patch: Partial }>(); /** A layer that was just created and should become the selection. Shared with create.model. */ export const selectAdded = createEvent<{ added: NodeId }>(); @@ -283,6 +287,15 @@ sample({ target: committed, }); +// committed doesn't check the lock (unlocking goes through it), so this edit does, as layerPatched +sample({ + clock: animPatched, + fn: ({ id, patch }) => ({ + edit: (doc: Doc) => (findLayer(doc, id)?.locked ? doc : withAnim(doc, id, patch)), + }), + target: committed, +}); + sample({ clock: layerFlagsSet, filter: ({ ids }) => ids.length > 0, diff --git a/src/lib/modules/editor/model/selection.model.ts b/src/lib/modules/editor/model/selection.model.ts index 55be1f9..ec3cecb 100644 --- a/src/lib/modules/editor/model/selection.model.ts +++ b/src/lib/modules/editor/model/selection.model.ts @@ -103,10 +103,12 @@ sample({ }, target: select, }); -// opening a layer's properties is what the user means by clicking it +// opening a layer's properties is what the user means by clicking it — except on the Animation +// tab, where picking a layer is how its list is used sample({ clock: [select, selectToggled], - filter: Boolean, + source: $rightPanel, + filter: (panel, picked) => Boolean(picked) && panel !== "anim", fn: () => "props" as const, target: $rightPanel, }); diff --git a/src/lib/modules/editor/model/sim.model.ts b/src/lib/modules/editor/model/sim.model.ts index 14fd5c1..959524f 100644 --- a/src/lib/modules/editor/model/sim.model.ts +++ b/src/lib/modules/editor/model/sim.model.ts @@ -1,21 +1,43 @@ // The simulator: the fake watch state the canvas renders against (time, steps, accent colour) // plus the list of data sources the current document actually reads, which is what the panel // offers to override. -import { createEvent, createStore, sample } from "effector"; -import { collectIdsDoc, defaultSim, type Sim } from "../core/document/sources"; -import { CLIPS, hasProc, RINGS } from "../core/document/proc"; +import { combine, createEvent, createStore, sample } from "effector"; +import { collectIdsDoc, defaultSim, idValue, timeParts, type Sim } from "../core/document/sources"; +import { CLIPS, animatedIn, hasProc, RINGS } from "../core/document/proc"; +import { $screen, $selected } from "./selection.model"; import { nextClip } from "../core/render/proc-scene"; import type { Point } from "../core/render/canvas"; import type { Doc } from "../core/document/doc"; import { $doc, docLoaded } from "./doc.model"; +import { rightPanelSet } from "./ui.model"; // ---- stores ---- export const $sim = createStore(defaultSim()); /** Every data source appearing in the document, with the max its widget declares. */ export const $ids = createStore<{ id: number; max: number }[]>([]); +/** The Animation tab's layers: every animated image on the screen being edited. */ +export const $animLayers = combine($doc, $screen, (doc, screen) => + animatedIn(doc?.screens.find((s) => s.kind === screen)?.layers ?? []), +); +/** The one the tab edits: the selected layer if it is animated, else the first. */ +export const $animCurrent = combine( + $animLayers, + $selected, + (layers, sel) => layers.find((l) => l.id === sel[0]?.id) ?? layers[0] ?? null, +); +/** The value the canvas animates the current layer to: the timeline's, else its source's + * (null for source 0, which always runs the full sweep). */ +export const $animValue = combine($animCurrent, $sim, (l, sim) => { + const source = l?.kind === "image" ? l.meta.source : 0; + + return source ? (sim.scrub?.value ?? idValue(source, sim, timeParts(sim))) : null; +}); + // ---- events ---- export const simPatched = createEvent>(); +/** The Animation tab went away (the phone's sheet closes without touching rightPanelSet). */ +export const animPanelClosed = createEvent(); export const overrideSet = createEvent<{ id: number; value: number | string }>(); /** A finger on the preview, for the widgets that answer one (types 4 and 5). */ export const watchPressed = createEvent(); @@ -27,16 +49,28 @@ const answers = (doc: Doc | null, type: number) => Boolean(doc?.screens.some((s) => hasProc(s.layers, type))); // ---- business logic ---- +// What the animated image (0x82, type 2) reads is the daylight %, so moving the clock or the sun +// times replays its sweep, as waking the screen does. Harmless for a face without one. +const MOVES_SUN = ["time", "sunrise", "sunset", "live"] as const; + sample({ clock: simPatched, source: $sim, - fn: (sim, patch) => ({ ...sim, ...patch }), + fn: (sim, patch) => ({ + ...sim, + ...(MOVES_SUN.some((k) => k in patch) ? { wakeAt: Date.now() } : {}), + ...patch, + }), target: $sim, }); sample({ clock: overrideSet, source: $sim, - fn: (sim, { id, value }) => ({ ...sim, overrides: { ...sim.overrides, [id]: value } }), + fn: (sim, { id, value }) => ({ + ...sim, + wakeAt: Date.now(), + overrides: { ...sim.overrides, [id]: value }, + }), target: $sim, }); // the source list follows the document: a new layer can introduce a source, deleting one can @@ -76,3 +110,11 @@ sample({ fn: (sim) => ({ ...sim, touch: null, clip: 0, clipAt: null }), target: $sim, }); +// the timeline holds the canvas only while its tab is open (or until another face loads) +sample({ + clock: [rightPanelSet, docLoaded, animPanelClosed], + source: $sim, + filter: (sim, clock) => sim.scrub !== null && clock !== "anim", + fn: (sim) => ({ ...sim, scrub: null }), + target: $sim, +}); diff --git a/src/lib/modules/editor/model/ui.model.ts b/src/lib/modules/editor/model/ui.model.ts index 56b0e16..c9906e2 100644 --- a/src/lib/modules/editor/model/ui.model.ts +++ b/src/lib/modules/editor/model/ui.model.ts @@ -6,14 +6,14 @@ import { createEvent, createStore, sample } from "effector"; /** Right-side panel tab. Driven by the `select` event rather than derived from the selection: * the selection store also changes when a simulator tweak re-selects the same layer, and * deriving would flip the tab back to Properties on every input. */ -export const $rightPanel = createStore<"props" | "sim">("props"); +export const $rightPanel = createStore<"props" | "anim" | "sim">("props"); export const $err = createStore(""); /** Keep a resize proportional. One flag for both ways in: the props panel's link toggle and a * corner drag on the canvas (shift inverts it there, as everywhere else). */ export const $lockAspect = createStore(true); // ---- events ---- -export const rightPanelSet = createEvent<"props" | "sim">(); +export const rightPanelSet = createEvent<"props" | "anim" | "sim">(); export const errored = createEvent(); export const lockAspectToggled = createEvent(); diff --git a/src/lib/modules/editor/pages/editor.svelte b/src/lib/modules/editor/pages/editor.svelte index dda9b7b..45d1714 100644 --- a/src/lib/modules/editor/pages/editor.svelte +++ b/src/lib/modules/editor/pages/editor.svelte @@ -53,6 +53,7 @@ import TreePanel from "../components/TreePanel.svelte"; import PropsPanel from "../components/PropsPanel.svelte"; import SimPanel from "../components/SimPanel.svelte"; + import AnimationPanel from "../components/AnimationPanel.svelte"; import ShortcutsDialog from "../components/ShortcutsDialog.svelte"; import { t } from "../i18n"; import { t as deviceT } from "$lib/modules/device/i18n"; @@ -152,7 +153,7 @@ let dirInput = $state(); let binsInput = $state(); - let mobilePanel = $state<"tree" | "props" | "sim" | null>(null); // drawer on mobile + let mobilePanel = $state<"tree" | "props" | "anim" | "sim" | null>(null); // drawer on mobile let helpOpen = $state(false); // the `?` overlay let hits: LayerHit[] = []; @@ -540,6 +541,7 @@ ]); const panelItems = $derived([ { value: "props", label: $t.properties }, + { value: "anim", label: $t.animTab, disabled: !$doc }, { value: "sim", label: $t.simulator, disabled: !$doc }, ]); const mobileTitle = $derived( @@ -547,9 +549,11 @@ ? $t.tree : mobilePanel === "props" ? $t.properties - : mobilePanel === "sim" - ? $t.simulator - : undefined, + : mobilePanel === "anim" + ? $t.animTab + : mobilePanel === "sim" + ? $t.simulator + : undefined, ); @@ -859,12 +863,14 @@ full items={panelItems} value={$rightPanel} - onChange={(v) => rightPanelSet(v as "props" | "sim")} + onChange={(v) => rightPanelSet(v as "props" | "anim" | "sim")} />
{#if $rightPanel === "sim"} + {:else if $rightPanel === "anim"} + {:else} {/if} @@ -874,11 +880,11 @@ {#if $doc}
- {#each [["tree", "account_tree", $t.tree], ["props", "tune", $t.propsShort], ["sim", "play_arrow", $t.simShort]] as [id, icon, label] (id)} + {#each [["tree", "account_tree", $t.tree], ["props", "tune", $t.propsShort], ["anim", "wb_twilight", $t.animTab], ["sim", "play_arrow", $t.simShort]] as [id, icon, label] (id)}