Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix: Halloween decorations: no phone crash, own lazy chunk, lighter idle cost; translated Night Shift words

aashu7e6dedeb1a33
diff --git a/.ai/lessons.md b/.ai/lessons.md
index bc5ff1559d..bea0832b83 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -4059,3 +4059,13 @@ The write was then removed (nothing reads it), so the rail always starts collaps
**Rule:** Put a seasonal or temporary behaviour on the removable unit itself (its `available` window and `mesh` on the `SeasonalTheme`, read by the shared resolver) and keep callers generic, so deleting the unit turns the behaviour off. Test the mechanism on a fixture, not on the instance. Keep ONE removal checklist, next to the code, and make every other comment point to it.
**Applies to:** `packages/utils/src/themes.ts` seasonal themes, `packages/react/src/Halloween/`, any feature flag, promo or seasonal UI.
+
+## The theme a page renders is not the theme the user picked
+
+**Context:** A seasonal theme made `getTheme` (`services/theme.server.ts`) return the seasonal name for everyone in season (2026-10).
+
+**Problem:** The ERP's onboarding theme step and `x+/account+/theme.tsx` also read `getTheme` to seed and post back the user's own pick. In season they posted the seasonal name, `themeColorValidator` refused it, and onboarding could not get past the theme step. The theme pickers meanwhile painted a chosen theme onto `<body>` while the server kept rendering the seasonal one.
+
+**Rule:** Keep "what to render" (`getTheme` → `resolveTheme`) and "what the user chose" (`getStoredTheme` → `storedTheme`) as two reads, and decide the season once, in the root loader (`Document` renders the name with `themeByName`). A picker that cannot take effect is disabled and says why (`useSeasonalTheme`, `SeasonalThemeNotice`).
+
+**Applies to:** `packages/utils/src/themes.ts`, every app's `services/theme.server.ts` and `root.tsx`, every theme picker.
diff --git a/.claude/rules/coding-conventions.md b/.claude/rules/coding-conventions.md
index 93decf92bb..04071f96c5 100644
--- a/.claude/rules/coding-conventions.md
+++ b/.claude/rules/coding-conventions.md
@@ -219,19 +219,30 @@ Themes are defined in `packages/utils/src/themes.ts` (`themes`, the only list
of theme names) and selected via the `useTheme()` hook
(`apps/erp/app/hooks/useTheme.tsx`). Each theme supplies HSL values for CSS
variables (`--primary`, `--background`, `--foreground`, `--card`, `--popover`,
-`--secondary`, `--muted`, `--accent`, `--destructive`). Theme names: `zinc`
+`--secondary`, `--muted`, `--accent`, `--destructive`) and its four `mesh`
+colors per mode (the ERP's onboarding backdrop). Theme names: `zinc`
(the default, `DEFAULT_THEME_NAME`), `neutral`, `red`, `orange`, `yellow`,
`green`, `blue`, `violet`, plus seasonal ones.
The choice is a `theme` cookie per browser, never a database column. Each app's
-`getTheme` (`services/theme.server.ts`) resolves through `resolveTheme`, which
-returns the default for a name no longer in `themes`, so removing a theme
-needs no migration and breaks no browser that still holds it.
+`getTheme` (`services/theme.server.ts`) is the theme to RENDER: it resolves
+through `resolveTheme`, which returns the default for a name no longer in
+`themes`, so removing a theme needs no migration and breaks no browser that
+still holds it. A route that shows or posts back the user's own pick (the
+ERP's onboarding theme step and `x+/account+/theme.tsx`) reads
+`getStoredTheme` (`storedTheme`) instead: in season `getTheme` returns the
+seasonal theme, which `themeColorValidator` refuses. The root `Document`
+renders the loader's name with `themeByName`, so the season is decided once,
+on the server.
A seasonal theme (`seasonalThemes`, never in `themes`) is not a choice: while
it is in season it replaces every theme for everyone, and when the season
ends everyone is back on their own cookie. No picker lists it and
-`themeColorValidator` refuses it. Its season is the `available` window on the
+`themeColorValidator` refuses it. While one is on, every picker (the ERP
+avatar menu and mobile profile sheet, the onboarding theme step, Account →
+Appearance) is disabled and shows `SeasonalThemeNotice`; both it and
+`useSeasonalTheme` (`@carbon/react`) read the root loader's theme through
+`isSeasonalTheme`, so they survive the theme's removal. Its season is the `available` window on the
theme (`ThemeWindow`, month and day inside one calendar year; Halloween is
October 31 only), and that window is the only switch: no flag, no deploy on
the day. The server has no time zone for the user, so `isInSeason` is true
@@ -239,8 +250,8 @@ while it is the season anywhere on Earth (UTC+14 reaches `from`, UTC-12 has
not left `to`); a fixed UTC check turned it on hours late east of UTC. To
preview one locally, widen its window. A seasonal theme lives in its own file
(`halloween-theme.ts`) and declares everything about itself on the
-`SeasonalTheme` object (its window, its `mesh` colors read through
-`seasonalMeshColors`), so no other code names it: removing it is that file,
+`SeasonalTheme` object (its window, its colors and `mesh`), so no other code
+names it: removing it is that file,
its `seasonalThemes` entry and its `index.ts` export. `themes.test.ts` tests
the window on a fixture and loops over `seasonalThemes`, so it survives the
removal unchanged.
@@ -250,19 +261,25 @@ Oct 31 date marker, the "boo" ghost) live in `packages/react/src/Halloween/`,
exported as `@carbon/react/Halloween` and mounted once in each shell
(`<HalloweenLayer />` in the ERP and MES `x+/_layout.tsx`). `useHalloween`
(`season.ts`) is the one check they sit behind — the root loader's theme is
-`halloween` — so nothing renders, styles or listens for anyone else. The
+`halloween` — so nothing renders, styles or listens for anyone else, and
+`HalloweenLayer.tsx` is all the shells import: the decorations
+(`Decorations.tsx`) are their own chunk, loaded only while it is on. The
+folder's shared maths (seeded randomness, easing, whole-number helpers built
+on `Math.trunc` because `no-raw-rounding` scans `packages/react/src`) is
+`Halloween/math.ts`. The
stylesheet hangs off `data-user-menu` (ERP avatar trigger), `data-date`
(calendar cells) and `data-app-card` (MES page card); those attributes do
nothing on their own and may stay when the folder is deleted. **The removal
checklist** (theme plus decorations) is the header of
`packages/react/src/Halloween/HalloweenLayer.tsx`: the folder and its
-export, three mounts, the theme file with its two registrations, then
-`lingui:extract`.
+export, three mounts, the theme file with its two registrations, the doc
+lines that name them, then `lingui:extract`.
The sign-in page's left panel (`_public+/_layout.tsx`) shows the Night Shift
while in season: `<HalloweenLoginArt />`, an ASCII story on a canvas
(`packages/react/src/Halloween/night-shift/`), lazy-loaded behind
-`useHalloween`. It brings its own headline scrim and forces the panel it
+`useHalloween` and only while the panel is shown (it is hidden below `lg`).
+It brings its own headline scrim and forces the panel it
fills `dark` from an effect, so the layout holds one line. A haunted plant works one
90-second shift (`ACTS` in `story.ts`) making a jack-o'-lantern; each shift
is seeded (`planShift`: face, weather, visitor, moon phase, a rare event),
@@ -271,4 +288,8 @@ shift index lives in sessionStorage (`carbon:night-shift`) so a revisit
continues the story. Everything a frame shows is a pure function of the
moment (`renderFrame`), pinned by `frame.test.ts` across panel sizes; the
cast reacts to the form (focus, secret fields, submit, error toasts) through
-DOM events only.
+DOM events only, and with reduced motion it draws one still frame and
+listens to nothing. The words it shows (stations, the ticket's status, the
+QC stamp) are Lingui strings passed in as `Labels`; the grid draws them as
+`Label`s, whole strings over reserved cells cut to fit, because a
+translation does not keep to one character per cell.
diff --git a/packages/react/AGENTS.md b/packages/react/AGENTS.md
index e71e471359..65d536635c 100644
--- a/packages/react/AGENTS.md
+++ b/packages/react/AGENTS.md
@@ -51,7 +51,7 @@ import { Button, Card, HStack, VStack, IconButton, cn } from "@carbon/react";
- **Error boundary**: `@carbon/react/ErrorBoundary` — `RouteErrorBoundary` (exported as `ErrorBoundary` from a module layout so a failed loader shows inside the app shell; it shows the status code and, for a 4xx, the message the server threw — `routeErrorCopy` — so throw a `Response` whose body says what was wrong. A 5xx or thrown `Error` gets generic copy) and `RootErrorBoundary` (drop-in root `ErrorBoundary` for RR v7 that maps 404 / 503 (the maintenance screen) / other HTTP / thrown `Error` to a styled screen) plus its parts (`ErrorScreen`, `GlitchHeading`, `StatusReadout`, `MagneticLink`, `NoiseOverlay`). Both read a request that got no response (`isNetworkError`: a `TypeError` with one of the browsers' fetch-failure messages) as a lost connection, not a fault, and `useNetworkRetry` revalidates when the browser is back online or the tab is shown again, which clears the error. Wrap it in the app's `Document` and pass `env` so `window.env` is set (the client crashes hydration otherwise). Copy is intentionally hardcoded English, not i18n.
- **Avatar**: `src` may be a URL or a generated-avatar value from `user.avatarUrl` (`dicebear:<style>:<seed>[:<rrggbb>]`; the styles and value helpers are in `@carbon/utils` `avatar.ts`). A generated value renders as a plain `<img>` of `generatedAvatarUrl(value)` (`utils/generatedAvatarImage.ts`, which `Avatar` imports instead of the renderer so no bundle that shows an avatar carries DiceBear) — `/file/avatar/:value?v=<GENERATED_AVATAR_RENDER_VERSION>` — so it is in the server-rendered HTML and needs no client JavaScript. Every app (ERP, MES, academy) serves that path with a one-line route re-exporting `generatedAvatarLoader` from `@carbon/react/GeneratedAvatar`: it draws the SVG on the server with DiceBear 10 and answers `Cache-Control: public, max-age=31536000, immutable`, so a refresh reads it from the browser cache. **Bump `GENERATED_AVATAR_RENDER_VERSION` whenever the same value would draw differently** (a DiceBear upgrade, a change to the rendering options), or browsers keep the old image. The avatar picker draws in the browser instead (`GeneratedAvatarPreview`, `useGeneratedAvatar`), because a color drag makes a new value per step; there the DiceBear core and each style's JSON load with `import()` (`STYLE_LOADERS`, typed `Record<GeneratedAvatarStyle, …>`), never with a `with: { type: "json" }` attribute (Vite passes it to the browser, which rejects the JSON Vite serves as JavaScript, and the picker stays grey); the server side instead bundles `@dicebear/styles` through `ssrNoExternal` in each app's `vite.config.ts`, because Node refuses a package's JSON without the attribute. `generatedAvatarClassName(style)` picks the image classes: line-art styles on white (`bg-white`) in both themes, color styles on `bg-muted`. A value's optional background goes to DiceBear as `backgroundColor`; on a dark one (`isDarkBackground`, WCAG contrast) the styles that draw lines straight onto the background (`INK_OPTIONS`) get white ink. The app `Avatar` wrappers turn a stored value into `src` with `avatarSrc` (`@carbon/utils`); a new user has no avatar (initials) until they choose one
- **Announcement**: `AnnouncementBar` is the one-line bar both shells render above their page area for the deployment's announcement. It remembers a dismissal in localStorage per user and announcement id, and while shown sets `--announcement-height` on `<html>`; the ERP's `--content-inset` includes it, and a page sized from `100dvh` outside that variable must subtract it
-- **Seasonal decorations**: `@carbon/react/Halloween` exports `HalloweenLayer` (mounted once in each app shell) and `HalloweenLoginArt` (the ERP sign-in panel's ASCII story, `src/Halloween/night-shift/`). Both render nothing unless the root loader's theme is `halloween`. Keep everything seasonal inside that folder: the removal checklist is the header of `src/Halloween/HalloweenLayer.tsx`
+- **Seasonal decorations**: `@carbon/react/Halloween` exports `HalloweenLayer` (mounted once in each app shell) and `HalloweenLoginArt` (the ERP sign-in panel's ASCII story, `src/Halloween/night-shift/`). Both render nothing unless the root loader's theme is `halloween`, and everything but that entry file loads in its own chunk. Keep everything seasonal inside that folder: the removal checklist is the header of `src/Halloween/HalloweenLayer.tsx`. Not seasonal and staying: `useSeasonalTheme` and `SeasonalThemeNotice` (`src/SeasonalTheme.tsx`), which disable the theme pickers and say why while any seasonal theme is on
- **Polish**: shadows over borders, `tabular-nums` for dynamic numbers, `active:scale-[0.98]` on pressables, `text-balance`/`text-pretty` for text wrapping
## Cross-References
diff --git a/packages/react/src/Halloween/BarSpider.tsx b/packages/react/src/Halloween/BarSpider.tsx
index 2b1ad33c75..fe02429dfa 100644
--- a/packages/react/src/Halloween/BarSpider.tsx
+++ b/packages/react/src/Halloween/BarSpider.tsx
@@ -66,11 +66,14 @@ function measureBar(layer: HTMLElement) {
if (!bar) return null;
const obstacles: Obstacle[] = [];
for (const node of Array.from(bar.querySelectorAll("*"))) {
- // Links and buttons whole, and every other element that holds no
+ // Anything pressable whole (links, buttons, fields, focusable or
+ // role-carrying elements), and every other element that holds no
// further elements (text, icons).
const leaf =
node.childElementCount === 0 ||
- node.matches("a, button, input, select, textarea, [role]");
+ node.matches(
+ "a, button, input, select, textarea, label, summary, [role], [tabindex]"
+ );
if (!leaf) continue;
const box = node.getBoundingClientRect();
if (box.width < 1 || box.height < 1) continue;
@@ -146,7 +149,7 @@ export function BarSpider({
const barChanged = new MutationObserver(() => schedule());
function measure() {
if (!layer) return;
- s?.layout(layer.getBoundingClientRect().width);
+ s?.layout(layer.getBoundingClientRect());
const found = measureBar(layer);
s?.setObstacles(found?.obstacles ?? []);
if (!found || found.bar === watched) return;
@@ -154,10 +157,14 @@ export function BarSpider({
barChanged.disconnect();
watched = found.bar;
barResized.observe(found.bar);
+ // An item shown, hidden or moved by a class, a style or its open
+ // state changes the boxes as much as one added or removed.
barChanged.observe(found.bar, {
childList: true,
subtree: true,
- characterData: true
+ characterData: true,
+ attributes: true,
+ attributeFilter: ["class", "style", "hidden", "data-state"]
});
}
function schedule() {
@@ -168,11 +175,26 @@ export function BarSpider({
layerResized.observe(layer);
const cardChanged = new MutationObserver(schedule);
cardChanged.observe(card, { childList: true });
+ // Scrolling only moves the layer on the screen: no need to re-measure
+ // the bar, just where pointer events land.
+ let scrollFrame = 0;
+ const onScroll = () => {
+ cancelAnimationFrame(scrollFrame);
+ scrollFrame = requestAnimationFrame(() =>
+ s.layout(layer.getBoundingClientRect())
+ );
+ };
+ window.addEventListener("scroll", onScroll, {
+ capture: true,
+ passive: true
+ });
measure();
s.appear();
return () => {
cancelAnimationFrame(frame);
+ cancelAnimationFrame(scrollFrame);
+ window.removeEventListener("scroll", onScroll, { capture: true });
barResized.disconnect();
barChanged.disconnect();
layerResized.disconnect();
diff --git a/packages/react/src/Halloween/Decorations.tsx b/packages/react/src/Halloween/Decorations.tsx
new file mode 100644
index 0000000000..7ce0437254
--- /dev/null
+++ b/packages/react/src/Halloween/Decorations.tsx
@@ -0,0 +1,52 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { AnimatePresence } from "motion/react";
+import { lazy, Suspense, useCallback, useState } from "react";
+import { createPortal } from "react-dom";
+import { BarSpider } from "./BarSpider";
+import { BooGhost } from "./Ghost";
+import { HalloweenStyles } from "./HalloweenStyles";
+import { BatFlyby, SuccessBats } from "./Visitors";
+
+// The app shell's decorations. Its own chunk, loaded by `HalloweenLayer` only
+// while the theme is on, so the rest of the year no shell downloads it.
+
+const loadReveal = () => import("./HalloweenReveal");
+const HalloweenReveal = lazy(loadReveal);
+
+function preloadReveal() {
+ void loadReveal();
+}
+
+export default function Decorations() {
+ const [revealOpen, setRevealOpen] = useState(false);
+ const open = useCallback(() => setRevealOpen(true), []);
+ const close = useCallback(() => setRevealOpen(false), []);
+
+ return (
+ <>
+ <HalloweenStyles />
+ {createPortal(
+ <div aria-hidden className="halloween-fog" />,
+ document.body
+ )}
+ <BarSpider
+ revealOpen={revealOpen}
+ onOpen={open}
+ onPreload={preloadReveal}
+ />
+ <BatFlyby />
+ <SuccessBats />
+ <BooGhost />
+ <AnimatePresence>
+ {revealOpen && (
+ <Suspense key="halloween-reveal" fallback={null}>
+ <HalloweenReveal onClose={close} />
+ </Suspense>
+ )}
+ </AnimatePresence>
+ </>
+ );
+}
diff --git a/packages/react/src/Halloween/HalloweenLayer.tsx b/packages/react/src/Halloween/HalloweenLayer.tsx
index 2854b5bcef..24787cf099 100644
--- a/packages/react/src/Halloween/HalloweenLayer.tsx
+++ b/packages/react/src/Halloween/HalloweenLayer.tsx
@@ -2,21 +2,8 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-import { AnimatePresence } from "motion/react";
-import {
- lazy,
- Suspense,
- useCallback,
- useEffect,
- useRef,
- useState
-} from "react";
-import { createPortal } from "react-dom";
-import { BarSpider } from "./BarSpider";
-import { BooGhost } from "./Ghost";
-import { HalloweenStyles } from "./HalloweenStyles";
+import { lazy, Suspense, useEffect, useRef, useState } from "react";
import { useHalloween } from "./season";
-import { BatFlyby, SuccessBats } from "./Visitors";
// Seasonal decoration, shared by the ERP and the MES (`@carbon/react/Halloween`).
// Everything renders only on Halloween, when the theme is on for everyone
@@ -33,23 +20,28 @@ import { BatFlyby, SuccessBats } from "./Visitors";
// packages/utils/src/index.ts and its entry in `seasonalThemes`
// (packages/utils/src/themes.ts). The theme carries everything else
// (its day, its mesh colors), so nothing reads it by name.
-// 4. Run `pnpm run lingui:extract` to drop its strings from the catalogs.
+// 4. Delete the doc lines that name them: the Halloween paragraphs of
+// .claude/rules/coding-conventions.md (Theme System), the "Seasonal
+// decorations" bullet of packages/react/AGENTS.md (keep its last
+// sentence) and `halloween-theme.ts` in packages/utils/AGENTS.md.
+// 5. Run `pnpm run lingui:extract` to drop its strings from the catalogs.
// Typecheck flags any mount or import left behind. The `data-user-menu`,
// `data-date` and `data-app-card` attributes the styles hang off, and
// `relative` on the sign-in logos, do nothing on their own and can stay.
-const loadReveal = () => import("./HalloweenReveal");
+// This file is all the shells import, so it stays small: everything else
+// loads in its own chunk, and only while the theme is on.
+const Decorations = lazy(() => import("./Decorations"));
const NightShift = lazy(() => import("./night-shift/NightShift"));
-const HalloweenReveal = lazy(loadReveal);
-
-function preloadReveal() {
- void loadReveal();
-}
export function HalloweenLayer() {
const on = useHalloween();
if (!on) return null;
- return <Decorations />;
+ return (
+ <Suspense fallback={null}>
+ <Decorations />
+ </Suspense>
+ );
}
/**
@@ -64,14 +56,25 @@ export function HalloweenLoginArt() {
function LoginArt() {
const ref = useRef<HTMLDivElement>(null);
+ // The panel is hidden on narrow screens: the engine loads and runs only
+ // while it is shown.
+ const [shown, setShown] = useState(false);
// The scene is night in either mode, so the panel it fills goes dark: its
// logo and headline take their dark variants. Undone on unmount.
useEffect(() => {
const panel = ref.current?.parentElement;
- if (!panel || panel.classList.contains("dark")) return;
- panel.classList.add("dark");
- return () => panel.classList.remove("dark");
+ if (!panel) return;
+ const darkened = !panel.classList.contains("dark");
+ if (darkened) panel.classList.add("dark");
+ const resized = new ResizeObserver(([entry]) => {
+ setShown((entry?.contentRect.width ?? 0) > 0);
+ });
+ resized.observe(panel);
+ return () => {
+ resized.disconnect();
+ if (darkened) panel.classList.remove("dark");
+ };
}, []);
return (
@@ -80,42 +83,13 @@ function LoginArt() {
aria-hidden
className="pointer-events-none absolute inset-0 overflow-hidden"
>
- <Suspense fallback={null}>
- <NightShift />
- </Suspense>
+ {shown && (
+ <Suspense fallback={null}>
+ <NightShift />
+ </Suspense>
+ )}
{/* Keeps the panel's headline readable over the fog. */}
<div className="absolute inset-x-0 bottom-0 z-10 h-64 bg-gradient-to-t from-black/75 via-black/40 to-transparent" />
</div>
);
}
-
-function Decorations() {
- const [revealOpen, setRevealOpen] = useState(false);
- const open = useCallback(() => setRevealOpen(true), []);
- const close = useCallback(() => setRevealOpen(false), []);
-
- return (
- <>
- <HalloweenStyles />
- {createPortal(
- <div aria-hidden className="halloween-fog" />,
- document.body
- )}
- <BarSpider
- revealOpen={revealOpen}
- onOpen={open}
- onPreload={preloadReveal}
- />
- <BatFlyby />
- <SuccessBats />
- <BooGhost />
- <AnimatePresence>
- {revealOpen && (
- <Suspense key="halloween-reveal" fallback={null}>
- <HalloweenReveal onClose={close} />
- </Suspense>
- )}
- </AnimatePresence>
- </>
- );
-}
diff --git a/packages/react/src/Halloween/HalloweenReveal.tsx b/packages/react/src/Halloween/HalloweenReveal.tsx
index 3a4146c80d..361b5f461d 100644
--- a/packages/react/src/Halloween/HalloweenReveal.tsx
+++ b/packages/react/src/Halloween/HalloweenReveal.tsx
@@ -3,15 +3,17 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { Trans, useLingui } from "@lingui/react/macro";
+import * as DialogPrimitive from "@radix-ui/react-dialog";
import { motion, useReducedMotion } from "motion/react";
import { useEffect, useRef } from "react";
-import { createPortal } from "react-dom";
import { Button } from "../Button";
-import useEscape from "../hooks/useEscape";
-import { HalloweenScene, NIGHT } from "./HalloweenScene";
+import { HalloweenScene } from "./HalloweenScene";
+import { NIGHT } from "./scene-palette";
// The surprise behind the spider web, over the whole screen. It closes on its
-// own, on Escape, or on a click anywhere.
+// own, on Escape, or on a click anywhere. A Radix dialog, so focus stays in it
+// and goes back where it was when it closes; mounted only while open (the
+// caller's AnimatePresence plays the fade out).
const AUTO_CLOSE_MS = 10_000;
@@ -20,41 +22,51 @@ export default function HalloweenReveal({ onClose }: { onClose: () => void }) {
const still = useReducedMotion() ?? false;
const closeRef = useRef<HTMLButtonElement>(null);
- useEscape(onClose);
-
useEffect(() => {
- closeRef.current?.focus();
const timer = window.setTimeout(onClose, AUTO_CLOSE_MS);
return () => window.clearTimeout(timer);
}, [onClose]);
- return createPortal(
- <motion.div
- role="dialog"
- aria-modal
- aria-label={t`Happy Halloween`}
- className="fixed inset-0 z-[100] cursor-pointer select-none overflow-hidden"
- style={{ backgroundColor: NIGHT }}
- initial={{ opacity: 0 }}
- animate={{ opacity: 1 }}
- exit={{ opacity: 0 }}
- transition={{ duration: still ? 0.2 : 0.6, ease: "easeOut" }}
- onClick={onClose}
- >
- <HalloweenScene title={t`Happy Halloween`} still={still} />
+ return (
+ <DialogPrimitive.Root open onOpenChange={(open) => !open && onClose()}>
+ <DialogPrimitive.Portal forceMount>
+ <DialogPrimitive.Content
+ asChild
+ forceMount
+ aria-describedby={undefined}
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ closeRef.current?.focus();
+ }}
+ >
+ <motion.div
+ className="fixed inset-0 z-[100] cursor-pointer select-none overflow-hidden"
+ style={{ backgroundColor: NIGHT }}
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ transition={{ duration: still ? 0.2 : 0.6, ease: "easeOut" }}
+ onClick={onClose}
+ >
+ <DialogPrimitive.Title className="sr-only">
+ {t`Happy Halloween`}
+ </DialogPrimitive.Title>
+ <HalloweenScene title={t`Happy Halloween`} still={still} />
- <motion.div
- className="absolute inset-x-0 bottom-10 flex justify-center gap-2"
- initial={still ? false : { opacity: 0, y: 12 }}
- animate={{ opacity: 1, y: 0 }}
- transition={{ duration: 0.5, delay: 2.4 }}
- onClick={(event) => event.stopPropagation()}
- >
- <Button ref={closeRef} variant="secondary" onClick={onClose}>
- <Trans>Close</Trans>
- </Button>
- </motion.div>
- </motion.div>,
- document.body
+ <motion.div
+ className="absolute inset-x-0 bottom-10 flex justify-center gap-2"
+ initial={still ? false : { opacity: 0, y: 12 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ duration: 0.5, delay: 2.4 }}
+ onClick={(event) => event.stopPropagation()}
+ >
+ <Button ref={closeRef} variant="secondary" onClick={onClose}>
+ <Trans>Close</Trans>
+ </Button>
+ </motion.div>
+ </motion.div>
+ </DialogPrimitive.Content>
+ </DialogPrimitive.Portal>
+ </DialogPrimitive.Root>
);
}
diff --git a/packages/react/src/Halloween/HalloweenScene.tsx b/packages/react/src/Halloween/HalloweenScene.tsx
index 502c520d60..43a697cbe6 100644
--- a/packages/react/src/Halloween/HalloweenScene.tsx
+++ b/packages/react/src/Halloween/HalloweenScene.tsx
@@ -4,6 +4,7 @@
import { motion } from "motion/react";
import type { ReactNode } from "react";
+import { useEffect, useRef, useState } from "react";
import { Bat } from "./Bat";
import { JackOLanterns, LANTERN_THUD_AT } from "./Pumpkins";
import { SpiderBody } from "./Spider";
@@ -42,8 +43,6 @@ import {
Witch
} from "./scene-sky";
-export { NIGHT };
-
// The surprise behind the spider web: a moonlit graveyard. Lightning opens
// the night, a witch crosses the moon, a haunted house lets out a colony of
// bats, a ghost rises from a grave, jack-o'-lanterns arrive and are lit one by
@@ -356,12 +355,54 @@ function Ghost() {
}
const TITLE_FONT = "Georgia, 'Times New Roman', serif";
+const TITLE_X = 740;
+const TITLE_Y = 212;
+// The scene's centre, which `xMidYMid slice` always keeps on screen.
+const SCENE_CENTRE = 800;
+const TITLE_MARGIN = 40;
+
+/**
+ * Where the title sits and how big, so it is never cut off. The scene is
+ * cropped to fill the window, so a portrait or narrow window shows only a
+ * middle band of it; a title too long for that band (a long translation, a
+ * tablet held upright) is centred and shrunk to fit.
+ */
+function useTitleFit() {
+ const ref = useRef<SVGTextElement>(null);
+ const [fit, setFit] = useState({ x: TITLE_X, scale: 1 });
+ useEffect(() => {
+ const text = ref.current;
+ const svg = text?.ownerSVGElement;
+ if (!text || !svg) return;
+ const measure = () => {
+ const { width, height } = svg.getBoundingClientRect();
+ const length = text.getComputedTextLength();
+ if (!width || !height || !length) return;
+ const visible = Math.min(1600, (900 * width) / height);
+ const half = visible / 2 - TITLE_MARGIN;
+ const fitsInPlace =
+ TITLE_X - length / 2 >= SCENE_CENTRE - half &&
+ TITLE_X + length / 2 <= SCENE_CENTRE + half;
+ setFit(
+ fitsInPlace
+ ? { x: TITLE_X, scale: 1 }
+ : { x: SCENE_CENTRE, scale: Math.min(1, half / (length / 2)) }
+ );
+ };
+ measure();
+ const resized = new ResizeObserver(measure);
+ resized.observe(svg);
+ return () => resized.disconnect();
+ }, []);
+ return { ref, ...fit };
+}
function Title({ title }: { title: string }) {
const still = useStill();
+ const fit = useTitleFit();
const lettering = {
- x: 740,
- y: 212,
+ x: TITLE_X,
+ y: TITLE_Y,
textAnchor: "middle",
fontFamily: TITLE_FONT,
fontWeight: 700,
@@ -369,7 +410,9 @@ function Title({ title }: { title: string }) {
letterSpacing: 3
} as const;
return (
- <g>
+ <g
+ transform={`translate(${fit.x} ${TITLE_Y}) scale(${fit.scale}) translate(${-TITLE_X} ${-TITLE_Y})`}
+ >
<motion.g
initial={still ? false : { opacity: 0 }}
animate={{ opacity: [0, 1, 0.25, 1, 0.55, 1] }}
@@ -379,10 +422,21 @@ function Title({ title }: { title: string }) {
times: [0, 0.18, 0.3, 0.48, 0.62, 1]
}}
>
- <ellipse cx={740} cy={180} rx={560} ry={120} fill="url(#hw-title-halo)">
+ <ellipse
+ cx={TITLE_X}
+ cy={180}
+ rx={560}
+ ry={120}
+ fill="url(#hw-title-halo)"
+ >
<Loop attributeName="opacity" values="1;0.7;1;0.82;1" dur="2.2s" />
</ellipse>
- <text {...lettering} fill="#ff6a12" filter="url(#hw-title-glow)">
+ <text
+ ref={fit.ref}
+ {...lettering}
+ fill="#ff6a12"
+ filter="url(#hw-title-glow)"
+ >
{title}
</text>
{/* Cut deep: a dark shadow below, the letters, then their bevel */}
diff --git a/packages/react/src/Halloween/HalloweenStyles.tsx b/packages/react/src/Halloween/HalloweenStyles.tsx
index 436824973d..0b5f5a32d6 100644
--- a/packages/react/src/Halloween/HalloweenStyles.tsx
+++ b/packages/react/src/Halloween/HalloweenStyles.tsx
@@ -336,11 +336,16 @@ const FOG_FADE =
// the window adds no scrolling.)
const FOG_RISE = 90;
+// Each bank is a tile wider than the window on both sides and drifts by
+// moving the whole layer (`transform`), which the browser can do without
+// repainting the mask; animating `mask-position` repainted half the window
+// every frame. One tile per loop, so the noise lines up again.
function fogLayer(image: string, opacity: number) {
return `
content: "";
position: absolute;
- inset: 0 0 -${FOG_RISE}px 0;
+ inset: 0 -${FOG_TILE.width}px -${FOG_RISE}px;
+ will-change: transform;
background-color: hsl(var(--foreground) / ${opacity});
-webkit-mask-image: ${image}, ${FOG_FADE};
-webkit-mask-size: ${FOG_TILE.width}px ${FOG_TILE.height}px, 100% 100%;
@@ -415,12 +420,12 @@ export const HALLOWEEN_CSS = `
halloween-fog-rise 9s ease-in-out -4s infinite alternate;
}
@keyframes halloween-fog-right {
- from { -webkit-mask-position: 0 100%, 0 0; mask-position: 0 100%, 0 0; }
- to { -webkit-mask-position: ${FOG_TILE.width}px 100%, 0 0; mask-position: ${FOG_TILE.width}px 100%, 0 0; }
+ from { transform: translateX(0); }
+ to { transform: translateX(${FOG_TILE.width}px); }
}
@keyframes halloween-fog-left {
- from { -webkit-mask-position: 0 100%, 0 0; mask-position: 0 100%, 0 0; }
- to { -webkit-mask-position: -${FOG_TILE.width}px 100%, 0 0; mask-position: -${FOG_TILE.width}px 100%, 0 0; }
+ from { transform: translateX(0); }
+ to { transform: translateX(-${FOG_TILE.width}px); }
}
@keyframes halloween-fog-rise {
from { translate: 0 0; }
diff --git a/packages/react/src/Halloween/Pumpkins.tsx b/packages/react/src/Halloween/Pumpkins.tsx
index 132191022a..859ada89ab 100644
--- a/packages/react/src/Halloween/Pumpkins.tsx
+++ b/packages/react/src/Halloween/Pumpkins.tsx
@@ -5,7 +5,7 @@
import type { Transition } from "motion/react";
import { motion } from "motion/react";
import type { ReactNode } from "react";
-import { seededRandom } from "./scene";
+import { seeded } from "./math";
import { Loop, LoopTransform, SCENE_ORIGIN, useStill } from "./scene-loops";
// Three jack-o'-lanterns, each with its own entrance and its own temper.
@@ -192,7 +192,7 @@ const SMOKE = {
type Particle = { id: string; dx: number; dy: number; r: number };
function particles(seed: number, count: number, spread: number): Particle[] {
- const rand = seededRandom(seed);
+ const rand = seeded(seed);
return Array.from({ length: count }, (_, i) => {
const side = i % 2 === 0 ? -1 : 1;
return {
diff --git a/packages/react/src/Halloween/Visitors.tsx b/packages/react/src/Halloween/Visitors.tsx
index 62df8a7085..802a923ba6 100644
--- a/packages/react/src/Halloween/Visitors.tsx
+++ b/packages/react/src/Halloween/Visitors.tsx
@@ -8,6 +8,7 @@ import { createPortal } from "react-dom";
import { Bat } from "./Bat";
import type { Flight } from "./flight";
import { approach, crossing, takeOff } from "./flight";
+import { onToast } from "./toasts";
// Bats that pass through now and then while Halloween is on: a few across
// the screen every few minutes, and a few out of a success toast. Each flies
@@ -131,7 +132,6 @@ export function BatFlyby() {
);
}
-const TOAST_SELECTOR = '[data-sonner-toast][data-type="success"]';
// At most one burst this often, so a run of saves is not a swarm.
const BURST_GAP_MS = 12_000;
@@ -147,47 +147,35 @@ export function SuccessBats() {
if (still) return;
let id = 0;
const timers = new Set<number>();
- // Looks only for the toast library adding a toast; every other change in
- // the page fails the first check.
- const observer = new MutationObserver((records) => {
- for (const record of records) {
- for (const node of Array.from(record.addedNodes)) {
- if (!(node instanceof Element)) continue;
- const toast = node.matches(TOAST_SELECTOR)
- ? node
- : node.querySelector(TOAST_SELECTOR);
- if (!toast) continue;
- if (performance.now() - lastBurst.current < BURST_GAP_MS) continue;
- lastBurst.current = performance.now();
- // Once the toast has slid into place.
- const timer = window.setTimeout(() => {
- timers.delete(timer);
- const box = toast.getBoundingClientRect();
- if (box.width === 0) return;
- id += 1;
- const count =
- 3 + (Math.random() < 0.5 ? 1 : 0) + (Math.random() < 0.5 ? 1 : 0);
- const burst: Burst = {
- id,
- x: box.left + box.width * (0.3 + Math.random() * 0.4),
- y: box.top + 8,
- bats: Array.from({ length: count }, (_, key) => ({
- key,
- flight: takeOff(Math.random),
- duration: 1.5 + Math.random() * 0.9,
- delay: Math.random() * 0.45,
- flap: 0.13 + Math.random() * 0.07
- }))
- };
- setBursts((current) => [...current, burst]);
- }, 380);
- timers.add(timer);
- }
- }
+ const stop = onToast("success", (toast) => {
+ if (performance.now() - lastBurst.current < BURST_GAP_MS) return;
+ lastBurst.current = performance.now();
+ // Once the toast has slid into place.
+ const timer = window.setTimeout(() => {
+ timers.delete(timer);
+ const box = toast.getBoundingClientRect();
+ if (box.width === 0) return;
+ id += 1;
+ const count =
+ 3 + (Math.random() < 0.5 ? 1 : 0) + (Math.random() < 0.5 ? 1 : 0);
+ const burst: Burst = {
+ id,
+ x: box.left + box.width * (0.3 + Math.random() * 0.4),
+ y: box.top + 8,
+ bats: Array.from({ length: count }, (_, key) => ({
+ key,
+ flight: takeOff(Math.random),
+ duration: 1.5 + Math.random() * 0.9,
+ delay: Math.random() * 0.45,
+ flap: 0.13 + Math.random() * 0.07
+ }))
+ };
+ setBursts((current) => [...current, burst]);
+ }, 380);
+ timers.add(timer);
});
- observer.observe(document.body, { childList: true, subtree: true });
return () => {
- observer.disconnect();
+ stop();
for (const timer of timers) window.clearTimeout(timer);
};
}, [still]);
diff --git a/packages/react/src/Halloween/bar-spider.test.ts b/packages/react/src/Halloween/bar-spider.test.ts
index c0e4beec3e..05e726faf1 100644
--- a/packages/react/src/Halloween/bar-spider.test.ts
+++ b/packages/react/src/Halloween/bar-spider.test.ts
@@ -91,7 +91,7 @@ function moveTo(x: number, y: number) {
pointerMove?.({ clientX: x, clientY: y, timeStamp: now });
}
-function setup(options = {}) {
+function setup(options = {}, width = WIDTH) {
const sim = createBarSpider();
const web = () => ({
spokes: fakeElement(),
@@ -111,7 +111,7 @@ function setup(options = {}) {
button: fakeElement()
};
sim.attach(el as unknown as BarSpiderElements, options);
- sim.layout(WIDTH);
+ sim.layout({ left: 0, top: 0, width });
sim.setObstacles(BAR);
return { sim, el };
}
@@ -226,6 +226,14 @@ describe("createBarSpider", { timeout: 30_000 }, () => {
Math.hypot(hiding.body.x - leftHub.x, hiding.body.y - leftHub.y)
).toBeLessThan(1);
+ // While it waits, its look round every second costs no frames.
+ live(2);
+ let frames = 0;
+ live(4, () => {
+ frames++;
+ });
+ expect(frames).toBe(0);
+
moveTo(WIDTH / 2, 400);
let outAgain = false;
live(20, () => {
@@ -302,6 +310,20 @@ describe("createBarSpider", { timeout: 30_000 }, () => {
expect(backOnTheBar).toBe(true);
});
+ it("waits while the bar has no width (hidden below md), then appears once it has one", () => {
+ const { sim } = setup({}, 0);
+ sim.appear();
+ moveTo(20, 20);
+ live(5);
+ expect(sim.state().total).toBe(0);
+
+ sim.layout({ left: 0, top: 0, width: WIDTH });
+ const { mode, s, total } = sim.state();
+ expect(total).toBeGreaterThan(0);
+ expect(mode).toBe("rest");
+ expect(s).toBe(total);
+ });
+
it("lets the page sleep while it rests", () => {
const { sim } = setup();
sim.appear();
diff --git a/packages/react/src/Halloween/bar-spider.ts b/packages/react/src/Halloween/bar-spider.ts
index 584fc8cb10..17fa5ef6fc 100644
--- a/packages/react/src/Halloween/bar-spider.ts
+++ b/packages/react/src/Halloween/bar-spider.ts
@@ -4,8 +4,8 @@
import type { CornerWeb } from "./corner-web";
import { BAR_HEIGHT, createCornerWeb } from "./corner-web";
-import { seededRandom } from "./scene";
-import type { Body, LegPose, Surface } from "./spider-rig";
+import { at, seeded } from "./math";
+import type { Body, LegPose } from "./spider-rig";
import { createRig, SPIDER_SCALE, toWorld } from "./spider-rig";
// A garden spider living on the top bar, with a web in each of its top
@@ -105,25 +105,14 @@ function turn(from: number, to: number) {
/** The angle that points the spider's head along (dx, dy). */
const facing = (dx: number, dy: number) => Math.atan2(-dx, dy);
-// The track always has its six points and five lengths once it is built, so
-// a missing one is a bug.
-function at<T>(list: readonly T[], i: number): T {
- const value = list[i];
- if (value === undefined) throw new Error(`bar spider: no track entry ${i}`);
- return value;
-}
-
-/** The page itself: a foot holds wherever it lands. */
-const page: Surface = {
- grip: (x, y) => ({ x, y, hold: null }),
- locate: () => ({ x: 0, y: 0 })
-};
-
export function createBarSpider() {
const rig = createRig();
- const rand = seededRandom(31);
+ const rand = seeded(31);
let width = 0;
+ // Where the layer sits on the screen, from the last layout: a pointer event
+ // is turned into layer coordinates without measuring the page.
+ let origin = { left: 0, top: 0 };
let webs: CornerWeb[] = [];
// The spider's path: out of the left web, along the bar, into the right one.
let track: Vec[] = [];
@@ -180,13 +169,15 @@ export function createBarSpider() {
let last = 0;
let accumulator = 0;
let calm = 0;
- let clock = 0;
let awake = false;
let idleTimer = 0;
let quietSince = 0;
// Watching: whether the pointer is still close (else it moves on soon).
let watching = false;
let pointerWasNear = false;
+ // Asked to appear before the bar had a width (the layer is hidden below
+ // md): there is no track yet, so it appears on the first real layout.
+ let appearOnLayout = false;
// ---- The track ------------------------------------------------------------
@@ -254,8 +245,9 @@ export function createBarSpider() {
later(seconds, then);
return;
}
+ // Anything that moves the spider wakes the loop itself (`walkTo`,
+ // `watch`), so a check that changes nothing costs no frames.
then();
- wake();
}, seconds * 1000);
}
@@ -294,7 +286,7 @@ export function createBarSpider() {
const pointerIsLeft = pointer.x < spider.body.x;
walkTo(pointerIsLeft ? total : 0, RUN_SPEED, () => {
spider.mode = "hide";
- quietSince = clock;
+ quietSince = performance.now();
watchFromHiding();
});
}
@@ -305,8 +297,11 @@ export function createBarSpider() {
const away =
Math.hypot(pointer.x - spider.body.x, pointer.y - spider.body.y) >
SAFE_DISTANCE;
- if (!away) quietSince = clock;
- if (away && clock - quietSince >= QUIET_BEFORE_RETURN) {
+ if (!away) quietSince = performance.now();
+ if (
+ away &&
+ performance.now() - quietSince >= QUIET_BEFORE_RETURN * 1000
+ ) {
wander();
return;
}
@@ -360,7 +355,6 @@ export function createBarSpider() {
}
function step(dt: number) {
- clock += dt;
for (const web of webs) web.step(dt);
const before = { x: spider.body.x, y: spider.body.y };
@@ -400,7 +394,6 @@ export function createBarSpider() {
dt,
spider.body,
{ x: spider.vx, y: spider.vy },
- page,
onThread ? "curl" : "walk"
);
}
@@ -554,7 +547,7 @@ export function createBarSpider() {
function land() {
spider.s = spider.holdS;
place();
- rig.place(spider.body, page);
+ rig.place(spider.body);
spider.mode = "pause";
spider.timer = 0.8;
spider.after = wander;
@@ -678,14 +671,11 @@ export function createBarSpider() {
// ---- The pointer ------------------------------------------------------------
function local(clientX: number, clientY: number) {
- const rect = el?.svg?.getBoundingClientRect();
- return rect
- ? { x: clientX - rect.left, y: clientY - rect.top }
- : { x: clientX, y: clientY };
+ return { x: clientX - origin.left, y: clientY - origin.top };
}
function onPointerMove(event: PointerEvent) {
- if (!el?.svg || spider.mode === "drag") return;
+ if (!el?.svg || !total || spider.mode === "drag") return;
const p = local(event.clientX, event.clientY);
const now = event.timeStamp;
const dt = Math.max(0.008, (now - pointer.time) / 1000);
@@ -714,7 +704,9 @@ export function createBarSpider() {
return;
}
}
- if (spider.mode === "hide" && near < SAFE_DISTANCE) quietSince = clock;
+ if (spider.mode === "hide" && near < SAFE_DISTANCE) {
+ quietSince = performance.now();
+ }
// Drawing near, it stops to face the pointer and follows it round; once
// the pointer has gone, it waits a moment and moves on.
@@ -769,11 +761,37 @@ export function createBarSpider() {
wake();
}
+ /**
+ * The webs, and the spider resting in the right-hand one; in a moment it
+ * comes out for a walk. With reduced motion it simply stays there.
+ */
+ function appear() {
+ appearOnLayout = !total;
+ if (appearOnLayout) return;
+ clearIdle();
+ for (const web of webs) web.reset();
+ spider.s = total;
+ spider.speed = 0;
+ spider.spin = 0;
+ spider.body.angle = 0;
+ place();
+ rig.place(spider.body);
+ render();
+ spider.mode = "rest";
+ if (options.reducedMotion) return;
+ later(1.6, wander);
+ }
+
return {
attach(elements: BarSpiderElements, spiderOptions: BarSpiderOptions = {}) {
el = elements;
options = spiderOptions;
- window.addEventListener("pointermove", onPointerMove, { passive: true });
+ // With reduced motion nothing follows the pointer.
+ if (!options.reducedMotion) {
+ window.addEventListener("pointermove", onPointerMove, {
+ passive: true
+ });
+ }
},
detach() {
sleep();
@@ -782,9 +800,15 @@ export function createBarSpider() {
el = null;
},
sleep,
- /** The bar's width changed: re-spin the corner webs to fit. */
- layout(nextWidth: number) {
- if (nextWidth === width) return;
+ /**
+ * Where the layer is now. When the bar's width changed, re-spin the
+ * corner webs to fit.
+ */
+ layout(box: { left: number; top: number; width: number }) {
+ origin = { left: box.left, top: box.top };
+ const nextWidth = box.width;
+ // A hidden layer measures 0: keep the last track rather than none.
+ if (!nextWidth || nextWidth === width) return;
const fraction = total ? spider.s / total : 1;
width = nextWidth;
webs = [createCornerWeb("left", width), createCornerWeb("right", width)];
@@ -793,33 +817,17 @@ export function createBarSpider() {
spider.target = Math.min(total, spider.target);
if (spider.mode !== "drag" && spider.mode !== "dangle") {
place();
- rig.place(spider.body, page);
+ rig.place(spider.body);
}
render();
+ if (appearOnLayout) appear();
},
/** What on the bar the click target must keep clear of. */
setObstacles(next: Obstacle[]) {
obstacles = next;
render();
},
- /**
- * The webs, and the spider resting in the right-hand one; in a moment it
- * comes out for a walk. With reduced motion it simply stays there.
- */
- appear() {
- clearIdle();
- for (const web of webs) web.reset();
- spider.s = total;
- spider.speed = 0;
- spider.spin = 0;
- spider.body.angle = 0;
- place();
- rig.place(spider.body, page);
- render();
- spider.mode = "rest";
- if (options.reducedMotion) return;
- later(1.6, wander);
- },
+ appear,
/** The webs burst and the spider drops. */
snap() {
clearIdle();
diff --git a/packages/react/src/Halloween/corner-web.test.ts b/packages/react/src/Halloween/corner-web.test.ts
index bfe6fba025..8c118ac6a1 100644
--- a/packages/react/src/Halloween/corner-web.test.ts
+++ b/packages/react/src/Halloween/corner-web.test.ts
@@ -4,7 +4,7 @@
import { describe, expect, it } from "vitest";
import { BAR_HEIGHT, createCornerWeb } from "./corner-web";
-import { seededRandom } from "./scene";
+import { seeded } from "./math";
// The corner cobwebs sit over the top bar all day. They must stay in their
// corner, keep inside the bar, sway when brushed and settle again.
@@ -56,7 +56,7 @@ describe("createCornerWeb", () => {
it("bursts on a snap and is whole again after a reset", () => {
const web = createCornerWeb("right", WIDTH);
const rest = web.paths();
- web.burst(seededRandom(1));
+ web.burst(seeded(1));
settle(web, 0.1);
expect(web.paths().rings).not.toBe(rest.rings);
web.reset();
diff --git a/packages/react/src/Halloween/corner-web.ts b/packages/react/src/Halloween/corner-web.ts
index b1409fa262..0e8c03c135 100644
--- a/packages/react/src/Halloween/corner-web.ts
+++ b/packages/react/src/Halloween/corner-web.ts
@@ -2,8 +2,6 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-import { seededRandom } from "./scene";
-
// The classic cobweb in a corner: spokes fanning out from where the bar's
// top edge meets its side, and rings strung between them, each span sagging
// towards the corner. One outer strand has snapped and hangs loose.
@@ -16,6 +14,8 @@ import { seededRandom } from "./scene";
// Coordinates are the bar's own: its top edge is y 0, its left edge x 0, its
// lower border y BAR_HEIGHT.
+import { at, seeded } from "./math";
+
export const BAR_HEIGHT = 49;
type Point = { x: number; y: number };
@@ -38,16 +38,8 @@ const RINGS = RING_RADII.length;
const HIDE_SPOKE = 2;
const HIDE_RING = 1;
-// Every index here comes from the web's own layout, so a missing value is a
-// bug, not a state to carry on through.
-function at<T>(list: ArrayLike<T>, i: number): T {
- const value = list[i];
- if (value === undefined) throw new Error(`corner web: no value at ${i}`);
- return value;
-}
-
export function createCornerWeb(side: "left" | "right", width: number) {
- const rand = seededRandom(side === "left" ? 4242 : 777);
+ const rand = seeded(side === "left" ? 4242 : 777);
// Out from the corner: +x along the top edge for the left corner, -x for
// the right; +y down the side.
const sx = side === "left" ? 1 : -1;
diff --git a/packages/react/src/Halloween/flight.test.ts b/packages/react/src/Halloween/flight.test.ts
index 4d48729fee..03905ecea2 100644
--- a/packages/react/src/Halloween/flight.test.ts
+++ b/packages/react/src/Halloween/flight.test.ts
@@ -7,14 +7,7 @@
import { describe, expect, it } from "vitest";
import { approach, crossing, takeOff } from "./flight";
-
-function seeded(seed: number) {
- let state = seed;
- return () => {
- state = (state * 16807) % 2147483647;
- return (state - 1) / 2147483646;
- };
-}
+import { seeded } from "./math";
const WIDTH = 1440;
const HEIGHT = 900;
diff --git a/packages/react/src/Halloween/flight.ts b/packages/react/src/Halloween/flight.ts
index 64518aeaa0..4568fe6a1e 100644
--- a/packages/react/src/Halloween/flight.ts
+++ b/packages/react/src/Halloween/flight.ts
@@ -8,6 +8,9 @@
// path is a random walk in position and in depth (`scale`), banking into each
// turn. Pure: the randomness comes from the `random` passed in.
+import type { Random } from "./math";
+import { clamp } from "./math";
+
export type Flight = {
x: number[];
y: number[];
@@ -16,12 +19,6 @@ export type Flight = {
opacity: number[];
};
-type Random = () => number;
-
-function clamp(value: number, low: number, high: number) {
- return Math.max(low, Math.min(high, value));
-}
-
/** Banks into the turn: the steeper the climb or dive, the harder the tilt. */
function bank(x: number[], y: number[]) {
return x.map((_, i) => {
diff --git a/packages/react/src/Halloween/math.ts b/packages/react/src/Halloween/math.ts
new file mode 100644
index 0000000000..d9bb930043
--- /dev/null
+++ b/packages/react/src/Halloween/math.ts
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// The small maths every Halloween decoration shares: seeded randomness,
+// clamping and easing, and whole-number helpers for the pixel and character
+// grids. `floorOf`, `nearest` and `fraction` are built on `Math.trunc`
+// because the `no-raw-rounding` check (@carbon/checks) refuses
+// `Math.floor`/`Math.round` in this package: that rule is for prices and
+// quantities, and these are only screen positions.
+
+export type Random = () => number;
+
+/** Mulberry32: a small, fast seeded generator returning [0, 1). */
+export function seeded(seed: number): Random {
+ let state = seed >>> 0;
+ return () => {
+ state = (state + 0x6d2b79f5) >>> 0;
+ let t = state;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+/** A stable pseudo-random number in [0, 1) for an integer. */
+export function hash01(n: number) {
+ let h = Math.imul(n ^ 0x9e3779b9, 0x85ebca6b);
+ h ^= h >>> 13;
+ h = Math.imul(h, 0xc2b2ae35);
+ h ^= h >>> 16;
+ return (h >>> 0) / 4294967296;
+}
+
+export function clamp(value: number, low: number, high: number) {
+ return Math.max(low, Math.min(high, value));
+}
+
+export function clamp01(value: number) {
+ return clamp(value, 0, 1);
+}
+
+/** 0 before `from`, 1 after `to`, linear between. */
+export function segment(t: number, from: number, to: number) {
+ return clamp01((t - from) / (to - from));
+}
+
+/** Smoothstep: eases in and out over [0, 1]. */
+export function ease(t: number) {
+ const k = clamp01(t);
+ return k * k * (3 - 2 * k);
+}
+
+export function lerp(a: number, b: number, t: number) {
+ return a + (b - a) * t;
+}
+
+/** The whole-number part, rounded towards minus infinity. */
+export function floorOf(value: number): number {
+ const whole = Math.trunc(value);
+ return value < whole ? whole - 1 : whole;
+}
+
+/** The nearest whole number, halves away from zero. */
+export function nearest(value: number) {
+ return value >= 0 ? Math.trunc(value + 0.5) : -Math.trunc(-value + 0.5);
+}
+
+/** The fractional part, always in [0, 1). */
+export function fraction(value: number) {
+ return value - floorOf(value);
+}
+
+/**
+ * The entry at an index the caller's own layout guarantees (a track point, a
+ * leg, a web ring), so a missing one is a bug, not a state to carry on with.
+ */
+export function at<T>(list: ArrayLike<T>, i: number): T {
+ const value = list[i];
+ if (value === undefined) throw new Error(`Halloween: no entry at ${i}`);
+ return value;
+}
diff --git a/packages/react/src/Halloween/night-shift/NightShift.tsx b/packages/react/src/Halloween/night-shift/NightShift.tsx
index 21d1fdc97a..3724234612 100644
--- a/packages/react/src/Halloween/night-shift/NightShift.tsx
+++ b/packages/react/src/Halloween/night-shift/NightShift.tsx
@@ -3,18 +3,21 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
// The Night Shift on a canvas: fills its positioned parent, runs at 24 fps,
-// pauses with the tab, and watches the sign-in form so the cast can react.
+// pauses with the tab, and watches the sign-in form so the cast can react
+// (with reduced motion it draws one still frame and watches nothing).
// The story resumes from the next shift on the next visit in the same
// browser session, so the hill keeps the lanterns it has earned.
+import { useLingui } from "@lingui/react/macro";
import { useEffect, useRef } from "react";
+import { onToast } from "../toasts";
import type { Buffers } from "./frame";
import { makeBuffers, renderFrame } from "./frame";
import type { Layout } from "./layout";
import { makeLayout } from "./layout";
import type { Metrics } from "./paint";
import { paint } from "./paint";
-import type { Watcher } from "./scene";
+import type { Labels, Watcher } from "./scene";
import { IDLE_WATCHER } from "./scene";
import type { Moment, ShiftPlan } from "./story";
import { actStart, momentAt, planShift } from "./story";
@@ -99,10 +102,21 @@ function readFocus(watcher: Watcher) {
watcher.field = !watcher.secret;
}
-const ERROR_TOAST = '[data-sonner-toast][data-type="error"]';
-
export default function NightShift() {
+ const { t } = useLingui();
const canvasRef = useRef<HTMLCanvasElement>(null);
+ const words: Labels = {
+ stations: [t`Wash`, t`Carve`, t`Light up`, t`QC`],
+ item: t`Jack-o'-lantern`,
+ inProgress: t`In Progress`,
+ complete: t`Completed`,
+ scrapped: t`Scrapped`,
+ passed: t`QC passed`,
+ rejected: t`Rejected`
+ };
+ // Read by every frame, so a language change shows on the next one.
+ const labels = useRef(words);
+ labels.current = words;
useEffect(() => {
const canvas = canvasRef.current;
@@ -180,7 +194,8 @@ export default function NightShift() {
planFor(moment.shift),
moment,
clock,
- watcher
+ watcher,
+ labels.current
);
paint(ctx, buffers.main, frame, metrics);
};
@@ -206,7 +221,14 @@ export default function NightShift() {
});
const resize = new ResizeObserver(redraw);
resize.observe(host);
- if (!still) frameId = window.requestAnimationFrame(tick);
+ // One still frame: nothing moves, so nothing needs to react.
+ if (still) {
+ return () => {
+ disposed = true;
+ resize.disconnect();
+ };
+ }
+ frameId = window.requestAnimationFrame(tick);
const onPointer = (event: PointerEvent) => {
if (!metrics) return;
@@ -222,20 +244,9 @@ export default function NightShift() {
const onSubmit = () => {
flareAt = clock;
};
- const toasts = new MutationObserver((records) => {
- for (const record of records) {
- for (const node of record.addedNodes) {
- if (
- node instanceof Element &&
- (node.matches(ERROR_TOAST) || node.querySelector(ERROR_TOAST))
- ) {
- alarmAt = clock;
- return;
- }
- }
- }
+ const stopToasts = onToast("error", () => {
+ alarmAt = clock;
});
- toasts.observe(document.body, { childList: true, subtree: true });
window.addEventListener("pointermove", onPointer, { passive: true });
document.documentElement.addEventListener("pointerleave", onLeave);
document.addEventListener("submit", onSubmit, true);
@@ -244,7 +255,7 @@ export default function NightShift() {
disposed = true;
window.cancelAnimationFrame(frameId);
resize.disconnect();
- toasts.disconnect();
+ stopToasts();
window.removeEventListener("pointermove", onPointer);
document.documentElement.removeEventListener("pointerleave", onLeave);
document.removeEventListener("submit", onSubmit, true);
diff --git a/packages/react/src/Halloween/night-shift/exterior.ts b/packages/react/src/Halloween/night-shift/exterior.ts
index 5646a478ff..2e313de049 100644
--- a/packages/react/src/Halloween/night-shift/exterior.ts
+++ b/packages/react/src/Halloween/night-shift/exterior.ts
@@ -2,1074 +2,35 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-// The hill at night: sky, moon, the plant with its clock tower and crane, the
-// graveyard, the fence with its cat and crow, the lantern procession and the
-// pumpkin patch, plus whoever visits this shift. Everything here is drawn
-// from the moment alone, so any instant of the story can be rendered cold.
+// The hill at night, back to front: the sky (sky.ts), the hill (hill.ts), the
+// plant (plant.ts) and the Great Lighting (great-lighting.ts). Every part is
+// drawn from the scene alone (the moment, the seconds and who is watching),
+// so any instant of the story can be rendered cold.
-import { GROUND, HILL, NIGHT, SILHOUETTE } from "../scene-palette";
-import type { Face } from "./faces";
-import type { Color } from "./grid";
-import { hex, mix, NO_BG, scale, spriteWidth } from "./grid";
-import { lanternSlot, pointAlong } from "./layout";
-import { fbm2, flicker, noise2 } from "./noise";
-import { drawLantern, drawPumpkin } from "./pumpkin";
-import type { Scene } from "./scene";
+import { drawGreatLighting } from "./great-lighting";
import {
- clamp01,
- ease,
- fraction,
- hash01,
- lerp,
- nearest,
- segment
-} from "./scene";
+ drawDance,
+ drawFence,
+ drawGhost,
+ drawGround,
+ drawHills,
+ drawPatch,
+ drawPath,
+ drawProcession,
+ drawStones
+} from "./hill";
+import { drawBong, drawCraneAndHero, drawFactory } from "./plant";
+import type { Scene } from "./scene";
import {
- BAT,
- BOO,
- CAT,
- CLOCK,
- CROW,
- GHOST,
- HORSEMAN,
- MARK_EDGES,
- MARK_STARS,
- SHIP,
- SKELETON,
- SPIDER,
- STONES,
- WITCH
-} from "./sprites";
-import { ACTS, actStart, LANTERNS_FOR_LIGHTING } from "./story";
-
-export const SKY_TOP = hex(NIGHT);
-export const SKY_HORIZON = hex("#1d1233");
-export const DAWN_TOP = hex("#191628");
-export const DAWN_HORIZON = hex("#5d4a68");
-const SILHOUETTE_BG = hex(SILHOUETTE);
-const GROUND_BG = hex(GROUND);
-const HILL_BG = hex(HILL);
-const RIM_EDGE = hex("#5b4a8a");
-const DAWN_EDGE = hex("#8a7a96");
-const STAR_DIM = hex("#3a3460");
-const STAR_BRIGHT = hex("#ece6ff");
-const MOON_DARK = hex("#3a3352");
-const MOON_LIT = hex("#f4ecd6");
-const EARTHSHINE = hex("#211b33");
-const BAT_DARK = hex("#0b0711");
-const BAT_RIM = hex("#5d4d86");
-const GRASS = hex("#2e2440");
-const GRASS_LIT = hex("#4d3d6a");
-const TEXTURE = hex("#241a33");
-const PATH = hex("#4a3a5c");
-const STONE = hex("#6f6890");
-const STONE_RIM = hex("#a49cc8");
-const STONE_BG = hex("#17111f");
-const RIP = hex("#3d3656");
-const FACTORY_TEXTURE = hex("#1a1226");
-const ROOF = hex("#4b3b70");
-const WINDOW_OFF = hex("#2a2140");
-const WINDOW_DIM = hex("#7a3a10");
-const WINDOW_LIT = hex("#ffb347");
-const DOOR_WOOD = hex("#1d120e");
-const DOOR_OPEN = hex("#8a4a12");
-const CHIMNEY = hex("#3d2f52");
-const SMOKE = hex("#6a6088");
-const CLOCK_RIM = hex("#a89a6a");
-const CLOCK_FACE = hex("#3a2f18");
-const CLOCK_HAND = hex("#fff1c4");
-const STEEL = hex("#5f5874");
-const CABLE = hex("#8a83a0");
-const VINE = hex("#33502a");
-const LEAF = hex("#4c7034");
-const PUMPKIN_SHELL = hex("#9a420c");
-const PUMPKIN_MARK = hex("#cf6a1c");
-const FENCE = hex("#4f3d4e");
-const CAT_LINE = hex("#3e3058");
-const CAT_BG = hex("#07040b");
-const CAT_EYES = hex("#d4ff5a");
-const CROW_LINE = hex("#3a304e");
-const CROW_EYE = hex("#ffcc33");
-const CAW = hex("#efe8ff");
-const LANTERN_LIGHT = hex("#ff8a2a");
-const ALARM = hex("#ff2d2d");
-const GHOST_GLOW = hex("#ddd8f6");
-const GHOST_BG = hex("#272238");
-const BONE = hex("#ece4cf");
-const VISITOR_RIM = hex("#4f4074");
-const SHIP_GLOW = hex("#8fd6b8");
-const SPIDER_EYES = hex("#ff3b3b");
-const HEAD_GLOW = hex("#ffb347");
-const RAIN = hex("#5d5585");
-const BOLT = hex("#f3eeff");
-const RING = hex("#d9c98e");
-const STAR_GOLD = hex("#ffe6a8");
-
-/** How far into the dawn: the sky pales, then the clock spins back. */
-export function dawnAt(scene: Scene) {
- return scene.moment.act === "dawn" ? ease(segment(scene.moment.t, 0, 6)) : 0;
-}
-
-/** Seconds into the Great Lighting (the witching hour, then the dawn). */
-function lightingTime(scene: Scene) {
- const { moment } = scene;
- if (moment.act === "witching") return moment.t;
- if (moment.act === "dawn") return 14 + moment.t;
- return -1;
-}
-
-/**
- * Where the moon is. On the shift of the Great Lighting it sets behind the
- * hills as the lanterns rise, and leaves them the sky.
- */
-function moonAt(scene: Scene) {
- const { moon, horizon } = scene.layout;
- if (!scene.plan.greatLighting) return moon;
- const T = lightingTime(scene);
- if (T < 0) return moon;
- const set = ease(segment(T, 0.5, 7));
- return { ...moon, y: lerp(moon.y, horizon + moon.r + 2, set) };
-}
-
-function overMoon(scene: Scene, x: number, y: number) {
- const { aspect } = scene.layout;
- const moon = moonAt(scene);
- const dx = (x + 0.5 - moon.x) / (moon.r * aspect);
- const dy = (y + 0.5 - moon.y) / moon.r;
- return dx * dx + dy * dy <= 1;
-}
-
-/** A silhouette's glyph colour: black against the moon, rim-lit elsewhere. */
-function silhouette(scene: Scene, dark: Color, rim: Color) {
- return (x: number, y: number) => (overMoon(scene, x, y) ? dark : rim);
-}
-
-function drawStars(scene: Scene, dawn: number) {
- const { grid, layout, seconds } = scene;
- for (const star of layout.stars) {
- const v = noise2(seconds * 0.7 + star.seed * 0.013, star.seed % 97);
- const shine = (0.3 + 0.7 * v) * (1 - dawn);
- if (shine < 0.14) continue;
- const char = v > 0.8 ? "*" : v > 0.64 ? "+" : v > 0.4 ? "." : "'";
- grid.put(star.x, star.y, char, mix(STAR_DIM, STAR_BRIGHT, shine));
- }
-}
-
-const MOON_RAMP = " .:-=+*#%@";
-
-function drawMoon(scene: Scene, dawn: number) {
- const { grid, layout, plan, lights } = scene;
- const { aspect } = layout;
- const moon = moonAt(scene);
- const angle = plan.moonPhase * Math.PI * 2;
- const lx = Math.sin(angle);
- const lz = Math.cos(angle);
- const rx = moon.r * aspect;
- for (
- let row = Math.trunc(moon.y - moon.r) - 1;
- row <= moon.y + moon.r + 1;
- row++
- ) {
- for (let col = Math.trunc(moon.x - rx) - 1; col <= moon.x + rx + 1; col++) {
- const nx = (col + 0.5 - moon.x) / rx;
- const ny = (row + 0.5 - moon.y) / moon.r;
- const d2 = nx * nx + ny * ny;
- if (d2 > 1) continue;
- const nz = Math.sqrt(1 - d2);
- const facing = nx * lx + nz * lz;
- const lit = clamp01((facing + 0.06) / 0.2);
- const maria = clamp01(
- (fbm2(nx * 2.4 + 3, ny * 2.4 + 1, 3, 5) - 0.5) / 0.16
- );
- const crater = noise2(nx * 9 + 1, ny * 9 + 4, 9) > 0.78 ? 0.75 : 1;
- const brightness = lit * (0.7 + 0.3 * nz) * (1 - 0.35 * maria) * crater;
- if (brightness < 0.07) {
- if ((col + row) % 2 === 0) grid.put(col, row, ".", EARTHSHINE);
- continue;
- }
- const index = Math.min(
- MOON_RAMP.length - 1,
- Math.trunc(brightness * MOON_RAMP.length)
- );
- grid.put(
- col,
- row,
- MOON_RAMP[index] ?? "@",
- mix(MOON_DARK, mix(MOON_LIT, DAWN_EDGE, dawn * 0.5), brightness)
- );
- }
- }
- const illumination = (1 + lz) / 2;
- lights.push({
- x: moon.x,
- y: moon.y,
- radius: moon.r * 3,
- color: hex("#b9b0e0"),
- power: 0,
- halo: (0.08 + 0.14 * illumination) * (1 - dawn * 0.6)
- });
-}
-
-function batTargets(scene: Scene) {
- const { cols, rows } = scene.layout;
- const targets: { x: number; y: number }[] = [];
- const spacingX = 2;
- const spacingY = 1;
- const letterWidth = spacingX * 5 + 4;
- const left = cols * 0.4 - (letterWidth * BOO.length) / 2;
- BOO.forEach((letter, k) => {
- letter.forEach((line, row) => {
- for (let col = 0; col < line.length; col++) {
- if (line[col] !== "#") continue;
- targets.push({
- x: left + k * letterWidth + col * spacingX,
- y: rows * 0.13 + row * spacingY
- });
- }
- });
- });
- return targets;
-}
-
-function drawBats(scene: Scene) {
- const { grid, layout, plan, moment, seconds } = scene;
- const t = moment.shiftT;
- if (t > 16) return;
- const boo = plan.event === "boo";
- const targets = boo ? batTargets(scene) : [];
- const count = boo ? targets.length : 12;
- const belfry = { x: layout.factory.tower, y: layout.factory.towerTop + 2 };
- const shade = silhouette(scene, BAT_DARK, BAT_RIM);
- for (let i = 0; i < count; i++) {
- const start = 1 + i * (boo ? 0.06 : 0.13);
- const u = (t - start) / (boo ? 11 : 8.5);
- if (u < 0 || u > 1) continue;
- const r1 = hash01(i * 7 + plan.index * 131);
- const r2 = hash01(i * 13 + 5);
- const control = {
- x: layout.moon.x + (r1 - 0.5) * layout.moon.r * layout.aspect * 2.6,
- y: layout.moon.y + (r2 - 0.5) * layout.moon.r * 2.2
- };
- const exit = {
- x: layout.cols + 6 + r1 * 10,
- y: layout.rows * (0.02 + hash01(i * 31 + 2) * 0.16)
- };
- const a = (1 - u) * (1 - u);
- const b = 2 * (1 - u) * u;
- const c = u * u;
- let x = a * belfry.x + b * control.x + c * exit.x;
- let y =
- a * belfry.y +
- b * control.y +
- c * exit.y +
- Math.sin(seconds * 9 + i) * 0.5;
- const target = targets[i];
- let folded = false;
- if (target) {
- const w = ease(segment(t, 3.4, 4.8)) * (1 - ease(segment(t, 7.4, 8.4)));
- x = lerp(x, target.x, w);
- y = lerp(y, target.y, w);
- // In formation each bat hangs as one glyph, so the letters read.
- folded = w > 0.85;
- }
- if (folded) {
- grid.put(x, y, "v", shade(x, y));
- continue;
- }
- const frame =
- BAT[Math.trunc(seconds * 11 + i * 0.37) % BAT.length] ?? "-v-";
- for (let k = 0; k < frame.length; k++) {
- grid.put(x - 1 + k, y, frame[k] ?? " ", shade(x - 1 + k, y));
- }
- }
-}
-
-function drawHills(scene: Scene, dawn: number) {
- const { grid, layout } = scene;
- const edge = mix(RIM_EDGE, DAWN_EDGE, dawn);
- for (let c = 0; c < layout.cols; c++) {
- const top = layout.ridge[c] ?? layout.horizon;
- const r0 = Math.trunc(top);
- for (let r = r0 + 1; r <= layout.horizon + 1; r++) {
- grid.blank(c, r);
- grid.fill(c, r, mix(HILL_BG, hex("#2a2236"), dawn * 0.5));
- if (hash01(c * 131 + r * 71) < 0.045) grid.put(c, r, ".", hex("#2b1f3e"));
- }
- const slope = (layout.ridge[c + 1] ?? top) - (layout.ridge[c - 1] ?? top);
- const char = slope < -0.45 ? "/" : slope > 0.45 ? "\\" : "_";
- grid.put(c, r0, char, edge);
- }
-}
-
-function drawGround(scene: Scene, dawn: number) {
- const { grid, layout, seconds } = scene;
- for (let c = 0; c < layout.cols; c++) {
- const top = layout.ground[c] ?? layout.horizon;
- const r0 = Math.trunc(top);
- for (let r = r0 + 1; r < layout.rows; r++) {
- grid.fill(c, r, GROUND_BG);
- grid.blank(c, r);
- const h = hash01(c * 977 + r * 131);
- if (h < 0.07)
- grid.put(c, r, h < 0.025 ? "," : h < 0.05 ? "." : "`", TEXTURE);
- }
- const tall = hash01(c * 17 + 3) < 0.4;
- const sway = noise2(c * 0.25 + seconds * 0.6, 1.3, 2);
- const blade = tall
- ? sway < 0.4
- ? "/"
- : sway > 0.6
- ? "\\"
- : "|"
- : hash01(c) < 0.5
- ? ","
- : "'";
- grid.put(
- c,
- r0,
- blade,
- mix(GRASS, mix(GRASS_LIT, DAWN_EDGE, dawn * 0.4), hash01(c * 3))
- );
- }
-}
-
-function drawPath(scene: Scene) {
- const { grid, layout } = scene;
- const steps = 110;
- for (let k = 0; k <= steps; k++) {
- if (hash01(k * 29) > 0.7) continue;
- const p = pointAlong(layout.path, k / steps, layout.aspect);
- grid.put(p.x, p.y + 0.4, k % 3 === 0 ? "," : ".", PATH);
- }
-}
-
-function drawStones(scene: Scene) {
- const { grid, layout } = scene;
- for (const stone of layout.stones) {
- const art = STONES[stone.kind];
- const width = spriteWidth(art);
- const left = stone.x - Math.trunc(width / 2);
- const top = stone.base - art.length + 1;
- grid.sprite(
- left,
- top,
- art,
- (char, col, row) =>
- char === "R" || char === "I" || char === "P"
- ? RIP
- : row === 0 || col >= width - 2
- ? STONE_RIM
- : STONE,
- STONE_BG
- );
- }
-}
-
-const RUN_START = ACTS[0].seconds;
-
-/** The tower clock: 12 at midnight, about half past five at dawn, then back. */
-export function clockHours(scene: Scene) {
- const { moment } = scene;
- const runEnd = actStart("dawn") + 6;
- const run = (s: number) =>
- 5.6 * clamp01((s - RUN_START) / (runEnd - RUN_START));
- if (moment.act !== "dawn") return run(moment.shiftT);
- if (moment.t < 6) return run(moment.shiftT);
- return run(runEnd) * (1 - ease(segment(moment.t, 6, 8.5)));
-}
-
-function handChar(angle: number) {
- const a = ((angle % Math.PI) + Math.PI) % Math.PI;
- if (a < Math.PI / 8 || a > (7 * Math.PI) / 8) return "|";
- if (a < (3 * Math.PI) / 8) return "/";
- if (a < (5 * Math.PI) / 8) return "-";
- return "\\";
-}
-
-function strikeGlow(scene: Scene) {
- if (scene.moment.act !== "midnight") return 0;
- let glow = 0;
- for (let k = 0; k < 12; k++) {
- const age = scene.moment.t - (0.6 + k * 0.55);
- if (age >= 0 && age < 0.5) glow = Math.max(glow, 1 - age / 0.5);
- }
- return glow;
-}
-
-function drawFactory(scene: Scene, dawn: number) {
- const { grid, layout, seconds, lights, moment, plan } = scene;
- const f = layout.factory;
- for (let r = f.roof; r < f.base + 1; r++) {
- for (let c = f.left; c <= f.right; c++) {
- grid.fill(c, r, SILHOUETTE_BG);
- grid.blank(c, r);
- if (hash01(c * 61 + r * 17) < 0.04) grid.put(c, r, ".", FACTORY_TEXTURE);
- }
- }
- for (let c = f.left; c + 2 <= f.right; c += 3) {
- grid.sprite(c, f.roof - 2, [" /|", "/$|"], ROOF, SILHOUETTE_BG);
- }
- for (const row of [f.roof + 2, f.roof + 5]) {
- if (row > f.base - 3) continue;
- for (let x = f.left + 2; x + 1 < f.right - 1; x += 4) {
- if (Math.abs(x - f.door) < 3) continue;
- const h = hash01(x * 13 + row * 7);
- if (h > 0.28) {
- const b = (0.6 + 0.4 * flicker(seconds + h * 10, x)) * (1 - dawn * 0.7);
- grid.text(x, row, "[]", mix(WINDOW_DIM, WINDOW_LIT, b));
- lights.push({
- x: x + 1,
- y: row + 0.5,
- radius: 2.2,
- color: WINDOW_LIT,
- power: 0.32 * b,
- halo: 0.05 * b
- });
- } else {
- grid.text(x, row, "[]", WINDOW_OFF);
- }
- }
- }
- const open =
- moment.act === "shipping" &&
- moment.t > 1.5 &&
- moment.t < (plan.event === "reject" ? 10 : 12.5);
- grid.sprite(
- f.door - 1,
- f.base - 3,
- [" _ ", "|$|", "|$|"],
- ROOF,
- open ? DOOR_OPEN : DOOR_WOOD
- );
- if (open) {
- lights.push({
- x: f.door,
- y: f.base - 1.5,
- radius: 4.5,
- color: WINDOW_LIT,
- power: 0.75,
- halo: 0.22
- });
- }
-
- for (let r = f.chimneyTop + 1; r < f.roof; r++) {
- grid.sprite(f.chimney - 1, r, ["|$|"], CHIMNEY, SILHOUETTE_BG);
- }
- grid.text(f.chimney - 1, f.chimneyTop, "===", ROOF);
- for (let k = 0; k < 16; k++) {
- const age = fraction(seconds * 0.11 + k / 16);
- const x =
- f.chimney + age * age * 18 + Math.sin(seconds * 0.7 + k) * age * 2;
- const y = f.chimneyTop - 1 - age * 12;
- const char =
- age < 0.18
- ? "o"
- : age < 0.5
- ? k % 2
- ? "("
- : ")"
- : age < 0.8
- ? "~"
- : ".";
- if (grid.isBlank(x, y)) grid.put(x, y, char, scale(SMOKE, 1 - age * 0.75));
- }
-
- grid.put(f.tower, f.towerTop - 1, "+", ROOF);
- grid.put(f.tower, f.towerTop, "^", ROOF);
- for (let k = 1; k <= 4; k++) {
- const y = f.towerTop + k;
- grid.put(f.tower - k - 1, y, "/", ROOF);
- grid.put(f.tower + k + 1, y, "\\", ROOF);
- for (let c = f.tower - k; c <= f.tower + k; c++) {
- grid.fill(c, y, SILHOUETTE_BG);
- grid.blank(c, y);
- }
- }
- for (let y = f.towerTop + 5; y < f.roof; y++) {
- grid.put(f.tower - 5, y, "|", ROOF);
- grid.put(f.tower + 5, y, "|", ROOF);
- for (let c = f.tower - 4; c <= f.tower + 4; c++) {
- grid.fill(c, y, SILHOUETTE_BG);
- grid.blank(c, y);
- }
- }
- const strike = strikeGlow(scene);
- const face = mix(CLOCK_FACE, hex("#7a6430"), strike * 0.6);
- grid.sprite(f.tower - 3, f.towerTop + 5, CLOCK, CLOCK_RIM, face);
- const center = { x: f.tower, y: f.towerTop + 7 };
- const hours = clockHours(scene);
- const minute = fraction(hours) * Math.PI * 2;
- const hour = (hours / 12) * Math.PI * 2;
- for (const k of [1, 2]) {
- grid.put(
- center.x + nearest(Math.sin(minute) * k),
- center.y + nearest(-Math.cos(minute) * k * 0.5),
- handChar(minute),
- CLOCK_HAND
- );
- }
- const hx = center.x + nearest(Math.sin(hour) * 1.2);
- const hy = center.y + nearest(-Math.cos(hour) * 0.6);
- if (hx !== center.x || hy !== center.y)
- grid.put(hx, hy, handChar(hour), scale(CLOCK_HAND, 0.85));
- grid.put(center.x, center.y, "o", CLOCK_HAND);
- lights.push({
- x: center.x,
- y: center.y,
- radius: 3 + strike * 5,
- color: hex("#ffd98a"),
- power: 0.25 + strike * 0.8,
- halo: 0.1 + strike * 0.3
- });
-}
-
-/** The crane on the roof, and the hero pumpkin while it hangs from it. */
-function drawCraneAndHero(scene: Scene) {
- const { grid, layout, moment, seconds } = scene;
- const f = layout.factory;
- const stub = 4;
- const reach = Math.max(stub, Math.trunc(layout.hero.x - f.mast));
- const heroRadius =
- moment.act === "midnight"
- ? 1.05
- : 1.05 +
- 1.15 * ease(segment(moment.t, 2.5, 6.5)) +
- 0.05 * Math.sin(seconds * 3);
- const heroTop = layout.hero.y - heroRadius;
- const t = moment.act === "harvest" ? moment.t : -1;
-
- let length = stub;
- let hookY = f.jib + 2;
- let carried = false;
- if (t >= 0) {
- if (t < 8) length = lerp(stub, reach, ease(segment(t, 6, 8)));
- else if (t < 11.5) length = reach;
- else length = lerp(reach, stub, ease(segment(t, 11.5, 13.2)));
- if (t >= 8 && t < 9.5)
- hookY = lerp(f.jib + 2, heroTop - 1, ease(segment(t, 8, 9.5)));
- else if (t >= 9.5 && t < 10) hookY = heroTop - 1;
- else if (t >= 10 && t < 13.2)
- hookY = lerp(heroTop - 1, f.jib + 3, ease(segment(t, 10, 11.5)));
- else if (t >= 13.2)
- hookY = lerp(f.jib + 3, f.roof + 2, ease(segment(t, 13.2, 14)));
- carried = t >= 10;
- }
- const L = Math.trunc(length);
- for (let y = f.jib; y < f.roof; y++) grid.put(f.mast, y, "H", STEEL);
- for (let k = 1; k <= L; k++) {
- grid.put(f.mast + k, f.jib, k === L ? ">" : "=", STEEL);
- if (k < L)
- grid.put(f.mast + k, f.jib + 1, k % 2 ? "\\" : "/", scale(STEEL, 0.7));
- }
- const hookX = f.mast + L - 1;
- for (let y = f.jib + 1; y < hookY; y++) grid.put(hookX, y, "|", CABLE);
- grid.put(hookX, hookY, "J", CABLE);
-
- // Lowered through the roof hatch at the end of the harvest: gone inside.
- const sunk = t >= 13.2 && hookY + 1 > f.roof - 1;
- const showHero =
- moment.act === "midnight" || (moment.act === "harvest" && !sunk);
- if (!showHero) return;
- const center = carried
- ? { x: hookX + 0.5, y: hookY + 1 + heroRadius }
- : { x: layout.hero.x, y: layout.hero.y };
- drawPumpkin(grid, {
- x: center.x,
- y: center.y,
- radius: heroRadius,
- aspect: layout.aspect,
- spin: seconds * 0.4,
- seconds
- });
-}
-
-function drawPatch(scene: Scene) {
- const { grid, layout, moment } = scene;
- const { patch } = layout;
- const grown =
- moment.act === "midnight"
- ? 0.15
- : moment.act === "harvest"
- ? ease(segment(moment.t, 0, 5))
- : 1;
- const end = patch.left + (patch.right - patch.left) * grown;
- for (let x = patch.left; x <= end; x++) {
- const wave = Math.sin(x * 0.42);
- const y = patch.y + 1 + nearest(wave * 0.8);
- const slope = Math.cos(x * 0.42);
- const char = slope > 0.5 ? "\\" : slope < -0.5 ? "/" : "~";
- grid.put(x, y, char, VINE);
- if (hash01(x * 41) < 0.22)
- grid.put(x, y - 1, hash01(x) < 0.5 ? "&" : "%", LEAF);
- if (hash01(x * 7 + 1) < 0.12) grid.put(x, y + 1, "@", scale(VINE, 0.8));
- }
- const spots = 6;
- for (let k = 0; k < spots; k++) {
- const x =
- patch.left + 2 + ((k + 0.5) * (patch.right - patch.left - 4)) / spots;
- if (Math.abs(x - layout.hero.x) < 7) continue;
- if (x > end) continue;
- const y = patch.y + (k % 2) - 0.2;
- const art = k % 3 === 0 ? "(@)" : k % 3 === 1 ? "(o)" : "(O)";
- grid.text(x - 1, y, art, PUMPKIN_SHELL);
- grid.put(x, y, art[1] ?? "@", PUMPKIN_MARK);
- grid.put(x, y - 1, "'", VINE);
- }
-}
-
-function drawFence(scene: Scene) {
- const { grid, layout, seconds, watcher } = scene;
- const { fence } = layout;
- for (let c = fence.left; c <= fence.right; c++) {
- const post = (c - fence.left) % 3 === 0;
- if (post) grid.put(c, fence.top, "^", FENCE);
- grid.put(c, fence.top + 1, post ? "|" : "-", FENCE);
- if (post) grid.put(c, fence.top + 2, "|", scale(FENCE, 0.8));
- }
-
- const { cat } = layout;
- let look: keyof typeof CAT.eyes = "ahead";
- if (watcher.secret) look = "left";
- else if (watcher.field) look = "right";
- else if (watcher.pointer) {
- const dx = watcher.pointer.x - cat.x;
- look = dx < -5 ? "left" : dx > 5 ? "right" : "ahead";
- } else {
- const idle = noise2(seconds * 0.18, 9, 4);
- look = idle < 0.36 ? "left" : idle > 0.64 ? "right" : "ahead";
- }
- if (fraction(seconds / 4.7) < 0.035) look = "blink";
- const art = [CAT.ears, CAT.eyes[look], ...CAT.body];
- grid.sprite(
- cat.x - 3,
- cat.y,
- art,
- (char) => (char === "o" ? CAT_EYES : CAT_LINE),
- CAT_BG
- );
- if (look !== "blink") {
- scene.lights.push({
- x: cat.x,
- y: cat.y + 1.5,
- radius: 1.4,
- color: CAT_EYES,
- power: 0.2,
- halo: 0.06
- });
- }
-
- const { crow } = layout;
- grid.sprite(
- crow.x,
- crow.y,
- CROW,
- (char) =>
- char === "o" ? CROW_EYE : char === ">" ? hex("#c9a227") : CROW_LINE,
- CAT_BG
- );
- if (watcher.alarm > 0)
- grid.text(
- crow.x + 4,
- crow.y - 1,
- "caw.",
- mix(CROW_LINE, CAW, watcher.alarm)
- );
-}
-
-function lanternLight(
- scene: Scene,
- x: number,
- y: number,
- lit: number,
- away: boolean
-) {
- const flare = scene.watcher.flare;
- scene.lights.push({
- x,
- y,
- radius: 2.8 + flare * 2,
- color:
- scene.watcher.alarm > 0
- ? mix(LANTERN_LIGHT, ALARM, scene.watcher.alarm)
- : LANTERN_LIGHT,
- power: 0.55 * lit * (away ? 0.45 : 1) * (1 + flare * 1.6),
- halo: 0.2 * lit * (away ? 0.5 : 1) * (1 + flare * 1.6)
- });
-}
-
-function lanternTint(scene: Scene, lit: number) {
- const { alarm } = scene.watcher;
- if (alarm <= 0) return undefined;
- const on = fraction(scene.seconds * 7) < 0.6;
- return mix(hex("#ffd36a"), ALARM, on ? alarm : alarm * 0.4 * lit);
-}
-
-/** The lanterns on the hill, the newest still hopping down from the door. */
-function drawProcession(scene: Scene) {
- const { grid, layout, plan, moment, seconds, watcher } = scene;
- if (
- plan.greatLighting &&
- (moment.act === "witching" || moment.act === "dawn")
- )
- return;
- const shipped =
- (moment.act === "witching" || moment.act === "dawn") &&
- plan.event !== "reject";
- const lanterns: Face[] = shipped
- ? [...plan.procession, plan.face]
- : plan.procession;
- const peek = lanterns.length - 1;
- lanterns.forEach((face, i) => {
- const s = lanternSlot(i, LANTERNS_FOR_LIGHTING);
- const p = pointAlong(layout.path, s, layout.aspect);
- const bob = noise2(seconds * 1.1 + i * 3.1, i, 6) > 0.64 ? -1 : 0;
- const lit = flicker(seconds + i * 1.7, i);
- const away = watcher.secret && !(watcher.peek && i === peek);
- drawLantern(grid, p.x, p.y - 0.6 + bob, face, {
- lit,
- away,
- tint: lanternTint(scene, lit)
- });
- lanternLight(scene, p.x, p.y - 0.6 + bob, lit, away);
- });
-
- if (moment.act !== "shipping") return;
- const t = moment.t;
- if (plan.event === "reject") {
- const s = segment(t, 2, 8.5) * 1.15;
- if (t > 2 && s <= 1) {
- const p = pointAlong(layout.path, s, layout.aspect);
- const roll =
- ["(@)", "(o)", "(@)", "(O)"][Math.trunc(seconds * 10) % 4] ?? "(@)";
- grid.text(p.x - 1, p.y - 0.6, roll, PUMPKIN_MARK);
- }
- const chase = segment(t, 2.7, 9.8) * 1.15;
- if (t > 2.7 && chase <= 1) {
- const p = pointAlong(layout.path, chase, layout.aspect);
- const frame =
- Math.trunc(seconds * 8) % 2 === 0 ? SKELETON.runA : SKELETON.runB;
- grid.sprite(p.x - 3, p.y - 4.6, frame, BONE);
- }
- return;
- }
- if (t < 2.5) return;
- const u = segment(t, 2.5, 11.5);
- const slot = lanternSlot(plan.procession.length, LANTERNS_FOR_LIGHTING);
- const p = pointAlong(layout.path, slot * u, layout.aspect);
- const hop = u < 1 ? Math.sin(fraction((t - 2.5) / 0.5) * Math.PI) * 1.2 : 0;
- const lit = flicker(seconds, 99);
- const away = watcher.secret && !watcher.peek;
- drawLantern(grid, p.x, p.y - 0.6 - hop, plan.face, {
- lit,
- away,
- tint: lanternTint(scene, lit)
- });
- lanternLight(scene, p.x, p.y - 0.6 - hop, lit, away);
-}
-
-function drawGhost(scene: Scene) {
- const { grid, layout, moment, seconds, watcher, lights } = scene;
- let alpha = 0;
- if (moment.act === "shipping") alpha = ease(segment(moment.t, 1.5, 4));
- else if (moment.act === "witching") alpha = 1;
- else if (moment.act === "dawn") alpha = 1 - ease(segment(moment.t, 6, 9));
- if (alpha <= 0) return;
- const first = layout.stones[0];
- const last = layout.stones[layout.stones.length - 1];
- const mid = first && last ? (first.x + last.x) / 2 : layout.cols * 0.45;
- const base = first?.base ?? layout.horizon + 2;
- const x = mid + Math.sin(seconds * 0.23) * layout.cols * 0.07;
- const y = base - 6.5 + Math.sin(seconds * 1.2) * 0.7;
- const body = watcher.secret
- ? watcher.peek
- ? GHOST.peek
- : GHOST.shut
- : GHOST.open;
- const hem = GHOST.hem[Math.trunc(seconds * 2.5) % 2] ?? GHOST.hem[0] ?? "";
- const color = mix(GROUND_BG, GHOST_GLOW, alpha * 0.9);
- grid.sprite(x - 4, y, [...body, hem], color, mix(GROUND_BG, GHOST_BG, alpha));
- lights.push({
- x,
- y: y + 2,
- radius: 3.4,
- color: hex("#b8b0ff"),
- power: 0.18 * alpha,
- halo: 0.1 * alpha
- });
-}
-
-function drawDance(scene: Scene) {
- const { grid, layout, moment, plan, seconds } = scene;
- if (plan.event !== "dance" || moment.act !== "witching" || plan.greatLighting)
- return;
- const f = layout.factory;
- const x = f.door + 3;
- const y = f.base - 4;
- const step = Math.trunc(seconds / 0.4) % 2 === 0;
- grid.sprite(x, y, step ? SKELETON.danceA : SKELETON.danceB, BONE);
- grid.text(x + (step ? 7 : 6), y + (step ? 0 : 2), "c[_]", hex("#c8a27a"));
- for (let k = 0; k < 3; k++) {
- const age = fraction(seconds * 0.5 + k / 3);
- grid.put(
- x + 3 + Math.sin(age * 6 + k) * 2,
- y - 1 - age * 5,
- k % 2 ? "♪" : "♫",
- scale(BONE, 1 - age)
- );
- }
-}
-
-function constellationPoint(scene: Scene, index: number) {
- const { cols, rows, aspect, factory } = scene.layout;
- const star = MARK_STARS[index] ?? MARK_STARS[0] ?? { x: 212, y: 240 };
- // Right of the chimney's smoke, as large as fits: the moon has set.
- const left = factory.chimney + 4;
- const right = cols - 3;
- const sy = Math.min((rows * 0.3) / 480, (right - left) / 2 / (212 * aspect));
- return {
- x: (left + right) / 2 + (star.x - 212) * sy * aspect,
- y: rows * 0.26 + (star.y - 240) * sy
- };
-}
-
-/** Thirteen lanterns rise and become the Carbon mark, then the stars. */
-function drawGreatLighting(scene: Scene) {
- const { grid, layout, plan, moment, seconds, lights } = scene;
- if (!plan.greatLighting) return;
- if (moment.act !== "witching" && moment.act !== "dawn") return;
- const T = lightingTime(scene);
- const lanterns = [...plan.procession, plan.face];
- const fade = 1 - ease(segment(T, 20, 24.5));
- const positions = lanterns.map((face, i) => {
- const slot = pointAlong(
- layout.path,
- lanternSlot(i, LANTERNS_FOR_LIGHTING),
- layout.aspect
- );
- const lift = ease(segment(T, 0.3 + i * 0.25, 3.8 + i * 0.25));
- const risen = {
- x: slot.x + Math.sin(seconds * 1.3 + i) * 2 * lift,
- y: slot.y - 0.6 - lift * 7
- };
- const glide = ease(segment(T, 5, 9));
- const target = constellationPoint(scene, i);
- return {
- face,
- x: lerp(risen.x, target.x, glide),
- y:
- lerp(risen.y, target.y, glide) +
- Math.sin(seconds * 2 + i) * 0.15 * (1 - glide),
- star: glide
- };
- });
-
- MARK_EDGES.forEach(([a, b], k) => {
- const from = positions[a];
- const to = positions[b];
- if (!from || !to) return;
- const shown = segment(T, 9 + k * 0.22, 9.6 + k * 0.22) * fade;
- if (shown <= 0) return;
- const steps = Math.trunc(
- Math.hypot((to.x - from.x) / layout.aspect, to.y - from.y) * 1.6
- );
- const dx = (to.x - from.x) / layout.aspect;
- const dy = to.y - from.y;
- const edge =
- Math.abs(dx) > 2 * Math.abs(dy)
- ? "-"
- : Math.abs(dy) > 2 * Math.abs(dx)
- ? "|"
- : dx * dy > 0
- ? "\\"
- : "/";
- for (let s = 1; s < steps; s++) {
- if (s / steps > shown) break;
- const x = lerp(from.x, to.x, s / steps);
- const y = lerp(from.y, to.y, s / steps);
- if (grid.isBlank(x, y))
- grid.put(x, y, edge, scale(STAR_GOLD, 0.7 * fade));
- }
- });
-
- positions.forEach((p, i) => {
- const lit = flicker(seconds + i, i);
- if (p.star < 0.5) {
- drawLantern(grid, p.x, p.y, p.face, { lit });
- } else {
- const twinkle = 0.7 + 0.3 * noise2(seconds * 3 + i, i, 8);
- const char = fade > 0.66 ? "*" : fade > 0.33 ? "+" : ".";
- grid.put(
- p.x,
- p.y,
- char,
- scale(
- mix(LANTERN_LIGHT, STAR_GOLD, p.star),
- twinkle * (0.4 + 0.6 * fade)
- )
- );
- }
- lights.push({
- x: p.x,
- y: p.y,
- radius: 2.6,
- color: mix(LANTERN_LIGHT, STAR_GOLD, p.star),
- power: 0.5 * lit * fade,
- halo: (0.18 + 0.12 * p.star) * fade
- });
- });
-}
-
-function drawSkyVisitor(scene: Scene) {
- const { grid, layout, plan, moment, seconds, lights } = scene;
- if (moment.act !== "witching" || plan.greatLighting) return;
- const t = moment.t;
- const { moon, cols } = layout;
- const shade = silhouette(scene, BAT_DARK, VISITOR_RIM);
- if (plan.visitor === "witch") {
- const u = segment(t, 2, 12);
- if (u <= 0 || u >= 1) return;
- const x = lerp(cols + 4, -22, u);
- const y = moon.y - 3 + Math.sin(t * 1.3) * 1.4;
- const cape = WITCH.cape[Math.trunc(seconds * 5) % 2] ?? "";
- const art = [...WITCH.body.slice(0, 4), cape, WITCH.broom];
- grid.sprite(x, y, art, (_char, col, row) => shade(x + col, y + row));
- return;
- }
- if (plan.visitor === "ship") {
- const u = segment(t, 1.5, 13);
- if (u <= 0 || u >= 1) return;
- const x = lerp(-30, cols + 2, u);
- const y = moon.y - 2 + Math.sin(t * 0.9) * 0.6;
- grid.sprite(x, y, SHIP, (_char, col, row) =>
- overMoon(scene, x + col, y + row) ? hex("#163a30") : SHIP_GLOW
- );
- lights.push({
- x: x + 13,
- y: y + 3,
- radius: 6,
- color: SHIP_GLOW,
- power: 0.15,
- halo: 0.12
- });
- return;
- }
- if (plan.visitor === "spider") {
- const down = ease(segment(t, 1.5, 5));
- const up = ease(segment(t, 10, 13));
- const drop = down * (1 - up);
- if (drop <= 0) return;
- const x = moon.x - 6;
- const y = lerp(-6, moon.y - 1, drop) + Math.sin(seconds * 1.6) * 0.4 * drop;
- for (let r = 0; r < y; r++) grid.put(x + 6, r, "|", scale(CABLE, 0.7));
- grid.sprite(x, y, SPIDER, (char, col, row) =>
- char === "o" ? SPIDER_EYES : shade(x + col, y + row)
- );
- lights.push({
- x: x + 6,
- y: y + 1,
- radius: 1.6,
- color: SPIDER_EYES,
- power: 0.3,
- halo: 0.08
- });
- }
-}
-
-function drawHorseman(scene: Scene) {
- const { grid, layout, plan, moment, seconds, lights } = scene;
- if (
- moment.act !== "witching" ||
- plan.greatLighting ||
- plan.visitor !== "horseman"
- )
- return;
- const u = segment(moment.t, 2, 11);
- if (u <= 0 || u >= 1) return;
- const x = lerp(-22, layout.cols + 2, u);
- const column = Math.trunc(x + 10);
- const ground =
- layout.ridge[Math.max(0, Math.min(layout.cols - 1, column))] ??
- layout.horizon;
- const gallop = Math.trunc(seconds * 8) % 2;
- const y = ground - 4.6 - (gallop ? 0.4 : 0);
- const legs = HORSEMAN.legs[gallop] ?? "";
- grid.sprite(x, y, [...HORSEMAN.body, legs], (char) =>
- char === "@" || char === "(" || char === ")" ? HEAD_GLOW : VISITOR_RIM
- );
- lights.push({
- x: x + 12,
- y,
- radius: 2.5,
- color: HEAD_GLOW,
- power: 0.5,
- halo: 0.2
- });
-}
-
-function drawBong(scene: Scene) {
- const { grid, layout, moment } = scene;
- if (moment.act !== "midnight") return;
- const origin = { x: layout.factory.tower, y: layout.factory.towerTop + 7 };
- for (let k = 0; k < 12; k++) {
- const age = moment.t - (0.6 + k * 0.55);
- if (age < 0 || age > 1.8) continue;
- const radius = age * 15;
- const strength = 1 - age / 1.8;
- const samples = Math.max(12, Math.trunc(radius * layout.aspect * 6));
- for (let s = 0; s < samples; s++) {
- const a = (s / samples) * Math.PI * 2;
- const x = origin.x + Math.cos(a) * radius * layout.aspect;
- const y = origin.y + Math.sin(a) * radius;
- if (!grid.isBlank(x, y) || grid.bg[grid.index(x, y)] !== NO_BG) continue;
- const char = strength > 0.66 ? "*" : strength > 0.33 ? ":" : ".";
- grid.put(x, y, char, scale(RING, strength * 0.8));
- }
- }
-}
-
-function drawRain(scene: Scene) {
- const { grid, layout, plan, moment, seconds } = scene;
- if (plan.weather !== "drizzle") return;
- const heavy = moment.act === "witching" ? 1.7 : 1;
- const count = Math.trunc(layout.cols * 0.45 * heavy);
- for (let k = 0; k < count; k++) {
- const speed = 22 + hash01(k * 3) * 10;
- const y =
- fraction((seconds * speed) / (layout.rows + 6) + hash01(k * 11)) *
- (layout.rows + 6) -
- 3;
- const x = hash01(k * 17) * (layout.cols + 10) - 5 + y * 0.3;
- grid.put(x, y, k % 3 === 0 ? "," : "'", RAIN);
- }
-}
-
-/** Lightning in the witching hour: draws the bolt, returns the flash. */
-function drawLightning(scene: Scene) {
- const { grid, layout, plan, moment } = scene;
- if (moment.act !== "witching" || plan.greatLighting) return 0;
- let flash = 0;
- const strikes = [
- 3.2 + hash01(plan.index * 3) * 1.5,
- 8.7 + hash01(plan.index * 5) * 1.8
- ];
- strikes.forEach((at, k) => {
- const age = moment.t - at;
- if (age < 0 || age > 0.6) return;
- flash = Math.max(
- flash,
- age < 0.08 ? 1 : age < 0.18 ? 0.35 : age < 0.26 ? 0.7 : 0
- );
- let x = layout.cols * (0.15 + hash01(plan.index * 7 + k) * 0.75);
- const bright = scale(BOLT, 1 - age / 0.6);
- for (let y = 0; y < (layout.ridge[Math.trunc(x)] ?? layout.horizon); y++) {
- const step = hash01(plan.index * 97 + k * 31 + y) * 3;
- const dx = step < 1 ? -1 : step < 2 ? 0 : 1;
- grid.put(x, y, dx < 0 ? "/" : dx > 0 ? "\\" : "|", bright);
- x += dx;
- }
- });
- return flash;
-}
+ dawnAt,
+ drawBats,
+ drawHorseman,
+ drawLightning,
+ drawMoon,
+ drawRain,
+ drawSkyVisitor,
+ drawStars
+} from "./sky";
export function drawExterior(scene: Scene) {
const dawn = dawnAt(scene);
diff --git a/packages/react/src/Halloween/night-shift/faces.ts b/packages/react/src/Halloween/night-shift/faces.ts
index b5ff37c2a3..adde1e6d4f 100644
--- a/packages/react/src/Halloween/night-shift/faces.ts
+++ b/packages/react/src/Halloween/night-shift/faces.ts
@@ -7,8 +7,8 @@
// relative to the pumpkin's centre. Every lantern also has a one-line
// version, `(^w^)`, for the procession on the hill.
-import type { Random } from "./random";
-import { floorOf } from "./random";
+import type { Random } from "../math";
+import { floorOf } from "../math";
type Part = { mask: readonly string[]; mini: string };
diff --git a/packages/react/src/Halloween/night-shift/frame.test.ts b/packages/react/src/Halloween/night-shift/frame.test.ts
index 309d07671e..e221462c58 100644
--- a/packages/react/src/Halloween/night-shift/frame.test.ts
+++ b/packages/react/src/Halloween/night-shift/frame.test.ts
@@ -11,6 +11,7 @@ import { miniFace } from "./faces";
import { makeBuffers, renderFrame } from "./frame";
import type { Grid } from "./grid";
import { makeLayout } from "./layout";
+import type { Labels } from "./scene";
import { IDLE_WATCHER } from "./scene";
import type { ShiftPlan } from "./story";
import { actStart, LANTERNS_FOR_LIGHTING, momentAt, planShift } from "./story";
@@ -21,6 +22,17 @@ const SIZES = [
[135, 76]
] as const;
+const LABELS: Labels = {
+ stations: ["Wash", "Carve", "Light up", "QC"],
+ item: "Jack-o'-lantern",
+ inProgress: "In Progress",
+ complete: "Completed",
+ scrapped: "Scrapped",
+ passed: "QC passed",
+ rejected: "Rejected"
+};
+
+/** Every glyph, then every label's words. */
function text(grid: Grid) {
let out = "";
for (let r = 0; r < grid.rows; r++) {
@@ -28,6 +40,7 @@ function text(grid: Grid) {
out += String.fromCharCode(grid.ch[r * grid.cols + c] ?? 32);
out += "\n";
}
+ for (const label of grid.labels) out += `${label.text}\n`;
return out;
}
@@ -36,12 +49,21 @@ function render(
seconds: number,
cols = 100,
rows = 60,
- watcher = IDLE_WATCHER
+ watcher = IDLE_WATCHER,
+ labels = LABELS
) {
const layout = makeLayout(cols, rows, 1.93);
const buffers = makeBuffers(cols, rows);
const moment = momentAt(seconds, plan.index);
- const frame = renderFrame(buffers, layout, plan, moment, seconds, watcher);
+ const frame = renderFrame(
+ buffers,
+ layout,
+ plan,
+ moment,
+ seconds,
+ watcher,
+ labels
+ );
return { frame, grid: buffers.main, layout };
}
@@ -98,6 +120,34 @@ describe("renderFrame", () => {
expect(after).toContain("QC PASSED");
});
+ it("keeps a long translation inside the ticket", () => {
+ const plan = planShift(7, 2);
+ const long = "x".repeat(60);
+ const { grid } = render(plan, actStart("line") + 10, 70, 40, IDLE_WATCHER, {
+ ...LABELS,
+ item: long,
+ inProgress: long,
+ stations: [long, long, long, long]
+ });
+ const status = grid.labels.find((label) => label.text === long);
+ expect(status).toBeDefined();
+ for (const label of grid.labels) {
+ expect(label.x).toBeGreaterThanOrEqual(0);
+ expect(label.x + label.cells).toBeLessThanOrEqual(grid.cols);
+ }
+ // The ticket's labels never overlap one another.
+ const row = (y: number) =>
+ grid.labels.filter((label) => label.y === y).sort((a, b) => a.x - b.x);
+ for (const y of new Set(grid.labels.map((label) => label.y))) {
+ const labels = row(y);
+ labels.slice(1).forEach((label, i) => {
+ const before = labels[i];
+ if (before)
+ expect(label.x).toBeGreaterThanOrEqual(before.x + before.cells);
+ });
+ }
+ });
+
it("scraps a rejected pumpkin", () => {
const plan = withPlan({ event: "reject" });
const after = text(render(plan, actStart("line") + 22).grid);
diff --git a/packages/react/src/Halloween/night-shift/frame.ts b/packages/react/src/Halloween/night-shift/frame.ts
index e7736bdd02..a700294d08 100644
--- a/packages/react/src/Halloween/night-shift/frame.ts
+++ b/packages/react/src/Halloween/night-shift/frame.ts
@@ -6,20 +6,15 @@
// the Line), wipes between them with a curtain of falling glyphs, rolls the
// fog in, and lights every glyph near a lantern, a window or a candle.
-import {
- DAWN_HORIZON,
- DAWN_TOP,
- drawExterior,
- SKY_HORIZON,
- SKY_TOP
-} from "./exterior";
+import { ease, hash01, lerp, segment } from "../math";
+import { drawExterior } from "./exterior";
import type { Color } from "./grid";
import { blue, Grid, green, hex, mix, NO_BG, red, rgb } from "./grid";
import { drawInterior } from "./interior";
import type { Layout } from "./layout";
import { fbm2 } from "./noise";
-import type { Light, Scene, Watcher } from "./scene";
-import { ease, hash01, lerp, segment } from "./scene";
+import { DAWN_HORIZON, DAWN_TOP, SKY_HORIZON, SKY_TOP } from "./palette";
+import type { Labels, Light, Scene, Watcher } from "./scene";
import type { Moment, ShiftPlan } from "./story";
export type Sky = { top: Color; horizon: Color };
@@ -177,12 +172,19 @@ function wipe(
) {
const { cols, rows } = target;
const spread = 0.45;
+ const frontAt = (c: number) =>
+ (progress * (1 + spread) - hash01(c * 53 + 7) * spread) * (rows + 4);
+ const sourceAt = (c: number, r: number) => (r < frontAt(c) - 2 ? to : from);
+ // A label goes with the cell it starts in.
+ target.labels = [
+ ...from.labels.filter((label) => sourceAt(label.x, label.y) === from),
+ ...to.labels.filter((label) => sourceAt(label.x, label.y) === to)
+ ];
for (let c = 0; c < cols; c++) {
- const lag = hash01(c * 53 + 7) * spread;
- const front = (progress * (1 + spread) - lag) * (rows + 4);
+ const front = frontAt(c);
for (let r = 0; r < rows; r++) {
const i = r * cols + c;
- const source = r < front - 2 ? to : from;
+ const source = sourceAt(c, r);
target.ch[i] = source.ch[i] ?? 32;
target.fg[i] = source.fg[i] ?? 0;
target.bg[i] = source.bg[i] ?? NO_BG;
@@ -203,26 +205,24 @@ function wipe(
}
}
-function sceneFor(
- grid: Grid,
- layout: Layout,
- plan: ShiftPlan,
- moment: Moment,
- seconds: number,
- watcher: Watcher
-): Scene {
- return { grid, layout, plan, moment, seconds, watcher, lights: [] };
+function sceneFor(grid: Grid, view: View, moment: Moment): Scene {
+ return { grid, ...view, moment, lights: [] };
}
+/** Everything a frame is drawn from but the moment. */
+type View = Omit<Scene, "grid" | "moment" | "lights">;
+
export function renderFrame(
buffers: Buffers,
layout: Layout,
plan: ShiftPlan,
moment: Moment,
seconds: number,
- watcher: Watcher
+ watcher: Watcher,
+ labels: Labels
): FrameOut {
const { main, from, to } = buffers;
+ const view: View = { layout, plan, seconds, watcher, labels };
main.clear();
let lights: Light[] = [];
let flash = 0;
@@ -241,8 +241,8 @@ export function renderFrame(
const before: Moment = toLine
? { ...moment, act: "harvest", t: 14, progress: 1 }
: { ...moment, act: "line", t: 24, progress: 1 };
- const fromScene = sceneFor(from, layout, plan, before, seconds, watcher);
- const toScene = sceneFor(to, layout, plan, moment, seconds, watcher);
+ const fromScene = sceneFor(from, view, before);
+ const toScene = sceneFor(to, view, moment);
if (toLine) {
drawExterior(fromScene);
drawInterior(toScene);
@@ -269,12 +269,12 @@ export function renderFrame(
];
exterior = !toLine;
} else if (moment.act === "line") {
- const scene = sceneFor(main, layout, plan, moment, seconds, watcher);
+ const scene = sceneFor(main, view, moment);
drawInterior(scene);
lights = scene.lights;
exterior = false;
} else {
- const scene = sceneFor(main, layout, plan, moment, seconds, watcher);
+ const scene = sceneFor(main, view, moment);
const out = drawExterior(scene);
flash = out.flash;
dawn = out.dawn;
diff --git a/packages/react/src/Halloween/night-shift/great-lighting.ts b/packages/react/src/Halloween/night-shift/great-lighting.ts
new file mode 100644
index 0000000000..ada579df00
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/great-lighting.ts
@@ -0,0 +1,116 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// The Great Lighting: thirteen lanterns rise and become the Carbon mark.
+
+import { ease, lerp, segment } from "../math";
+import { mix, scale } from "./grid";
+import { lanternSlot, pointAlong } from "./layout";
+import { flicker, noise2 } from "./noise";
+import { LANTERN_LIGHT, STAR_GOLD } from "./palette";
+import { drawLantern } from "./pumpkin";
+import type { Scene } from "./scene";
+import { lightingTime } from "./sky";
+import { MARK_EDGES, MARK_STARS } from "./sprites";
+import { LANTERNS_FOR_LIGHTING } from "./story";
+
+function constellationPoint(scene: Scene, index: number) {
+ const { cols, rows, aspect, factory } = scene.layout;
+ const star = MARK_STARS[index] ?? MARK_STARS[0] ?? { x: 212, y: 240 };
+ // Right of the chimney's smoke, as large as fits: the moon has set.
+ const left = factory.chimney + 4;
+ const right = cols - 3;
+ const sy = Math.min((rows * 0.3) / 480, (right - left) / 2 / (212 * aspect));
+ return {
+ x: (left + right) / 2 + (star.x - 212) * sy * aspect,
+ y: rows * 0.26 + (star.y - 240) * sy
+ };
+}
+
+/** Thirteen lanterns rise and become the Carbon mark, then the stars. */
+export function drawGreatLighting(scene: Scene) {
+ const { grid, layout, plan, moment, seconds, lights } = scene;
+ if (!plan.greatLighting) return;
+ if (moment.act !== "witching" && moment.act !== "dawn") return;
+ const T = lightingTime(scene);
+ const lanterns = [...plan.procession, plan.face];
+ const fade = 1 - ease(segment(T, 20, 24.5));
+ const positions = lanterns.map((face, i) => {
+ const slot = pointAlong(
+ layout.path,
+ lanternSlot(i, LANTERNS_FOR_LIGHTING),
+ layout.aspect
+ );
+ const lift = ease(segment(T, 0.3 + i * 0.25, 3.8 + i * 0.25));
+ const risen = {
+ x: slot.x + Math.sin(seconds * 1.3 + i) * 2 * lift,
+ y: slot.y - 0.6 - lift * 7
+ };
+ const glide = ease(segment(T, 5, 9));
+ const target = constellationPoint(scene, i);
+ return {
+ face,
+ x: lerp(risen.x, target.x, glide),
+ y:
+ lerp(risen.y, target.y, glide) +
+ Math.sin(seconds * 2 + i) * 0.15 * (1 - glide),
+ star: glide
+ };
+ });
+
+ MARK_EDGES.forEach(([a, b], k) => {
+ const from = positions[a];
+ const to = positions[b];
+ if (!from || !to) return;
+ const shown = segment(T, 9 + k * 0.22, 9.6 + k * 0.22) * fade;
+ if (shown <= 0) return;
+ const steps = Math.trunc(
+ Math.hypot((to.x - from.x) / layout.aspect, to.y - from.y) * 1.6
+ );
+ const dx = (to.x - from.x) / layout.aspect;
+ const dy = to.y - from.y;
+ const edge =
+ Math.abs(dx) > 2 * Math.abs(dy)
+ ? "-"
+ : Math.abs(dy) > 2 * Math.abs(dx)
+ ? "|"
+ : dx * dy > 0
+ ? "\\"
+ : "/";
+ for (let s = 1; s < steps; s++) {
+ if (s / steps > shown) break;
+ const x = lerp(from.x, to.x, s / steps);
+ const y = lerp(from.y, to.y, s / steps);
+ if (grid.isBlank(x, y))
+ grid.put(x, y, edge, scale(STAR_GOLD, 0.7 * fade));
+ }
+ });
+
+ positions.forEach((p, i) => {
+ const lit = flicker(seconds + i, i);
+ if (p.star < 0.5) {
+ drawLantern(grid, p.x, p.y, p.face, { lit });
+ } else {
+ const twinkle = 0.7 + 0.3 * noise2(seconds * 3 + i, i, 8);
+ const char = fade > 0.66 ? "*" : fade > 0.33 ? "+" : ".";
+ grid.put(
+ p.x,
+ p.y,
+ char,
+ scale(
+ mix(LANTERN_LIGHT, STAR_GOLD, p.star),
+ twinkle * (0.4 + 0.6 * fade)
+ )
+ );
+ }
+ lights.push({
+ x: p.x,
+ y: p.y,
+ radius: 2.6,
+ color: mix(LANTERN_LIGHT, STAR_GOLD, p.star),
+ power: 0.5 * lit * fade,
+ halo: (0.18 + 0.12 * p.star) * fade
+ });
+ });
+}
diff --git a/packages/react/src/Halloween/night-shift/grid.ts b/packages/react/src/Halloween/night-shift/grid.ts
index 6a670fc058..d5a5c0a860 100644
--- a/packages/react/src/Halloween/night-shift/grid.ts
+++ b/packages/react/src/Halloween/night-shift/grid.ts
@@ -4,9 +4,9 @@
// The character grid every frame is drawn into before it is painted: one
// glyph, one text colour and an optional cell background per cell. Colours
-// are packed 0xRRGGBB numbers so a frame allocates nothing.
+// are packed 0xRRGGBB numbers in typed arrays, so a cell allocates nothing.
-import { floorOf } from "./random";
+import { floorOf } from "../math";
export type Color = number;
@@ -60,12 +60,39 @@ export function css(color: Color) {
return `#${color.toString(16).padStart(6, "0")}`;
}
+/**
+ * Words in the user's language (a station name, a ticket's status). The grid
+ * draws one character per cell, which a translation cannot keep to: a
+ * combining mark, or a CJK glyph twice a cell wide. So a label reserves its
+ * cells and the painter draws the whole string over them, cut short to fit.
+ */
+export type Label = {
+ x: number;
+ y: number;
+ cells: number;
+ text: string;
+ color: Color;
+ align: "left" | "center";
+};
+
+// East Asian wide and fullwidth ranges: about two cells each.
+const WIDE =
+ /[\u1100-\u115f\u2e80-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6]/;
+
+/** Roughly how many cells a string takes in the panel's monospace font. */
+export function cellsFor(text: string) {
+ let cells = 0;
+ for (const char of text) cells += WIDE.test(char) ? 2 : 1;
+ return cells;
+}
+
export class Grid {
readonly cols: number;
readonly rows: number;
readonly ch: Uint16Array;
readonly fg: Uint32Array;
readonly bg: Int32Array;
+ labels: Label[] = [];
constructor(cols: number, rows: number) {
this.cols = cols;
@@ -80,6 +107,7 @@ export class Grid {
this.ch.fill(32);
this.fg.fill(0);
this.bg.fill(NO_BG);
+ this.labels = [];
}
/** The cell index under a point, or -1 off the grid. */
@@ -121,6 +149,26 @@ export class Grid {
return i < 0 || this.ch[i] === 32;
}
+ /**
+ * A label in at most `cells` cells from (x, y), centred on them or from
+ * their left. Returns how many cells it took.
+ */
+ label(
+ x: number,
+ y: number,
+ text: string,
+ color: Color,
+ maxCells: number,
+ align: Label["align"] = "left",
+ background: Color = NO_BG
+ ) {
+ const cells = Math.max(0, Math.min(maxCells, cellsFor(text)));
+ if (cells === 0) return 0;
+ for (let k = 0; k < cells; k++) this.blank(x + k, y, background);
+ this.labels.push({ x, y, cells, text, color, align });
+ return cells;
+ }
+
/** Writes a string left to right; spaces leave what is behind. */
text(x: number, y: number, value: string, color: Color) {
for (let k = 0; k < value.length; k++) {
diff --git a/packages/react/src/Halloween/night-shift/hill.ts b/packages/react/src/Halloween/night-shift/hill.ts
new file mode 100644
index 0000000000..d65b4f3284
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/hill.ts
@@ -0,0 +1,364 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// The hill: its ridges and ground, the path, the graveyard, the pumpkin
+// patch, the fence with its cat and crow, the lantern procession, the ghost
+// and the foreman's dance.
+
+import { ease, fraction, hash01, nearest, segment } from "../math";
+import type { Face } from "./faces";
+import { hex, mix, scale, spriteWidth } from "./grid";
+import { lanternSlot, pointAlong } from "./layout";
+import { flicker, noise2 } from "./noise";
+import {
+ ALARM,
+ BONE,
+ CAT_BG,
+ CAT_EYES,
+ CAT_LINE,
+ CAW,
+ CROW_EYE,
+ CROW_LINE,
+ DAWN_EDGE,
+ FENCE,
+ GHOST_BG,
+ GHOST_GLOW,
+ GRASS,
+ GRASS_LIT,
+ GROUND_BG,
+ HILL_BG,
+ LANTERN_LIGHT,
+ LEAF,
+ PATH,
+ PUMPKIN_MARK,
+ PUMPKIN_SHELL,
+ RIM_EDGE,
+ RIP,
+ STONE,
+ STONE_BG,
+ STONE_RIM,
+ TEXTURE,
+ VINE
+} from "./palette";
+import { drawLantern } from "./pumpkin";
+import type { Scene } from "./scene";
+import { CAT, CROW, GHOST, SKELETON, STONES } from "./sprites";
+import { LANTERNS_FOR_LIGHTING } from "./story";
+
+export function drawHills(scene: Scene, dawn: number) {
+ const { grid, layout } = scene;
+ const edge = mix(RIM_EDGE, DAWN_EDGE, dawn);
+ for (let c = 0; c < layout.cols; c++) {
+ const top = layout.ridge[c] ?? layout.horizon;
+ const r0 = Math.trunc(top);
+ for (let r = r0 + 1; r <= layout.horizon + 1; r++) {
+ grid.blank(c, r);
+ grid.fill(c, r, mix(HILL_BG, hex("#2a2236"), dawn * 0.5));
+ if (hash01(c * 131 + r * 71) < 0.045) grid.put(c, r, ".", hex("#2b1f3e"));
+ }
+ const slope = (layout.ridge[c + 1] ?? top) - (layout.ridge[c - 1] ?? top);
+ const char = slope < -0.45 ? "/" : slope > 0.45 ? "\\" : "_";
+ grid.put(c, r0, char, edge);
+ }
+}
+
+export function drawGround(scene: Scene, dawn: number) {
+ const { grid, layout, seconds } = scene;
+ for (let c = 0; c < layout.cols; c++) {
+ const top = layout.ground[c] ?? layout.horizon;
+ const r0 = Math.trunc(top);
+ for (let r = r0 + 1; r < layout.rows; r++) {
+ grid.fill(c, r, GROUND_BG);
+ grid.blank(c, r);
+ const h = hash01(c * 977 + r * 131);
+ if (h < 0.07)
+ grid.put(c, r, h < 0.025 ? "," : h < 0.05 ? "." : "`", TEXTURE);
+ }
+ const tall = hash01(c * 17 + 3) < 0.4;
+ const sway = noise2(c * 0.25 + seconds * 0.6, 1.3, 2);
+ const blade = tall
+ ? sway < 0.4
+ ? "/"
+ : sway > 0.6
+ ? "\\"
+ : "|"
+ : hash01(c) < 0.5
+ ? ","
+ : "'";
+ grid.put(
+ c,
+ r0,
+ blade,
+ mix(GRASS, mix(GRASS_LIT, DAWN_EDGE, dawn * 0.4), hash01(c * 3))
+ );
+ }
+}
+
+export function drawPath(scene: Scene) {
+ const { grid, layout } = scene;
+ const steps = 110;
+ for (let k = 0; k <= steps; k++) {
+ if (hash01(k * 29) > 0.7) continue;
+ const p = pointAlong(layout.path, k / steps, layout.aspect);
+ grid.put(p.x, p.y + 0.4, k % 3 === 0 ? "," : ".", PATH);
+ }
+}
+
+export function drawStones(scene: Scene) {
+ const { grid, layout } = scene;
+ for (const stone of layout.stones) {
+ const art = STONES[stone.kind];
+ const width = spriteWidth(art);
+ const left = stone.x - Math.trunc(width / 2);
+ const top = stone.base - art.length + 1;
+ grid.sprite(
+ left,
+ top,
+ art,
+ (char, col, row) =>
+ char === "R" || char === "I" || char === "P"
+ ? RIP
+ : row === 0 || col >= width - 2
+ ? STONE_RIM
+ : STONE,
+ STONE_BG
+ );
+ }
+}
+
+export function drawPatch(scene: Scene) {
+ const { grid, layout, moment } = scene;
+ const { patch } = layout;
+ const grown =
+ moment.act === "midnight"
+ ? 0.15
+ : moment.act === "harvest"
+ ? ease(segment(moment.t, 0, 5))
+ : 1;
+ const end = patch.left + (patch.right - patch.left) * grown;
+ for (let x = patch.left; x <= end; x++) {
+ const wave = Math.sin(x * 0.42);
+ const y = patch.y + 1 + nearest(wave * 0.8);
+ const slope = Math.cos(x * 0.42);
+ const char = slope > 0.5 ? "\\" : slope < -0.5 ? "/" : "~";
+ grid.put(x, y, char, VINE);
+ if (hash01(x * 41) < 0.22)
+ grid.put(x, y - 1, hash01(x) < 0.5 ? "&" : "%", LEAF);
+ if (hash01(x * 7 + 1) < 0.12) grid.put(x, y + 1, "@", scale(VINE, 0.8));
+ }
+ const spots = 6;
+ for (let k = 0; k < spots; k++) {
+ const x =
+ patch.left + 2 + ((k + 0.5) * (patch.right - patch.left - 4)) / spots;
+ if (Math.abs(x - layout.hero.x) < 7) continue;
+ if (x > end) continue;
+ const y = patch.y + (k % 2) - 0.2;
+ const art = k % 3 === 0 ? "(@)" : k % 3 === 1 ? "(o)" : "(O)";
+ grid.text(x - 1, y, art, PUMPKIN_SHELL);
+ grid.put(x, y, art[1] ?? "@", PUMPKIN_MARK);
+ grid.put(x, y - 1, "'", VINE);
+ }
+}
+
+export function drawFence(scene: Scene) {
+ const { grid, layout, seconds, watcher } = scene;
+ const { fence } = layout;
+ for (let c = fence.left; c <= fence.right; c++) {
+ const post = (c - fence.left) % 3 === 0;
+ if (post) grid.put(c, fence.top, "^", FENCE);
+ grid.put(c, fence.top + 1, post ? "|" : "-", FENCE);
+ if (post) grid.put(c, fence.top + 2, "|", scale(FENCE, 0.8));
+ }
+
+ const { cat } = layout;
+ let look: keyof typeof CAT.eyes = "ahead";
+ if (watcher.secret) look = "left";
+ else if (watcher.field) look = "right";
+ else if (watcher.pointer) {
+ const dx = watcher.pointer.x - cat.x;
+ look = dx < -5 ? "left" : dx > 5 ? "right" : "ahead";
+ } else {
+ const idle = noise2(seconds * 0.18, 9, 4);
+ look = idle < 0.36 ? "left" : idle > 0.64 ? "right" : "ahead";
+ }
+ if (fraction(seconds / 4.7) < 0.035) look = "blink";
+ const art = [CAT.ears, CAT.eyes[look], ...CAT.body];
+ grid.sprite(
+ cat.x - 3,
+ cat.y,
+ art,
+ (char) => (char === "o" ? CAT_EYES : CAT_LINE),
+ CAT_BG
+ );
+ if (look !== "blink") {
+ scene.lights.push({
+ x: cat.x,
+ y: cat.y + 1.5,
+ radius: 1.4,
+ color: CAT_EYES,
+ power: 0.2,
+ halo: 0.06
+ });
+ }
+
+ const { crow } = layout;
+ grid.sprite(
+ crow.x,
+ crow.y,
+ CROW,
+ (char) =>
+ char === "o" ? CROW_EYE : char === ">" ? hex("#c9a227") : CROW_LINE,
+ CAT_BG
+ );
+ if (watcher.alarm > 0)
+ grid.text(
+ crow.x + 4,
+ crow.y - 1,
+ "caw.",
+ mix(CROW_LINE, CAW, watcher.alarm)
+ );
+}
+
+function lanternLight(
+ scene: Scene,
+ x: number,
+ y: number,
+ lit: number,
+ away: boolean
+) {
+ const flare = scene.watcher.flare;
+ scene.lights.push({
+ x,
+ y,
+ radius: 2.8 + flare * 2,
+ color:
+ scene.watcher.alarm > 0
+ ? mix(LANTERN_LIGHT, ALARM, scene.watcher.alarm)
+ : LANTERN_LIGHT,
+ power: 0.55 * lit * (away ? 0.45 : 1) * (1 + flare * 1.6),
+ halo: 0.2 * lit * (away ? 0.5 : 1) * (1 + flare * 1.6)
+ });
+}
+
+function lanternTint(scene: Scene, lit: number) {
+ const { alarm } = scene.watcher;
+ if (alarm <= 0) return undefined;
+ const on = fraction(scene.seconds * 7) < 0.6;
+ return mix(hex("#ffd36a"), ALARM, on ? alarm : alarm * 0.4 * lit);
+}
+
+/** The lanterns on the hill, the newest still hopping down from the door. */
+export function drawProcession(scene: Scene) {
+ const { grid, layout, plan, moment, seconds, watcher } = scene;
+ if (
+ plan.greatLighting &&
+ (moment.act === "witching" || moment.act === "dawn")
+ )
+ return;
+ const shipped =
+ (moment.act === "witching" || moment.act === "dawn") &&
+ plan.event !== "reject";
+ const lanterns: Face[] = shipped
+ ? [...plan.procession, plan.face]
+ : plan.procession;
+ const peek = lanterns.length - 1;
+ lanterns.forEach((face, i) => {
+ const s = lanternSlot(i, LANTERNS_FOR_LIGHTING);
+ const p = pointAlong(layout.path, s, layout.aspect);
+ const bob = noise2(seconds * 1.1 + i * 3.1, i, 6) > 0.64 ? -1 : 0;
+ const lit = flicker(seconds + i * 1.7, i);
+ const away = watcher.secret && !(watcher.peek && i === peek);
+ drawLantern(grid, p.x, p.y - 0.6 + bob, face, {
+ lit,
+ away,
+ tint: lanternTint(scene, lit)
+ });
+ lanternLight(scene, p.x, p.y - 0.6 + bob, lit, away);
+ });
+
+ if (moment.act !== "shipping") return;
+ const t = moment.t;
+ if (plan.event === "reject") {
+ const s = segment(t, 2, 8.5) * 1.15;
+ if (t > 2 && s <= 1) {
+ const p = pointAlong(layout.path, s, layout.aspect);
+ const roll =
+ ["(@)", "(o)", "(@)", "(O)"][Math.trunc(seconds * 10) % 4] ?? "(@)";
+ grid.text(p.x - 1, p.y - 0.6, roll, PUMPKIN_MARK);
+ }
+ const chase = segment(t, 2.7, 9.8) * 1.15;
+ if (t > 2.7 && chase <= 1) {
+ const p = pointAlong(layout.path, chase, layout.aspect);
+ const frame =
+ Math.trunc(seconds * 8) % 2 === 0 ? SKELETON.runA : SKELETON.runB;
+ grid.sprite(p.x - 3, p.y - 4.6, frame, BONE);
+ }
+ return;
+ }
+ if (t < 2.5) return;
+ const u = segment(t, 2.5, 11.5);
+ const slot = lanternSlot(plan.procession.length, LANTERNS_FOR_LIGHTING);
+ const p = pointAlong(layout.path, slot * u, layout.aspect);
+ const hop = u < 1 ? Math.sin(fraction((t - 2.5) / 0.5) * Math.PI) * 1.2 : 0;
+ const lit = flicker(seconds, 99);
+ const away = watcher.secret && !watcher.peek;
+ drawLantern(grid, p.x, p.y - 0.6 - hop, plan.face, {
+ lit,
+ away,
+ tint: lanternTint(scene, lit)
+ });
+ lanternLight(scene, p.x, p.y - 0.6 - hop, lit, away);
+}
+
+export function drawGhost(scene: Scene) {
+ const { grid, layout, moment, seconds, watcher, lights } = scene;
+ let alpha = 0;
+ if (moment.act === "shipping") alpha = ease(segment(moment.t, 1.5, 4));
+ else if (moment.act === "witching") alpha = 1;
+ else if (moment.act === "dawn") alpha = 1 - ease(segment(moment.t, 6, 9));
+ if (alpha <= 0) return;
+ const first = layout.stones[0];
+ const last = layout.stones[layout.stones.length - 1];
+ const mid = first && last ? (first.x + last.x) / 2 : layout.cols * 0.45;
+ const base = first?.base ?? layout.horizon + 2;
+ const x = mid + Math.sin(seconds * 0.23) * layout.cols * 0.07;
+ const y = base - 6.5 + Math.sin(seconds * 1.2) * 0.7;
+ const body = watcher.secret
+ ? watcher.peek
+ ? GHOST.peek
+ : GHOST.shut
+ : GHOST.open;
+ const hem = GHOST.hem[Math.trunc(seconds * 2.5) % 2] ?? GHOST.hem[0] ?? "";
+ const color = mix(GROUND_BG, GHOST_GLOW, alpha * 0.9);
+ grid.sprite(x - 4, y, [...body, hem], color, mix(GROUND_BG, GHOST_BG, alpha));
+ lights.push({
+ x,
+ y: y + 2,
+ radius: 3.4,
+ color: hex("#b8b0ff"),
+ power: 0.18 * alpha,
+ halo: 0.1 * alpha
+ });
+}
+
+export function drawDance(scene: Scene) {
+ const { grid, layout, moment, plan, seconds } = scene;
+ if (plan.event !== "dance" || moment.act !== "witching" || plan.greatLighting)
+ return;
+ const f = layout.factory;
+ const x = f.door + 3;
+ const y = f.base - 4;
+ const step = Math.trunc(seconds / 0.4) % 2 === 0;
+ grid.sprite(x, y, step ? SKELETON.danceA : SKELETON.danceB, BONE);
+ grid.text(x + (step ? 7 : 6), y + (step ? 0 : 2), "c[_]", hex("#c8a27a"));
+ for (let k = 0; k < 3; k++) {
+ const age = fraction(seconds * 0.5 + k / 3);
+ grid.put(
+ x + 3 + Math.sin(age * 6 + k) * 2,
+ y - 1 - age * 5,
+ k % 2 ? "♪" : "♫",
+ scale(BONE, 1 - age)
+ );
+ }
+}
diff --git a/packages/react/src/Halloween/night-shift/interior.ts b/packages/react/src/Halloween/night-shift/interior.ts
index 9f52917bb0..346f82d4a9 100644
--- a/packages/react/src/Halloween/night-shift/interior.ts
+++ b/packages/react/src/Halloween/night-shift/interior.ts
@@ -7,13 +7,13 @@
// along, the way a Carbon job does. Once the candle catches, the whole floor
// turns from cold purple to warm orange.
+import { clamp01, ease, fraction, hash01, lerp, segment } from "../math";
import { carvedCells, cellKey, HERO_MIN_RADIUS } from "./faces";
import type { Color } from "./grid";
-import { hex, mix, scale } from "./grid";
+import { cellsFor, hex, mix, scale } from "./grid";
import { flicker, noise2 } from "./noise";
import { drawPumpkin } from "./pumpkin";
import type { Scene } from "./scene";
-import { clamp01, ease, fraction, hash01, lerp, segment } from "./scene";
import { CANDLE, LAMP, NOZZLE, SKELETON } from "./sprites";
const WALL_COLD = hex("#120c18");
@@ -46,8 +46,6 @@ const AMBER = hex("#f5b544");
const PENDING = hex("#5a5270");
const PUMPKIN_GLOW = hex("#ff8a2a");
-const STATIONS = ["Wash", "Carve", "Light", "QC"] as const;
-
/** Where the pumpkin is along the line, seconds into the act. */
function travel(t: number, stops: number[], start: number, exit: number) {
const [wash = 0, carve = 0, light = 0, qc = 0] = stops;
@@ -73,13 +71,30 @@ export function warmthAt(t: number) {
return ease(segment(t, 17.4, 18.6));
}
+/** A bracketed plate, `[ WORD ]`, centred on x, the word cut to fit. */
+function plate(
+ scene: Scene,
+ centre: number,
+ y: number,
+ word: string,
+ color: Color,
+ background: Color,
+ maxCells: number
+) {
+ const cells = Math.max(1, Math.min(cellsFor(word), maxCells));
+ const left = Math.trunc(centre - (cells + 4) / 2);
+ // `$` keeps the wall out from behind the plate.
+ scene.grid.sprite(left, y, [`[$${"$".repeat(cells)}$]`], color, background);
+ scene.grid.label(left + 2, y, word, color, cells, "center", background);
+}
+
function drawTicket(
scene: Scene,
done: boolean[],
rejected: boolean,
active: number
) {
- const { grid, layout, plan } = scene;
+ const { grid, layout, plan, labels } = scene;
const width = Math.min(layout.cols - 4, 48);
const left = Math.trunc((layout.cols - width) / 2);
const top = Math.max(7, Math.trunc(layout.rows * 0.12));
@@ -96,22 +111,33 @@ function drawTicket(
grid.put(left + width - 1, top + 2, "|", TICKET_LINE);
grid.text(left + 2, top + 1, plan.job, TICKET_JOB);
- grid.text(
- left + 3 + plan.job.length,
- top + 1,
- "· Jack-o'-lantern",
- TICKET_TEXT
- );
const finished = done.every(Boolean);
- const status =
- rejected && done[3] ? "Scrapped" : finished ? "Complete" : "In Progress";
- const statusColor = rejected && done[3] ? FAIL : finished ? PASS : AMBER;
- const statusLeft = left + width - 3 - status.length - 2;
+ const scrapped = rejected && done[3];
+ const status = scrapped
+ ? labels.scrapped
+ : finished
+ ? labels.complete
+ : labels.inProgress;
+ const statusColor = scrapped ? FAIL : finished ? PASS : AMBER;
+ // The status keeps up to a third of the ticket; the item takes the rest.
+ const statusCells = Math.min(cellsFor(status), Math.trunc(inner / 3));
+ const statusLeft = left + width - 3 - statusCells - 2;
grid.put(statusLeft, top + 1, "●", statusColor);
- grid.text(statusLeft + 2, top + 1, status, statusColor);
+ grid.label(statusLeft + 2, top + 1, status, statusColor, statusCells);
+ const itemLeft = left + 3 + plan.job.length;
+ grid.put(itemLeft, top + 1, "·", TICKET_TEXT);
+ grid.label(
+ itemLeft + 2,
+ top + 1,
+ labels.item,
+ TICKET_TEXT,
+ statusLeft - 1 - (itemLeft + 2)
+ );
+ // Four equal slots: a mark, a space, the station's name.
+ const slot = Math.trunc((inner - 2) / 4);
let x = left + 2;
- STATIONS.forEach((name, k) => {
+ labels.stations.forEach((name, k) => {
const isDone = done[k] ?? false;
const failed = rejected && k === 3 && isDone;
const mark = failed ? "✗" : isDone ? "✓" : k === active ? "●" : "○";
@@ -123,18 +149,19 @@ function drawTicket(
? AMBER
: PENDING;
grid.put(x, top + 2, mark, color);
- grid.text(
+ grid.label(
x + 2,
top + 2,
name,
- isDone || k === active ? TICKET_TEXT : PENDING
+ isDone || k === active ? TICKET_TEXT : PENDING,
+ slot - 3
);
- x += name.length + 6;
+ x += slot;
});
}
export function drawInterior(scene: Scene) {
- const { grid, layout, plan, moment, seconds, lights } = scene;
+ const { grid, layout, plan, moment, seconds, lights, labels } = scene;
const { cols, rows, aspect } = layout;
const t = moment.act === "line" ? moment.t : 24;
const warmth = warmthAt(t);
@@ -346,28 +373,29 @@ export function drawInterior(scene: Scene) {
grid.sprite(inspector.x, inspector.y, pose, BONE);
if (t >= 21.3) {
- // `$` keeps the wall out of the gaps between words.
- const stamp = rejected ? "[$REJECTED$]" : "[$QC$PASSED$]";
const pop = 1 - ease(segment(t, 21.3, 21.6)) * 0.4;
const color: Color = rejected ? FAIL : PASS;
- grid.sprite(
- qc - Math.trunc(stamp.length / 2),
+ plate(
+ scene,
+ qc,
beltY - radius * 2 - 3.5,
- [stamp],
+ (rejected ? labels.rejected : labels.passed).toLocaleUpperCase(),
scale(color, pop + 0.4),
- TICKET_BG
+ TICKET_BG,
+ Math.trunc(cols * 0.3)
);
}
// Signs last, so the wash pipe and the carving arm pass behind them.
stops.forEach((stop, k) => {
- const label = `[$${(STATIONS[k] ?? "").toUpperCase()}$]`;
- grid.sprite(
- stop - Math.trunc(label.length / 2),
+ plate(
+ scene,
+ stop,
signY,
- [label],
+ (labels.stations[k] ?? "").toLocaleUpperCase(),
SIGN,
- SIGN_BG
+ SIGN_BG,
+ Math.trunc(cols * 0.19) - 4
);
});
diff --git a/packages/react/src/Halloween/night-shift/layout.ts b/packages/react/src/Halloween/night-shift/layout.ts
index 171e5f112c..2750c93b4d 100644
--- a/packages/react/src/Halloween/night-shift/layout.ts
+++ b/packages/react/src/Halloween/night-shift/layout.ts
@@ -6,8 +6,9 @@
// Recomputed only when the panel resizes. The upper left stays clear for the
// Carbon logo and the lower band is fog, behind the panel's headline.
+import { floorOf, seeded } from "../math";
import { fbm2, noise2 } from "./noise";
-import { floorOf, hashSeed, seeded } from "./random";
+import { hashSeed } from "./random";
export type Point = { x: number; y: number };
diff --git a/packages/react/src/Halloween/night-shift/noise.ts b/packages/react/src/Halloween/night-shift/noise.ts
index d0cc55aa52..6bbbccd9fb 100644
--- a/packages/react/src/Halloween/night-shift/noise.ts
+++ b/packages/react/src/Halloween/night-shift/noise.ts
@@ -4,7 +4,7 @@
// Smooth value noise for fog, moon craters, ridges and candle flicker.
-import { floorOf } from "./random";
+import { ease, floorOf } from "../math";
function lattice(x: number, y: number, seed: number) {
let h =
@@ -15,16 +15,12 @@ function lattice(x: number, y: number, seed: number) {
return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
}
-function smooth(t: number) {
- return t * t * (3 - 2 * t);
-}
-
/** Value noise in [0, 1], continuous in x and y. */
export function noise2(x: number, y: number, seed = 0) {
const x0 = floorOf(x);
const y0 = floorOf(y);
- const fx = smooth(x - x0);
- const fy = smooth(y - y0);
+ const fx = ease(x - x0);
+ const fy = ease(y - y0);
const a = lattice(x0, y0, seed);
const b = lattice(x0 + 1, y0, seed);
const c = lattice(x0, y0 + 1, seed);
diff --git a/packages/react/src/Halloween/night-shift/paint.ts b/packages/react/src/Halloween/night-shift/paint.ts
index b34479152c..5e837b789d 100644
--- a/packages/react/src/Halloween/night-shift/paint.ts
+++ b/packages/react/src/Halloween/night-shift/paint.ts
@@ -9,7 +9,7 @@
// a fallback font need not share the monospace advance.
import type { FrameOut } from "./frame";
-import type { Grid } from "./grid";
+import type { Grid, Label } from "./grid";
import { blue, css, green, NO_BG, red } from "./grid";
export type Metrics = {
@@ -45,6 +45,31 @@ function quantize(color: number) {
return color & 0xf8f8f8;
}
+// Graphemes, so a cut never splits a letter from its marks.
+const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
+
+/** A label's whole string over its cells, cut with an ellipsis to fit. */
+function drawLabel(ctx: CanvasRenderingContext2D, label: Label, m: Metrics) {
+ const room = label.cells * m.cellWidth;
+ let text = label.text;
+ if (ctx.measureText(text).width > room) {
+ const parts = Array.from(graphemes.segment(text), (part) => part.segment);
+ while (parts.length > 0 && ctx.measureText(`${text}…`).width > room) {
+ parts.pop();
+ text = parts.join("");
+ }
+ text = `${text}…`;
+ }
+ const left = m.offsetX + label.x * m.cellWidth;
+ ctx.fillStyle = style(quantize(label.color));
+ ctx.textAlign = label.align;
+ ctx.fillText(
+ text,
+ label.align === "center" ? left + room / 2 : left,
+ m.offsetY + label.y * m.cellHeight + m.cellHeight / 2
+ );
+}
+
export function paint(
ctx: CanvasRenderingContext2D,
grid: Grid,
@@ -147,6 +172,8 @@ export function paint(
flush();
}
+ for (const label of grid.labels) drawLabel(ctx, label, m);
+
if (frame.flash > 0) {
ctx.fillStyle = `rgba(232,228,255,${frame.flash * 0.45})`;
ctx.fillRect(0, 0, m.width, m.height);
diff --git a/packages/react/src/Halloween/night-shift/palette.ts b/packages/react/src/Halloween/night-shift/palette.ts
new file mode 100644
index 0000000000..68c709e527
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/palette.ts
@@ -0,0 +1,71 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// The Night Shift's colours, shared by every part of the scene.
+
+import { GROUND, HILL, NIGHT, SILHOUETTE } from "../scene-palette";
+import { hex } from "./grid";
+
+export const SKY_TOP = hex(NIGHT);
+export const SKY_HORIZON = hex("#1d1233");
+export const DAWN_TOP = hex("#191628");
+export const DAWN_HORIZON = hex("#5d4a68");
+export const SILHOUETTE_BG = hex(SILHOUETTE);
+export const GROUND_BG = hex(GROUND);
+export const HILL_BG = hex(HILL);
+export const RIM_EDGE = hex("#5b4a8a");
+export const DAWN_EDGE = hex("#8a7a96");
+export const STAR_DIM = hex("#3a3460");
+export const STAR_BRIGHT = hex("#ece6ff");
+export const MOON_DARK = hex("#3a3352");
+export const MOON_LIT = hex("#f4ecd6");
+export const EARTHSHINE = hex("#211b33");
+export const BAT_DARK = hex("#0b0711");
+export const BAT_RIM = hex("#5d4d86");
+export const GRASS = hex("#2e2440");
+export const GRASS_LIT = hex("#4d3d6a");
+export const TEXTURE = hex("#241a33");
+export const PATH = hex("#4a3a5c");
+export const STONE = hex("#6f6890");
+export const STONE_RIM = hex("#a49cc8");
+export const STONE_BG = hex("#17111f");
+export const RIP = hex("#3d3656");
+export const FACTORY_TEXTURE = hex("#1a1226");
+export const ROOF = hex("#4b3b70");
+export const WINDOW_OFF = hex("#2a2140");
+export const WINDOW_DIM = hex("#7a3a10");
+export const WINDOW_LIT = hex("#ffb347");
+export const DOOR_WOOD = hex("#1d120e");
+export const DOOR_OPEN = hex("#8a4a12");
+export const CHIMNEY = hex("#3d2f52");
+export const SMOKE = hex("#6a6088");
+export const CLOCK_RIM = hex("#a89a6a");
+export const CLOCK_FACE = hex("#3a2f18");
+export const CLOCK_HAND = hex("#fff1c4");
+export const STEEL = hex("#5f5874");
+export const CABLE = hex("#8a83a0");
+export const VINE = hex("#33502a");
+export const LEAF = hex("#4c7034");
+export const PUMPKIN_SHELL = hex("#9a420c");
+export const PUMPKIN_MARK = hex("#cf6a1c");
+export const FENCE = hex("#4f3d4e");
+export const CAT_LINE = hex("#3e3058");
+export const CAT_BG = hex("#07040b");
+export const CAT_EYES = hex("#d4ff5a");
+export const CROW_LINE = hex("#3a304e");
+export const CROW_EYE = hex("#ffcc33");
+export const CAW = hex("#efe8ff");
+export const LANTERN_LIGHT = hex("#ff8a2a");
+export const ALARM = hex("#ff2d2d");
+export const GHOST_GLOW = hex("#ddd8f6");
+export const GHOST_BG = hex("#272238");
+export const BONE = hex("#ece4cf");
+export const VISITOR_RIM = hex("#4f4074");
+export const SHIP_GLOW = hex("#8fd6b8");
+export const SPIDER_EYES = hex("#ff3b3b");
+export const HEAD_GLOW = hex("#ffb347");
+export const RAIN = hex("#5d5585");
+export const BOLT = hex("#f3eeff");
+export const RING = hex("#d9c98e");
+export const STAR_GOLD = hex("#ffe6a8");
diff --git a/packages/react/src/Halloween/night-shift/plant.ts b/packages/react/src/Halloween/night-shift/plant.ts
new file mode 100644
index 0000000000..aba071c7cd
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/plant.ts
@@ -0,0 +1,279 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// The plant: the factory with its clock tower, the crane on its roof and
+// the hero pumpkin it lifts, and the clock's bong at midnight.
+
+import {
+ clamp01,
+ ease,
+ fraction,
+ hash01,
+ lerp,
+ nearest,
+ segment
+} from "../math";
+import { hex, mix, NO_BG, scale } from "./grid";
+import { flicker } from "./noise";
+import {
+ CABLE,
+ CHIMNEY,
+ CLOCK_FACE,
+ CLOCK_HAND,
+ CLOCK_RIM,
+ DOOR_OPEN,
+ DOOR_WOOD,
+ FACTORY_TEXTURE,
+ RING,
+ ROOF,
+ SILHOUETTE_BG,
+ SMOKE,
+ STEEL,
+ WINDOW_DIM,
+ WINDOW_LIT,
+ WINDOW_OFF
+} from "./palette";
+import { drawPumpkin } from "./pumpkin";
+import type { Scene } from "./scene";
+import { CLOCK } from "./sprites";
+import { ACTS, actStart } from "./story";
+
+const RUN_START = ACTS[0].seconds;
+
+/** The tower clock: 12 at midnight, about half past five at dawn, then back. */
+export function clockHours(scene: Scene) {
+ const { moment } = scene;
+ const runEnd = actStart("dawn") + 6;
+ const run = (s: number) =>
+ 5.6 * clamp01((s - RUN_START) / (runEnd - RUN_START));
+ if (moment.act !== "dawn") return run(moment.shiftT);
+ if (moment.t < 6) return run(moment.shiftT);
+ return run(runEnd) * (1 - ease(segment(moment.t, 6, 8.5)));
+}
+
+function handChar(angle: number) {
+ const a = ((angle % Math.PI) + Math.PI) % Math.PI;
+ if (a < Math.PI / 8 || a > (7 * Math.PI) / 8) return "|";
+ if (a < (3 * Math.PI) / 8) return "/";
+ if (a < (5 * Math.PI) / 8) return "-";
+ return "\\";
+}
+
+function strikeGlow(scene: Scene) {
+ if (scene.moment.act !== "midnight") return 0;
+ let glow = 0;
+ for (let k = 0; k < 12; k++) {
+ const age = scene.moment.t - (0.6 + k * 0.55);
+ if (age >= 0 && age < 0.5) glow = Math.max(glow, 1 - age / 0.5);
+ }
+ return glow;
+}
+
+export function drawFactory(scene: Scene, dawn: number) {
+ const { grid, layout, seconds, lights, moment, plan } = scene;
+ const f = layout.factory;
+ for (let r = f.roof; r < f.base + 1; r++) {
+ for (let c = f.left; c <= f.right; c++) {
+ grid.fill(c, r, SILHOUETTE_BG);
+ grid.blank(c, r);
+ if (hash01(c * 61 + r * 17) < 0.04) grid.put(c, r, ".", FACTORY_TEXTURE);
+ }
+ }
+ for (let c = f.left; c + 2 <= f.right; c += 3) {
+ grid.sprite(c, f.roof - 2, [" /|", "/$|"], ROOF, SILHOUETTE_BG);
+ }
+ for (const row of [f.roof + 2, f.roof + 5]) {
+ if (row > f.base - 3) continue;
+ for (let x = f.left + 2; x + 1 < f.right - 1; x += 4) {
+ if (Math.abs(x - f.door) < 3) continue;
+ const h = hash01(x * 13 + row * 7);
+ if (h > 0.28) {
+ const b = (0.6 + 0.4 * flicker(seconds + h * 10, x)) * (1 - dawn * 0.7);
+ grid.text(x, row, "[]", mix(WINDOW_DIM, WINDOW_LIT, b));
+ lights.push({
+ x: x + 1,
+ y: row + 0.5,
+ radius: 2.2,
+ color: WINDOW_LIT,
+ power: 0.32 * b,
+ halo: 0.05 * b
+ });
+ } else {
+ grid.text(x, row, "[]", WINDOW_OFF);
+ }
+ }
+ }
+ const open =
+ moment.act === "shipping" &&
+ moment.t > 1.5 &&
+ moment.t < (plan.event === "reject" ? 10 : 12.5);
+ grid.sprite(
+ f.door - 1,
+ f.base - 3,
+ [" _ ", "|$|", "|$|"],
+ ROOF,
+ open ? DOOR_OPEN : DOOR_WOOD
+ );
+ if (open) {
+ lights.push({
+ x: f.door,
+ y: f.base - 1.5,
+ radius: 4.5,
+ color: WINDOW_LIT,
+ power: 0.75,
+ halo: 0.22
+ });
+ }
+
+ for (let r = f.chimneyTop + 1; r < f.roof; r++) {
+ grid.sprite(f.chimney - 1, r, ["|$|"], CHIMNEY, SILHOUETTE_BG);
+ }
+ grid.text(f.chimney - 1, f.chimneyTop, "===", ROOF);
+ for (let k = 0; k < 16; k++) {
+ const age = fraction(seconds * 0.11 + k / 16);
+ const x =
+ f.chimney + age * age * 18 + Math.sin(seconds * 0.7 + k) * age * 2;
+ const y = f.chimneyTop - 1 - age * 12;
+ const char =
+ age < 0.18
+ ? "o"
+ : age < 0.5
+ ? k % 2
+ ? "("
+ : ")"
+ : age < 0.8
+ ? "~"
+ : ".";
+ if (grid.isBlank(x, y)) grid.put(x, y, char, scale(SMOKE, 1 - age * 0.75));
+ }
+
+ grid.put(f.tower, f.towerTop - 1, "+", ROOF);
+ grid.put(f.tower, f.towerTop, "^", ROOF);
+ for (let k = 1; k <= 4; k++) {
+ const y = f.towerTop + k;
+ grid.put(f.tower - k - 1, y, "/", ROOF);
+ grid.put(f.tower + k + 1, y, "\\", ROOF);
+ for (let c = f.tower - k; c <= f.tower + k; c++) {
+ grid.fill(c, y, SILHOUETTE_BG);
+ grid.blank(c, y);
+ }
+ }
+ for (let y = f.towerTop + 5; y < f.roof; y++) {
+ grid.put(f.tower - 5, y, "|", ROOF);
+ grid.put(f.tower + 5, y, "|", ROOF);
+ for (let c = f.tower - 4; c <= f.tower + 4; c++) {
+ grid.fill(c, y, SILHOUETTE_BG);
+ grid.blank(c, y);
+ }
+ }
+ const strike = strikeGlow(scene);
+ const face = mix(CLOCK_FACE, hex("#7a6430"), strike * 0.6);
+ grid.sprite(f.tower - 3, f.towerTop + 5, CLOCK, CLOCK_RIM, face);
+ const center = { x: f.tower, y: f.towerTop + 7 };
+ const hours = clockHours(scene);
+ const minute = fraction(hours) * Math.PI * 2;
+ const hour = (hours / 12) * Math.PI * 2;
+ for (const k of [1, 2]) {
+ grid.put(
+ center.x + nearest(Math.sin(minute) * k),
+ center.y + nearest(-Math.cos(minute) * k * 0.5),
+ handChar(minute),
+ CLOCK_HAND
+ );
+ }
+ const hx = center.x + nearest(Math.sin(hour) * 1.2);
+ const hy = center.y + nearest(-Math.cos(hour) * 0.6);
+ if (hx !== center.x || hy !== center.y)
+ grid.put(hx, hy, handChar(hour), scale(CLOCK_HAND, 0.85));
+ grid.put(center.x, center.y, "o", CLOCK_HAND);
+ lights.push({
+ x: center.x,
+ y: center.y,
+ radius: 3 + strike * 5,
+ color: hex("#ffd98a"),
+ power: 0.25 + strike * 0.8,
+ halo: 0.1 + strike * 0.3
+ });
+}
+
+/** The crane on the roof, and the hero pumpkin while it hangs from it. */
+export function drawCraneAndHero(scene: Scene) {
+ const { grid, layout, moment, seconds } = scene;
+ const f = layout.factory;
+ const stub = 4;
+ const reach = Math.max(stub, Math.trunc(layout.hero.x - f.mast));
+ const heroRadius =
+ moment.act === "midnight"
+ ? 1.05
+ : 1.05 +
+ 1.15 * ease(segment(moment.t, 2.5, 6.5)) +
+ 0.05 * Math.sin(seconds * 3);
+ const heroTop = layout.hero.y - heroRadius;
+ const t = moment.act === "harvest" ? moment.t : -1;
+
+ let length = stub;
+ let hookY = f.jib + 2;
+ let carried = false;
+ if (t >= 0) {
+ if (t < 8) length = lerp(stub, reach, ease(segment(t, 6, 8)));
+ else if (t < 11.5) length = reach;
+ else length = lerp(reach, stub, ease(segment(t, 11.5, 13.2)));
+ if (t >= 8 && t < 9.5)
+ hookY = lerp(f.jib + 2, heroTop - 1, ease(segment(t, 8, 9.5)));
+ else if (t >= 9.5 && t < 10) hookY = heroTop - 1;
+ else if (t >= 10 && t < 13.2)
+ hookY = lerp(heroTop - 1, f.jib + 3, ease(segment(t, 10, 11.5)));
+ else if (t >= 13.2)
+ hookY = lerp(f.jib + 3, f.roof + 2, ease(segment(t, 13.2, 14)));
+ carried = t >= 10;
+ }
+ const L = Math.trunc(length);
+ for (let y = f.jib; y < f.roof; y++) grid.put(f.mast, y, "H", STEEL);
+ for (let k = 1; k <= L; k++) {
+ grid.put(f.mast + k, f.jib, k === L ? ">" : "=", STEEL);
+ if (k < L)
+ grid.put(f.mast + k, f.jib + 1, k % 2 ? "\\" : "/", scale(STEEL, 0.7));
+ }
+ const hookX = f.mast + L - 1;
+ for (let y = f.jib + 1; y < hookY; y++) grid.put(hookX, y, "|", CABLE);
+ grid.put(hookX, hookY, "J", CABLE);
+
+ // Lowered through the roof hatch at the end of the harvest: gone inside.
+ const sunk = t >= 13.2 && hookY + 1 > f.roof - 1;
+ const showHero =
+ moment.act === "midnight" || (moment.act === "harvest" && !sunk);
+ if (!showHero) return;
+ const center = carried
+ ? { x: hookX + 0.5, y: hookY + 1 + heroRadius }
+ : { x: layout.hero.x, y: layout.hero.y };
+ drawPumpkin(grid, {
+ x: center.x,
+ y: center.y,
+ radius: heroRadius,
+ aspect: layout.aspect,
+ spin: seconds * 0.4,
+ seconds
+ });
+}
+
+export function drawBong(scene: Scene) {
+ const { grid, layout, moment } = scene;
+ if (moment.act !== "midnight") return;
+ const origin = { x: layout.factory.tower, y: layout.factory.towerTop + 7 };
+ for (let k = 0; k < 12; k++) {
+ const age = moment.t - (0.6 + k * 0.55);
+ if (age < 0 || age > 1.8) continue;
+ const radius = age * 15;
+ const strength = 1 - age / 1.8;
+ const samples = Math.max(12, Math.trunc(radius * layout.aspect * 6));
+ for (let s = 0; s < samples; s++) {
+ const a = (s / samples) * Math.PI * 2;
+ const x = origin.x + Math.cos(a) * radius * layout.aspect;
+ const y = origin.y + Math.sin(a) * radius;
+ if (!grid.isBlank(x, y) || grid.bg[grid.index(x, y)] !== NO_BG) continue;
+ const char = strength > 0.66 ? "*" : strength > 0.33 ? ":" : ".";
+ grid.put(x, y, char, scale(RING, strength * 0.8));
+ }
+ }
+}
diff --git a/packages/react/src/Halloween/night-shift/random.ts b/packages/react/src/Halloween/night-shift/random.ts
index 84f3bd7038..e8d09c0826 100644
--- a/packages/react/src/Halloween/night-shift/random.ts
+++ b/packages/react/src/Halloween/night-shift/random.ts
@@ -6,19 +6,7 @@
// seed, so a shift looks the same however often it is rendered, and the
// story can be replayed (and tested) from the seed alone.
-export type Random = () => number;
-
-/** Mulberry32: small, fast and good enough for picking pumpkin faces. */
-export function seeded(seed: number): Random {
- let state = seed >>> 0;
- return () => {
- state = (state + 0x6d2b79f5) >>> 0;
- let t = state;
- t = Math.imul(t ^ (t >>> 15), t | 1);
- t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
- };
-}
+import type { Random } from "../math";
/** Folds numbers into one 32-bit seed (FNV-1a over their bits). */
export function hashSeed(...parts: number[]): number {
@@ -31,12 +19,6 @@ export function hashSeed(...parts: number[]): number {
return hash >>> 0;
}
-/** The whole-number part, rounded towards minus infinity. */
-export function floorOf(value: number): number {
- const whole = Math.trunc(value);
- return value < whole ? whole - 1 : whole;
-}
-
/** Picks by weight: `[["a", 3], ["b", 1]]` gives "a" three times in four. */
export function pickWeighted<T>(
random: Random,
diff --git a/packages/react/src/Halloween/night-shift/scene.ts b/packages/react/src/Halloween/night-shift/scene.ts
index 700851665f..9eb2b28c82 100644
--- a/packages/react/src/Halloween/night-shift/scene.ts
+++ b/packages/react/src/Halloween/night-shift/scene.ts
@@ -48,8 +48,23 @@ export const IDLE_WATCHER: Watcher = {
alarm: 0
};
+/**
+ * The words the scene shows, in the user's language: the factory's four
+ * stations, the job on the line's ticket, its status and the QC stamp.
+ */
+export type Labels = {
+ stations: readonly [string, string, string, string];
+ item: string;
+ inProgress: string;
+ complete: string;
+ scrapped: string;
+ passed: string;
+ rejected: string;
+};
+
export type Scene = {
grid: Grid;
+ labels: Labels;
layout: Layout;
plan: ShiftPlan;
moment: Moment;
@@ -58,44 +73,3 @@ export type Scene = {
watcher: Watcher;
lights: Light[];
};
-
-export function clamp01(value: number) {
- return value <= 0 ? 0 : value >= 1 ? 1 : value;
-}
-
-/** 0 before `from`, 1 after `to`, linear between. */
-export function segment(t: number, from: number, to: number) {
- return clamp01((t - from) / (to - from));
-}
-
-export function ease(t: number) {
- const k = clamp01(t);
- return k * k * (3 - 2 * k);
-}
-
-export function lerp(a: number, b: number, t: number) {
- return a + (b - a) * t;
-}
-
-/** The nearest whole number, halves away from zero. */
-export function nearest(value: number) {
- return value >= 0 ? Math.trunc(value + 0.5) : -Math.trunc(-value + 0.5);
-}
-
-/** The fractional part, always in [0, 1). */
-export function fraction(value: number) {
- return (
- value -
- Math.trunc(value) +
- (value < 0 && value !== Math.trunc(value) ? 1 : 0)
- );
-}
-
-/** A stable pseudo-random number in [0, 1) for an integer. */
-export function hash01(n: number) {
- let h = Math.imul(n ^ 0x9e3779b9, 0x85ebca6b);
- h ^= h >>> 13;
- h = Math.imul(h, 0xc2b2ae35);
- h ^= h >>> 16;
- return (h >>> 0) / 4294967296;
-}
diff --git a/packages/react/src/Halloween/night-shift/sky.ts b/packages/react/src/Halloween/night-shift/sky.ts
new file mode 100644
index 0000000000..7069b9825d
--- /dev/null
+++ b/packages/react/src/Halloween/night-shift/sky.ts
@@ -0,0 +1,341 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// The sky over the hill: stars, the moon, bats, the witching hour's
+// visitors, rain and lightning. Also when the dawn and the Great Lighting
+// are, and what sits in front of the moon, which the hill and plant read.
+
+import { clamp01, ease, fraction, hash01, lerp, segment } from "../math";
+import type { Color } from "./grid";
+import { hex, mix, scale } from "./grid";
+import { fbm2, noise2 } from "./noise";
+import {
+ BAT_DARK,
+ BAT_RIM,
+ BOLT,
+ CABLE,
+ DAWN_EDGE,
+ EARTHSHINE,
+ HEAD_GLOW,
+ MOON_DARK,
+ MOON_LIT,
+ RAIN,
+ SHIP_GLOW,
+ SPIDER_EYES,
+ STAR_BRIGHT,
+ STAR_DIM,
+ VISITOR_RIM
+} from "./palette";
+import type { Scene } from "./scene";
+import { BAT, BOO, HORSEMAN, SHIP, SPIDER, WITCH } from "./sprites";
+
+/** How far into the dawn: the sky pales, then the clock spins back. */
+export function dawnAt(scene: Scene) {
+ return scene.moment.act === "dawn" ? ease(segment(scene.moment.t, 0, 6)) : 0;
+}
+
+/** Seconds into the Great Lighting (the witching hour, then the dawn). */
+export function lightingTime(scene: Scene) {
+ const { moment } = scene;
+ if (moment.act === "witching") return moment.t;
+ if (moment.act === "dawn") return 14 + moment.t;
+ return -1;
+}
+
+/**
+ * Where the moon is. On the shift of the Great Lighting it sets behind the
+ * hills as the lanterns rise, and leaves them the sky.
+ */
+function moonAt(scene: Scene) {
+ const { moon, horizon } = scene.layout;
+ if (!scene.plan.greatLighting) return moon;
+ const T = lightingTime(scene);
+ if (T < 0) return moon;
+ const set = ease(segment(T, 0.5, 7));
+ return { ...moon, y: lerp(moon.y, horizon + moon.r + 2, set) };
+}
+
+export function overMoon(scene: Scene, x: number, y: number) {
+ const { aspect } = scene.layout;
+ const moon = moonAt(scene);
+ const dx = (x + 0.5 - moon.x) / (moon.r * aspect);
+ const dy = (y + 0.5 - moon.y) / moon.r;
+ return dx * dx + dy * dy <= 1;
+}
+
+/** A silhouette's glyph colour: black against the moon, rim-lit elsewhere. */
+export function silhouette(scene: Scene, dark: Color, rim: Color) {
+ return (x: number, y: number) => (overMoon(scene, x, y) ? dark : rim);
+}
+
+export function drawStars(scene: Scene, dawn: number) {
+ const { grid, layout, seconds } = scene;
+ for (const star of layout.stars) {
+ const v = noise2(seconds * 0.7 + star.seed * 0.013, star.seed % 97);
+ const shine = (0.3 + 0.7 * v) * (1 - dawn);
+ if (shine < 0.14) continue;
+ const char = v > 0.8 ? "*" : v > 0.64 ? "+" : v > 0.4 ? "." : "'";
+ grid.put(star.x, star.y, char, mix(STAR_DIM, STAR_BRIGHT, shine));
+ }
+}
+
+const MOON_RAMP = " .:-=+*#%@";
+
+export function drawMoon(scene: Scene, dawn: number) {
+ const { grid, layout, plan, lights } = scene;
+ const { aspect } = layout;
+ const moon = moonAt(scene);
+ const angle = plan.moonPhase * Math.PI * 2;
+ const lx = Math.sin(angle);
+ const lz = Math.cos(angle);
+ const rx = moon.r * aspect;
+ for (
+ let row = Math.trunc(moon.y - moon.r) - 1;
+ row <= moon.y + moon.r + 1;
+ row++
+ ) {
+ for (let col = Math.trunc(moon.x - rx) - 1; col <= moon.x + rx + 1; col++) {
+ const nx = (col + 0.5 - moon.x) / rx;
+ const ny = (row + 0.5 - moon.y) / moon.r;
+ const d2 = nx * nx + ny * ny;
+ if (d2 > 1) continue;
+ const nz = Math.sqrt(1 - d2);
+ const facing = nx * lx + nz * lz;
+ const lit = clamp01((facing + 0.06) / 0.2);
+ const maria = clamp01(
+ (fbm2(nx * 2.4 + 3, ny * 2.4 + 1, 3, 5) - 0.5) / 0.16
+ );
+ const crater = noise2(nx * 9 + 1, ny * 9 + 4, 9) > 0.78 ? 0.75 : 1;
+ const brightness = lit * (0.7 + 0.3 * nz) * (1 - 0.35 * maria) * crater;
+ if (brightness < 0.07) {
+ if ((col + row) % 2 === 0) grid.put(col, row, ".", EARTHSHINE);
+ continue;
+ }
+ const index = Math.min(
+ MOON_RAMP.length - 1,
+ Math.trunc(brightness * MOON_RAMP.length)
+ );
+ grid.put(
+ col,
+ row,
+ MOON_RAMP[index] ?? "@",
+ mix(MOON_DARK, mix(MOON_LIT, DAWN_EDGE, dawn * 0.5), brightness)
+ );
+ }
+ }
+ const illumination = (1 + lz) / 2;
+ lights.push({
+ x: moon.x,
+ y: moon.y,
+ radius: moon.r * 3,
+ color: hex("#b9b0e0"),
+ power: 0,
+ halo: (0.08 + 0.14 * illumination) * (1 - dawn * 0.6)
+ });
+}
+
+function batTargets(scene: Scene) {
+ const { cols, rows } = scene.layout;
+ const targets: { x: number; y: number }[] = [];
+ const spacingX = 2;
+ const spacingY = 1;
+ const letterWidth = spacingX * 5 + 4;
+ const left = cols * 0.4 - (letterWidth * BOO.length) / 2;
+ BOO.forEach((letter, k) => {
+ letter.forEach((line, row) => {
+ for (let col = 0; col < line.length; col++) {
+ if (line[col] !== "#") continue;
+ targets.push({
+ x: left + k * letterWidth + col * spacingX,
+ y: rows * 0.13 + row * spacingY
+ });
+ }
+ });
+ });
+ return targets;
+}
+
+export function drawBats(scene: Scene) {
+ const { grid, layout, plan, moment, seconds } = scene;
+ const t = moment.shiftT;
+ if (t > 16) return;
+ const boo = plan.event === "boo";
+ const targets = boo ? batTargets(scene) : [];
+ const count = boo ? targets.length : 12;
+ const belfry = { x: layout.factory.tower, y: layout.factory.towerTop + 2 };
+ const shade = silhouette(scene, BAT_DARK, BAT_RIM);
+ for (let i = 0; i < count; i++) {
+ const start = 1 + i * (boo ? 0.06 : 0.13);
+ const u = (t - start) / (boo ? 11 : 8.5);
+ if (u < 0 || u > 1) continue;
+ const r1 = hash01(i * 7 + plan.index * 131);
+ const r2 = hash01(i * 13 + 5);
+ const control = {
+ x: layout.moon.x + (r1 - 0.5) * layout.moon.r * layout.aspect * 2.6,
+ y: layout.moon.y + (r2 - 0.5) * layout.moon.r * 2.2
+ };
+ const exit = {
+ x: layout.cols + 6 + r1 * 10,
+ y: layout.rows * (0.02 + hash01(i * 31 + 2) * 0.16)
+ };
+ const a = (1 - u) * (1 - u);
+ const b = 2 * (1 - u) * u;
+ const c = u * u;
+ let x = a * belfry.x + b * control.x + c * exit.x;
+ let y =
+ a * belfry.y +
+ b * control.y +
+ c * exit.y +
+ Math.sin(seconds * 9 + i) * 0.5;
+ const target = targets[i];
+ let folded = false;
+ if (target) {
+ const w = ease(segment(t, 3.4, 4.8)) * (1 - ease(segment(t, 7.4, 8.4)));
+ x = lerp(x, target.x, w);
+ y = lerp(y, target.y, w);
+ // In formation each bat hangs as one glyph, so the letters read.
+ folded = w > 0.85;
+ }
+ if (folded) {
+ grid.put(x, y, "v", shade(x, y));
+ continue;
+ }
+ const frame =
+ BAT[Math.trunc(seconds * 11 + i * 0.37) % BAT.length] ?? "-v-";
+ for (let k = 0; k < frame.length; k++) {
+ grid.put(x - 1 + k, y, frame[k] ?? " ", shade(x - 1 + k, y));
+ }
+ }
+}
+
+export function drawSkyVisitor(scene: Scene) {
+ const { grid, layout, plan, moment, seconds, lights } = scene;
+ if (moment.act !== "witching" || plan.greatLighting) return;
+ const t = moment.t;
+ const { moon, cols } = layout;
+ const shade = silhouette(scene, BAT_DARK, VISITOR_RIM);
+ if (plan.visitor === "witch") {
+ const u = segment(t, 2, 12);
+ if (u <= 0 || u >= 1) return;
+ const x = lerp(cols + 4, -22, u);
+ const y = moon.y - 3 + Math.sin(t * 1.3) * 1.4;
+ const cape = WITCH.cape[Math.trunc(seconds * 5) % 2] ?? "";
+ const art = [...WITCH.body.slice(0, 4), cape, WITCH.broom];
+ grid.sprite(x, y, art, (_char, col, row) => shade(x + col, y + row));
+ return;
+ }
+ if (plan.visitor === "ship") {
+ const u = segment(t, 1.5, 13);
+ if (u <= 0 || u >= 1) return;
+ const x = lerp(-30, cols + 2, u);
+ const y = moon.y - 2 + Math.sin(t * 0.9) * 0.6;
+ grid.sprite(x, y, SHIP, (_char, col, row) =>
+ overMoon(scene, x + col, y + row) ? hex("#163a30") : SHIP_GLOW
+ );
+ lights.push({
+ x: x + 13,
+ y: y + 3,
+ radius: 6,
+ color: SHIP_GLOW,
+ power: 0.15,
+ halo: 0.12
+ });
+ return;
+ }
+ if (plan.visitor === "spider") {
+ const down = ease(segment(t, 1.5, 5));
+ const up = ease(segment(t, 10, 13));
+ const drop = down * (1 - up);
+ if (drop <= 0) return;
+ const x = moon.x - 6;
+ const y = lerp(-6, moon.y - 1, drop) + Math.sin(seconds * 1.6) * 0.4 * drop;
+ for (let r = 0; r < y; r++) grid.put(x + 6, r, "|", scale(CABLE, 0.7));
+ grid.sprite(x, y, SPIDER, (char, col, row) =>
+ char === "o" ? SPIDER_EYES : shade(x + col, y + row)
+ );
+ lights.push({
+ x: x + 6,
+ y: y + 1,
+ radius: 1.6,
+ color: SPIDER_EYES,
+ power: 0.3,
+ halo: 0.08
+ });
+ }
+}
+
+export function drawHorseman(scene: Scene) {
+ const { grid, layout, plan, moment, seconds, lights } = scene;
+ if (
+ moment.act !== "witching" ||
+ plan.greatLighting ||
+ plan.visitor !== "horseman"
+ )
+ return;
+ const u = segment(moment.t, 2, 11);
+ if (u <= 0 || u >= 1) return;
+ const x = lerp(-22, layout.cols + 2, u);
+ const column = Math.trunc(x + 10);
+ const ground =
+ layout.ridge[Math.max(0, Math.min(layout.cols - 1, column))] ??
+ layout.horizon;
+ const gallop = Math.trunc(seconds * 8) % 2;
+ const y = ground - 4.6 - (gallop ? 0.4 : 0);
+ const legs = HORSEMAN.legs[gallop] ?? "";
+ grid.sprite(x, y, [...HORSEMAN.body, legs], (char) =>
+ char === "@" || char === "(" || char === ")" ? HEAD_GLOW : VISITOR_RIM
+ );
+ lights.push({
+ x: x + 12,
+ y,
+ radius: 2.5,
+ color: HEAD_GLOW,
+ power: 0.5,
+ halo: 0.2
+ });
+}
+
+export function drawRain(scene: Scene) {
+ const { grid, layout, plan, moment, seconds } = scene;
+ if (plan.weather !== "drizzle") return;
+ const heavy = moment.act === "witching" ? 1.7 : 1;
+ const count = Math.trunc(layout.cols * 0.45 * heavy);
+ for (let k = 0; k < count; k++) {
+ const speed = 22 + hash01(k * 3) * 10;
+ const y =
+ fraction((seconds * speed) / (layout.rows + 6) + hash01(k * 11)) *
+ (layout.rows + 6) -
+ 3;
+ const x = hash01(k * 17) * (layout.cols + 10) - 5 + y * 0.3;
+ grid.put(x, y, k % 3 === 0 ? "," : "'", RAIN);
+ }
+}
+
+/** Lightning in the witching hour: draws the bolt, returns the flash. */
+export function drawLightning(scene: Scene) {
+ const { grid, layout, plan, moment } = scene;
+ if (moment.act !== "witching" || plan.greatLighting) return 0;
+ let flash = 0;
+ const strikes = [
+ 3.2 + hash01(plan.index * 3) * 1.5,
+ 8.7 + hash01(plan.index * 5) * 1.8
+ ];
+ strikes.forEach((at, k) => {
+ const age = moment.t - at;
+ if (age < 0 || age > 0.6) return;
+ flash = Math.max(
+ flash,
+ age < 0.08 ? 1 : age < 0.18 ? 0.35 : age < 0.26 ? 0.7 : 0
+ );
+ let x = layout.cols * (0.15 + hash01(plan.index * 7 + k) * 0.75);
+ const bright = scale(BOLT, 1 - age / 0.6);
+ for (let y = 0; y < (layout.ridge[Math.trunc(x)] ?? layout.horizon); y++) {
+ const step = hash01(plan.index * 97 + k * 31 + y) * 3;
+ const dx = step < 1 ? -1 : step < 2 ? 0 : 1;
+ grid.put(x, y, dx < 0 ? "/" : dx > 0 ? "\\" : "|", bright);
+ x += dx;
+ }
+ });
+ return flash;
+}
diff --git a/packages/react/src/Halloween/night-shift/story.ts b/packages/react/src/Halloween/night-shift/story.ts
index 22812cd4d8..499ecb2a26 100644
--- a/packages/react/src/Halloween/night-shift/story.ts
+++ b/packages/react/src/Halloween/night-shift/story.ts
@@ -8,9 +8,10 @@
// then a rare event), and the lanterns it ships stay on the hill. When the
// hill holds thirteen, they all rise and become the Carbon mark in the sky.
+import { seeded } from "../math";
import type { Face } from "./faces";
import { drawFace } from "./faces";
-import { hashSeed, pickWeighted, seeded } from "./random";
+import { hashSeed, pickWeighted } from "./random";
export const ACTS = [
{ id: "midnight", seconds: 9 },
diff --git a/packages/react/src/Halloween/scene.ts b/packages/react/src/Halloween/scene.ts
index 52efe1e474..afb4bded40 100644
--- a/packages/react/src/Halloween/scene.ts
+++ b/packages/react/src/Halloween/scene.ts
@@ -6,17 +6,7 @@
// so the scene is identical on every open. The scene's coordinates are a
// 1600 × 900 viewBox; the ground line sits around y 700–760.
-/** mulberry32: a small seeded PRNG returning [0, 1). */
-export function seededRandom(seed: number) {
- let state = seed >>> 0;
- return () => {
- state = (state + 0x6d2b79f5) >>> 0;
- let t = state;
- t = Math.imul(t ^ (t >>> 15), t | 1);
- t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
- };
-}
+import { seeded } from "./math";
export type Star = {
id: string;
@@ -30,7 +20,7 @@ export type Star = {
// Most stars are faint pinpricks; a cubed random keeps the big ones rare.
export const STARS: Star[] = (() => {
- const rand = seededRandom(1031);
+ const rand = seeded(1031);
return Array.from({ length: 120 }, (_, i) => {
const size = rand();
return {
@@ -61,7 +51,7 @@ export const BRIGHT_STARS = [
* line from the top left down towards the moon, as one path of tiny circles.
*/
export const STAR_DUST = (() => {
- const rand = seededRandom(2203);
+ const rand = seeded(2203);
let d = "";
for (let i = 0; i < 220; i++) {
const t = rand();
@@ -81,7 +71,7 @@ export const STAR_DUST = (() => {
* little and leans back towards the line, the way a real channel does.
*/
export const LIGHTNING = (() => {
- const rand = seededRandom(1310);
+ const rand = seeded(1310);
function channel(
x: number,
y: number,
@@ -128,7 +118,7 @@ export const SHOOTING_STARS = [
* puff is more than a half circle, so neighbours overlap like real billows.
*/
function cloudPath(width: number, height: number, seed: number) {
- const rand = seededRandom(seed);
+ const rand = seeded(seed);
const puffs = 6;
const step = width / puffs;
let d = "M 0 0";
@@ -186,7 +176,7 @@ export const CLOUDS = [
* width, so each depth is drawn as a single stroked path.
*/
export const TREE = (() => {
- const rand = seededRandom(666);
+ const rand = seeded(666);
const baseX = 1432;
const baseY = 790;
const byDepth: string[] = [];
@@ -254,7 +244,7 @@ export const TREE = (() => {
* the graveyard gate between two stone pillars.
*/
export const FENCE = (() => {
- const rand = seededRandom(13);
+ const rand = seeded(13);
const startX = 520;
const count = 30;
const gap = 16;
@@ -364,7 +354,7 @@ function bladesPath({
height: [number, number];
perClump: number;
}) {
- const rand = seededRandom(seed);
+ const rand = seeded(seed);
let d = "";
for (let x = from; x < to; x += every[0] + rand() * (every[1] - every[0])) {
const ground = base(x);
@@ -431,7 +421,7 @@ export const FAR_RIDGE = (() => {
for (let x = -70; x <= 1680; x += 10) line += ` L ${x} ${ridge(x)}`;
const d = `${line} L 1680 900 L -80 900 Z`;
- const rand = seededRandom(91);
+ const rand = seeded(91);
let trees = "";
for (const x of [618, 640, 652, 846, 862, 1000, 1018, 1196, 1210]) {
const tall = 14 + rand() * 16;
@@ -456,7 +446,7 @@ export type Drifter = {
/** Fireflies over the graveyard, each wandering its own small loop. */
export const FIREFLIES: Drifter[] = (() => {
- const rand = seededRandom(3110);
+ const rand = seeded(3110);
return Array.from({ length: 18 }, (_, i) => ({
id: `firefly-${i}`,
x: 260 + rand() * 1300,
@@ -517,7 +507,7 @@ export type FogPuff = {
/** One bank of ground fog: a row of soft overlapping puffs. */
function fogBank(seed: number, y: number, rx: number, ry: number): FogPuff[] {
- const rand = seededRandom(seed);
+ const rand = seeded(seed);
const puffs: FogPuff[] = [];
for (let x = -260; x < 1900; x += rx * (0.7 + rand() * 0.5)) {
puffs.push({
diff --git a/packages/react/src/Halloween/season.ts b/packages/react/src/Halloween/season.ts
index 885cba1513..3a41778006 100644
--- a/packages/react/src/Halloween/season.ts
+++ b/packages/react/src/Halloween/season.ts
@@ -3,7 +3,7 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { halloweenTheme } from "@carbon/utils";
-import { useSyncExternalStore } from "react";
+import useHydrated from "../hooks/useHydrated";
import { useRouteData } from "../hooks/useRouteData";
// The one check every Halloween decoration sits behind, the sign-in page's
@@ -13,23 +13,12 @@ import { useRouteData } from "../hooks/useRouteData";
// and off by itself, and the rest of the year nothing is rendered, styled or
// listened to.
-// Hydration never reverses, so there is nothing to listen to.
-function subscribe() {
- return () => {
- // Nothing to unsubscribe.
- };
-}
-
/**
* Whether the Halloween decorations are on. False on the server: they
* measure the page and listen to the document, so they mount after hydration.
*/
export function useHalloween() {
const root = useRouteData<{ theme?: string }>("/");
- const hydrated = useSyncExternalStore(
- subscribe,
- () => true,
- () => false
- );
+ const hydrated = useHydrated();
return hydrated && root?.theme === halloweenTheme.name;
}
diff --git a/packages/react/src/Halloween/spider-rig.test.ts b/packages/react/src/Halloween/spider-rig.test.ts
index aefcb0dd96..4ca8de837a 100644
--- a/packages/react/src/Halloween/spider-rig.test.ts
+++ b/packages/react/src/Halloween/spider-rig.test.ts
@@ -3,15 +3,9 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { describe, expect, it } from "vitest";
-import type { Surface } from "./spider-rig";
import { createRig, LEGS, SPIDER_SCALE, solveKnee } from "./spider-rig";
// The page: a foot holds wherever it lands.
-const page: Surface = {
- grip: (x, y) => ({ x, y, hold: null }),
- locate: () => ({ x: 0, y: 0 })
-};
-
const DT = 1 / 120;
function groupOf(leg: number) {
@@ -50,10 +44,10 @@ describe("createRig", () => {
it("keeps every foot planted while the body holds still", () => {
const rig = createRig();
const body = { x: 100, y: 100, angle: 0 };
- rig.place(body, page);
+ rig.place(body);
const placed = rig.feet();
for (let i = 0; i < 240; i++) {
- rig.update(DT, body, { x: 0, y: 0 }, page, "walk");
+ rig.update(DT, body, { x: 0, y: 0 }, "walk");
}
expect(rig.stepping()).toBe(false);
expect(rig.feet()).toEqual(placed);
@@ -62,14 +56,14 @@ describe("createRig", () => {
it("walks with an alternating gait: four feet down, the groups taking turns", () => {
const rig = createRig();
const body = { x: 0, y: 0, angle: 0 };
- rig.place(body, page);
+ rig.place(body);
// An unhurried walk: about four body lengths a second.
const speed = 60 * SPIDER_SCALE;
const steps = { 0: 0, 1: 0 };
let wasUp = new Set<number>();
for (let i = 0; i < 360; i++) {
body.y += speed * DT;
- rig.update(DT, body, { x: 0, y: speed }, page, "walk");
+ rig.update(DT, body, { x: 0, y: speed }, "walk");
const up = new Set(
rig
.feet()
@@ -90,35 +84,13 @@ describe("createRig", () => {
expect(Math.abs(steps[0] - steps[1])).toBeLessThanOrEqual(4);
});
- it("feet holding a thread go with it as it sways", () => {
- const rig = createRig();
- let sway = 0;
- const thread: Surface = {
- grip: (x, y) => ({ x, y, hold: { x, y } }),
- locate: (hold) => {
- const p = hold as { x: number; y: number };
- return { x: p.x + sway, y: p.y };
- }
- };
- const body = { x: 50, y: 50, angle: 0 };
- rig.place(body, thread);
- const before = rig.feet();
- sway = 2;
- rig.update(DT, body, { x: 0, y: 0 }, thread, "walk");
- rig.feet().forEach((foot, i) => {
- const was = before[i];
- if (!was) throw new Error(`no foot ${i} before`);
- expect(foot.x).toBeCloseTo(was.x + 2);
- });
- });
-
it("draws its legs in when it dangles", () => {
const rig = createRig();
const body = { x: 0, y: 0, angle: 0 };
- rig.place(body, page);
+ rig.place(body);
const spread = Math.max(...rig.feet().map((f) => Math.hypot(f.x, f.y)));
for (let i = 0; i < 120; i++) {
- rig.update(DT, body, { x: 0, y: 0 }, page, "curl");
+ rig.update(DT, body, { x: 0, y: 0 }, "curl");
}
const drawnIn = Math.max(...rig.feet().map((f) => Math.hypot(f.x, f.y)));
expect(drawnIn).toBeLessThan(spread * 0.6);
diff --git a/packages/react/src/Halloween/spider-rig.ts b/packages/react/src/Halloween/spider-rig.ts
index 6b9123c27c..63a5ff208b 100644
--- a/packages/react/src/Halloween/spider-rig.ts
+++ b/packages/react/src/Halloween/spider-rig.ts
@@ -4,8 +4,7 @@
// The spider's legs, animated the way real legs work rather than wiggled.
//
-// Each foot grips something (a thread of the web, or the page) and stays put
-// while the body moves over it. Once the body has drawn too far ahead of a
+// Each foot stays put on the page while the body moves over it. Once the body has drawn too far ahead of a
// foot, the leg lifts and swings it forward to a new grip. Spiders walk with
// an alternating tetrapod gait: legs 1 and 3 on one side step together with
// legs 2 and 4 on the other, then the other four, so four feet are always
@@ -15,21 +14,13 @@
// The body's own frame has the head along +y and the spider's right along
// +x; an angle of 0 points the head down the screen.
+import { at, ease } from "./math";
+
// Sized to sit in the top bar: about 20 px from fangs to spinnerets.
export const SPIDER_SCALE = 0.72;
type Vec = { x: number; y: number };
-/** Whatever a foot is holding: the caller turns it back into a live point. */
-export type Hold = unknown;
-
-export type Surface = {
- /** The grip nearest a point: where the foot goes, and what it holds. */
- grip(x: number, y: number): { x: number; y: number; hold: Hold | null };
- /** Where a hold is now (the web sways, and the feet go with it). */
- locate(hold: Hold): Vec;
-};
-
export type Body = { x: number; y: number; angle: number };
type LegSpec = {
@@ -64,13 +55,11 @@ export const LEGS: LegSpec[] = ([-1, 1] as const).flatMap((side) =>
type Foot = {
x: number;
y: number;
- hold: Hold | null;
stepping: boolean;
fromX: number;
fromY: number;
toX: number;
toY: number;
- toHold: Hold | null;
t: number;
duration: number;
};
@@ -81,14 +70,6 @@ export type LegPose = { hip: Vec; knee: Vec; ankle: Vec; foot: Vec };
// can be: a stride is never longer than a leg.
const LEAD = 0.11;
const MAX_LEAD = 9;
-const smooth = (t: number) => t * t * (3 - 2 * t);
-
-// A leg number always names one of the eight legs, so a missing one is a bug.
-function at<T>(list: readonly T[], i: number): T {
- const value = list[i];
- if (value === undefined) throw new Error(`spider rig: no leg ${i}`);
- return value;
-}
export function toWorld(body: Body, p: Vec): Vec {
const cos = Math.cos(body.angle);
@@ -147,13 +128,11 @@ export function createRig() {
const feet: Foot[] = LEGS.map(() => ({
x: 0,
y: 0,
- hold: null,
stepping: false,
fromX: 0,
fromY: 0,
toX: 0,
toY: 0,
- toHold: null,
t: 0,
duration: 0.1
}));
@@ -165,36 +144,25 @@ export function createRig() {
return (upper + lower) * SPIDER_SCALE;
};
- function startStep(
- i: number,
- target: Vec,
- surface: Surface,
- speed: number,
- duration?: number
- ) {
+ function startStep(i: number, target: Vec, speed: number) {
const foot = at(feet, i);
- const grip = surface.grip(target.x, target.y);
foot.stepping = true;
foot.fromX = foot.x;
foot.fromY = foot.y;
- foot.toX = grip.x;
- foot.toY = grip.y;
- foot.toHold = grip.hold;
+ foot.toX = target.x;
+ foot.toY = target.y;
foot.t = 0;
// Quick steps when running, deliberate ones when creeping.
- foot.duration =
- duration ?? Math.max(0.05, Math.min(0.12, 0.12 - speed / 2000));
+ foot.duration = Math.max(0.05, Math.min(0.12, 0.12 - speed / 2000));
}
return {
- /** Put every foot straight down where it rests, gripping the surface. */
- place(body: Body, surface: Surface) {
+ /** Put every foot straight down where it rests. */
+ place(body: Body) {
feet.forEach((foot, i) => {
const p = restAt(body, i);
- const grip = surface.grip(p.x, p.y);
- foot.x = grip.x;
- foot.y = grip.y;
- foot.hold = grip.hold;
+ foot.x = p.x;
+ foot.y = p.y;
foot.stepping = false;
});
},
@@ -203,30 +171,16 @@ export function createRig() {
* Move the feet for this step of the body. "curl" draws the legs in, as a
* spider dangling from a thread holds them.
*/
- update(
- dt: number,
- body: Body,
- velocity: Vec,
- surface: Surface,
- mode: "walk" | "curl"
- ) {
+ update(dt: number, body: Body, velocity: Vec, mode: "walk" | "curl") {
const speed = Math.hypot(velocity.x, velocity.y);
- for (const foot of feet) {
- if (!foot.stepping && foot.hold !== null) {
- const p = surface.locate(foot.hold);
- foot.x = p.x;
- foot.y = p.y;
- }
- }
if (mode === "curl") {
- const ease = Math.min(1, dt * 14);
+ const pull = Math.min(1, dt * 14);
feet.forEach((foot, i) => {
const rest = at(LEGS, i).rest;
const p = toWorld(body, { x: rest.x * 0.42, y: rest.y * 0.42 + 2 });
- foot.x += (p.x - foot.x) * ease;
- foot.y += (p.y - foot.y) * ease;
- foot.hold = null;
+ foot.x += (p.x - foot.x) * pull;
+ foot.y += (p.y - foot.y) * pull;
foot.stepping = false;
});
return;
@@ -238,11 +192,8 @@ export function createRig() {
feet.forEach((foot, i) => {
if (!foot.stepping) return;
foot.t = Math.min(1, foot.t + dt / foot.duration);
- const to =
- foot.toHold !== null
- ? surface.locate(foot.toHold)
- : { x: foot.toX, y: foot.toY };
- const e = smooth(foot.t);
+ const to = { x: foot.toX, y: foot.toY };
+ const e = ease(foot.t);
const stride = Math.hypot(to.x - foot.fromX, to.y - foot.fromY);
const swing =
Math.sin(Math.PI * foot.t) *
@@ -252,7 +203,6 @@ export function createRig() {
foot.y = foot.fromY + (to.y - foot.fromY) * e + lateral.y * swing;
if (foot.t >= 1) {
foot.stepping = false;
- foot.hold = foot.toHold;
foot.x = to.x;
foot.y = to.y;
}
@@ -280,7 +230,7 @@ export function createRig() {
if (!due) continue;
LEGS.forEach((leg, i) => {
if (leg.group === group && at(error, i) > threshold * 0.4) {
- startStep(i, at(targets, i), surface, speed);
+ startStep(i, at(targets, i), speed);
}
});
nextGroup = group === 0 ? 1 : 0;
@@ -297,19 +247,12 @@ export function createRig() {
const overstretched =
Math.hypot(foot.x - hip.x, foot.y - hip.y) > reachOf(i) * 0.97;
if (overstretched || at(error, i) > threshold * 3.2) {
- startStep(i, at(targets, i), surface, speed);
+ startStep(i, at(targets, i), speed);
airborne++;
}
});
},
- /** Lift one leg and set it down again a little elsewhere: idle fussing. */
- fidget(i: number, body: Body, surface: Surface, nudge: Vec) {
- if (at(feet, i).stepping) return;
- const p = restAt(body, i);
- startStep(i, { x: p.x + nudge.x, y: p.y + nudge.y }, surface, 0, 0.22);
- },
-
stepping() {
return feet.some((foot) => foot.stepping);
},
@@ -349,7 +292,7 @@ export function createRig() {
outward
);
// The metatarsus comes down from the raised knee; near the foot the
- // tarsus hooks onto the thread, a small bend just short of the end.
+ // tarsus bends a little, just short of the end.
const ankle = {
x: knee.x + (end.x - knee.x) * 0.74 + outwardSide.x * height * 0.08,
y: knee.y + (end.y - knee.y) * 0.74 + outwardSide.y * height * 0.08
diff --git a/packages/react/src/Halloween/toasts.ts b/packages/react/src/Halloween/toasts.ts
new file mode 100644
index 0000000000..2f24c4a169
--- /dev/null
+++ b/packages/react/src/Halloween/toasts.ts
@@ -0,0 +1,38 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// Watches for a toast of one type appearing (sonner 2: each toast is an
+// `li[data-sonner-toast][data-type]` inside an `ol[data-sonner-toaster]`,
+// and the list itself is only mounted while it holds a toast). The observer
+// covers the whole page, so every other change is turned away by one
+// `matches` on the record's target or on what was added to it.
+
+const TOASTER = "[data-sonner-toaster]";
+
+export function onToast(
+ type: "success" | "error",
+ callback: (toast: Element) => void
+) {
+ const selector = `[data-sonner-toast][data-type="${type}"]`;
+ const observer = new MutationObserver((records) => {
+ for (const record of records) {
+ const inToaster =
+ record.target instanceof Element && record.target.matches(TOASTER);
+ for (const node of Array.from(record.addedNodes)) {
+ if (!(node instanceof Element)) continue;
+ // A toast added to a list already showing, or a new list with it.
+ const toast = inToaster
+ ? node.matches(selector)
+ ? node
+ : null
+ : node.matches(TOASTER)
+ ? node.querySelector(selector)
+ : null;
+ if (toast) callback(toast);
+ }
+ }
+ });
+ observer.observe(document.body, { childList: true, subtree: true });
+ return () => observer.disconnect();
+}