diff --git a/src/lib/shimejic/core/----------OLDanimation.ts b/src/lib/shimejic/core/----------OLDanimation.ts deleted file mode 100644 index e3b748c..0000000 --- a/src/lib/shimejic/core/----------OLDanimation.ts +++ /dev/null @@ -1,89 +0,0 @@ -/** - * animation.ts — frame sequencing for animated sprites. - * - * Owns: a clip (list of frames + fps + loop mode) and the elapsed time - * inside it. Does not own: what a "walk" is, which clip should be playing, - * or anything about drawing. - * - * The output — `frame` — is a CanvasImageSource, which plugs directly - * into the renderer's `SpriteDraw.image` field with no conversion. - */ - -export interface AnimationClip { - /** Ordered frames. Any CanvasImageSource: HTMLImageElement, ImageBitmap, canvas, … */ - frames: CanvasImageSource[]; - /** Playback rate in frames per second. */ - fps: number; - /** Default true. When false, holds the last frame after one pass. */ - loop?: boolean; -} - -export class Animator { - private clip: AnimationClip | null = null; - private elapsed = 0; - private finished = false; - private active = false; - - /** Begin playing a clip. If it's already the current clip, this is a no-op. */ - play(clip: AnimationClip | null): void { - if (clip === this.clip) return; - this.clip = clip; - this.elapsed = 0; - this.finished = false; - this.active = clip !== null && clip.frames.length > 0; - } - - /** Force a restart of the current clip. */ - restart(): void { - if (!this.clip) return; - this.elapsed = 0; - this.finished = false; - this.active = this.clip.frames.length > 0; - } - - stop(): void { - this.active = false; - } - - /** Advance by `dt` seconds. */ - update(dt: number): void { - if (!this.active || !this.clip || this.finished) return; - - this.elapsed += dt; - - if (!this.clip.loop) { - const duration = this.clip.frames.length / this.clip.fps; - if (this.elapsed >= duration) { - this.elapsed = duration; - this.finished = true; - } - } - } - - /** Current frame image, or null if no clip is playing. */ - get frame(): CanvasImageSource | null { - if (!this.clip || !this.clip.frames.length) return null; - return this.clip.frames[this.frameIndex]; - } - - /** Current frame index within the clip. */ - get frameIndex(): number { - if (!this.clip || !this.clip.frames.length) return 0; - const raw = Math.floor(this.elapsed * this.clip.fps); - return this.clip.loop ? raw % this.clip.frames.length : Math.min(raw, this.clip.frames.length - 1); - } - - /** True when a non-looping clip has reached its final frame. */ - get done(): boolean { - return this.finished; - } - - /** Time elapsed in the current clip, seconds. */ - get time(): number { - return this.elapsed; - } - - get currentClip(): AnimationClip | null { - return this.clip; - } -} diff --git a/src/lib/shimejic/core/----------OLDassets.ts b/src/lib/shimejic/core/----------OLDassets.ts deleted file mode 100644 index 0edd962..0000000 --- a/src/lib/shimejic/core/----------OLDassets.ts +++ /dev/null @@ -1,34 +0,0 @@ -export class ImageCache { - private images = new Map(); - - async load(urls: string[]): Promise { - const results = await Promise.all( - urls.map( - url => - new Promise<[string, HTMLImageElement]>((resolve, reject) => { - const img = new Image(); - img.onload = () => resolve([url, img]); - img.onerror = () => reject(new Error(`Could not load "${url}"`)); - img.src = url; - }), - ), - ); - this.images = new Map(results); - } - - get(url: string): HTMLImageElement | undefined { - return this.images.get(url); - } - - largestSize(urls: string[]): { w: number; h: number } { - let w = 0; - let h = 0; - for (const url of urls) { - const img = this.images.get(url); - if (!img) continue; - w = Math.max(w, img.naturalWidth); - h = Math.max(h, img.naturalHeight); - } - return { w, h }; - } -} diff --git a/src/lib/shimejic/core/----------OLDphysics.ts b/src/lib/shimejic/core/----------OLDphysics.ts deleted file mode 100644 index 1c5168c..0000000 --- a/src/lib/shimejic/core/----------OLDphysics.ts +++ /dev/null @@ -1,300 +0,0 @@ -export interface Vec2 { - x: number; - y: number; -} - -export interface RigidBodyConfig { - /** Top-left corner position, px. */ - position: Vec2; - /** Width in px. */ - width: number; - /** Height in px. */ - height: number; - /** Default 1. Use 0 for a static body. */ - mass?: number; - /** Bounciness, 0–1. 0 = no bounce, 1 = perfectly elastic. Default 0.4. */ - restitution?: number; - /** Coulomb friction coefficient. Default 0.3. */ - friction?: number; - /** Air resistance as fraction of velocity lost per second. Default 0. */ - linearDamping?: number; -} - -export class RigidBody { - /* --- kinematics --- */ - position: Vec2; - velocity: Vec2; - /** Force accumulator. Cleared at the end of every substep. */ - force: Vec2 = { x: 0, y: 0 }; - - /* --- shape --- */ - width: number; - height: number; - - /* --- material --- */ - mass: number; - inverseMass: number; - restitution: number; - friction: number; - linearDamping: number; - - /* --- contacts (per-substep; reset at the start of each substep) --- */ - onGround = false; - onCeiling = false; - onLeftWall = false; - onRightWall = false; - - constructor(config: RigidBodyConfig) { - this.position = { ...config.position }; - this.velocity = { x: 0, y: 0 }; - this.width = config.width; - this.height = config.height; - this.mass = config.mass ?? 1; - this.inverseMass = this.mass > 0 ? 1 / this.mass : 0; - this.restitution = config.restitution ?? 0.4; - this.friction = config.friction ?? 0.3; - this.linearDamping = config.linearDamping ?? 0; - } - - /* --- geometry --- */ - get left(): number { - return this.position.x; - } - get right(): number { - return this.position.x + this.width; - } - get top(): number { - return this.position.y; - } - get bottom(): number { - return this.position.y + this.height; - } - get centerX(): number { - return this.position.x + this.width / 2; - } - get centerY(): number { - return this.position.y + this.height / 2; - } - - /* --- force application --- */ - - /** - * Add a continuous force (N). Accumulates until the next substep, when - * it's converted to acceleration via `a = F/m` and then cleared. - * Apply every frame for a sustained push (wind, thrust). - */ - applyForce(f: Vec2): void { - this.force.x += f.x; - this.force.y += f.y; - } - - /** - * Add an instantaneous velocity change (kg·px/s). Applied immediately. - * Use for one-shot pushes: throws, hits, explosions. - */ - applyImpulse(i: Vec2): void { - this.velocity.x += i.x * this.inverseMass; - this.velocity.y += i.y * this.inverseMass; - } - - /** Overwrite velocity directly. No mass scaling. */ - setVelocity(v: Vec2): void { - this.velocity.x = v.x; - this.velocity.y = v.y; - } - - /** Clear the force accumulator. Called by the world after each substep. */ - clearForces(): void { - this.force.x = 0; - this.force.y = 0; - } -} - -/* ------------------------------------------------------------------ */ -/* World */ -/* ------------------------------------------------------------------ */ - -export interface PhysicsSolverConfig { - /** Playfield width, px. */ - width: number; - /** Playfield height, px. */ - height: number; - /** Thickness of the floor strip at the bottom, px. Default 0. */ - floorHeight?: number; - /** Constant acceleration applied to every body. Default {0, 1500}. */ - gravity?: Vec2; - /** Physics tick length in seconds. Default 1/120. */ - fixedDt?: number; - /** Max substeps per `step()` call. Default 8. */ - maxSubsteps?: number; - /** Vertical speed below which a ground contact is treated as resting, px/s. Default 40. */ - restVelocityThreshold?: number; -} - -export class PhysicsSolver { - gravity: Vec2; - width: number; - height: number; - - rbArray: RigidBody[] = []; - - readonly fixedDt: number; - readonly maxSubsteps: number; - readonly restVelocityThreshold: number; - - private dtAccumulator = 0; - - constructor(config: PhysicsSolverConfig) { - this.gravity = config.gravity ?? { x: 0, y: 1500 }; - this.width = config.width; - this.height = config.height; - this.fixedDt = config.fixedDt ?? 1 / 120; - this.maxSubsteps = config.maxSubsteps ?? 8; - this.restVelocityThreshold = config.restVelocityThreshold ?? 40; - } - - resize(width: number, height: number, floorHeight?: number): void { - this.width = width; - this.height = height; - for (const b of this.rbArray) { - b.position.x = clamp(b.position.x, 0, this.width - b.width); - } - } - - addBody(rb: RigidBody): RigidBody { - this.rbArray.push(rb); - return rb; - } - - removeBody(rb: RigidBody): void { - const i = this.rbArray.indexOf(rb); - if (i >= 0) this.rbArray.splice(i, 1); - } - - /* -------------------------------------------------------------- */ - - /** - * Advance the simulation by `dt` seconds of real time. - * Consumes from an accumulator and runs as many fixed substeps as fit. - */ - step(dt: number): void { - this.dtAccumulator += dt; - - let substeps = 0; - while (this.dtAccumulator >= this.fixedDt && substeps < this.maxSubsteps) { - this.fixedStep(this.fixedDt); - this.dtAccumulator -= this.fixedDt; - substeps++; - } - - // If we hit the cap, drop the backlog rather than spiral. - if (substeps >= this.maxSubsteps) this.dtAccumulator = 0; - } - - /** - * Run exactly one fixed substep, ignoring the accumulator. - * For deterministic tests and headless simulation. - */ - stepOnce(): void { - this.fixedStep(this.fixedDt); - } - - /* -------------------------------------------------------------- */ - - private fixedStep(dt: number): void { - for (const rb of this.rbArray) { - rb.onGround = false; - rb.onCeiling = false; - rb.onLeftWall = false; - rb.onRightWall = false; - - this.integrate(rb, dt); - this.resolveWorldCollisions(rb, dt); - } - } - - private integrate(rb: RigidBody, dt: number): void { - if (rb.inverseMass === 0) return; - - // Gravity as a force: F = m·g - rb.force.x += this.gravity.x * rb.mass; - rb.force.y += this.gravity.y * rb.mass; - - // F = m·a → a = F/m. Then v += a·dt. - rb.velocity.x += rb.force.x * rb.inverseMass * dt; - rb.velocity.y += rb.force.y * rb.inverseMass * dt; - - // Linear damping: fraction of velocity lost per second. - if (rb.linearDamping > 0) { - const retain = Math.pow(1 - rb.linearDamping, dt); - rb.velocity.x *= retain; - rb.velocity.y *= retain; - } - - // Integrate position from the *new* velocity (semi-implicit Euler). - rb.position.x += rb.velocity.x * dt; - rb.position.y += rb.velocity.y * dt; - - rb.clearForces(); - } - - private resolveWorldCollisions(rb: RigidBody, dt: number): void { - if (rb.position.y > this.height - rb.height * 0.5) { - rb.position.y = this.height - rb.height * 0.5; - rb.onGround = true; - - if (rb.velocity.y > 0) { - if (rb.velocity.y < this.restVelocityThreshold) { - // Too slow to bounce meaningfully — rest. - rb.velocity.y = 0; - } else { - rb.velocity.y = -rb.velocity.y * rb.restitution; - } - } - - // Coulomb friction: decelerate by μ·g each second while touching. - if (rb.friction > 0 && Math.abs(rb.velocity.x) > 0) { - const pressureForce = rb.friction * Math.abs(this.gravity.y); - const dv = pressureForce * dt; - if (Math.abs(rb.velocity.x) <= dv) { - rb.velocity.x = 0; - } else { - rb.velocity.x -= Math.sign(rb.velocity.x) * dv; - } - } - } - - /* --- ceiling --- */ - if (rb.top < 0) { - rb.position.y = 0; - rb.onCeiling = true; - if (rb.velocity.y < 0) { - rb.velocity.y = -rb.velocity.y * rb.restitution; - } - } - - /* --- left wall --- */ - if (rb.left < 0) { - rb.position.x = 0; - rb.onLeftWall = true; - if (rb.velocity.x < 0) { - rb.velocity.x = -rb.velocity.x * rb.restitution; - } - } - - /* --- right wall --- */ - if (rb.right > this.width) { - rb.position.x = this.width - rb.width; - rb.onRightWall = true; - if (rb.velocity.x > 0) { - rb.velocity.x = -rb.velocity.x * rb.restitution; - } - } - } -} - -/* ------------------------------------------------------------------ */ - -export function clamp(v: number, lo: number, hi: number): number { - return Math.min(Math.max(v, lo), hi); -} diff --git a/src/lib/shimejic/core/----------OLDrenderer.ts b/src/lib/shimejic/core/----------OLDrenderer.ts deleted file mode 100644 index 18c9334..0000000 --- a/src/lib/shimejic/core/----------OLDrenderer.ts +++ /dev/null @@ -1,423 +0,0 @@ -/** - * renderer.ts — standalone 2D canvas renderer. - * - * Knows nothing about what it's drawing. Takes a data description of a - * frame and paints it. Owns: - * - the canvas and its DPI scaling - * - a scratch canvas for reflection compositing - * - pixel-art crispness (imageSmoothingEnabled, integer rounding) - * - * Does not own: - * - the animation loop (caller calls `render()` per frame) - * - resize detection (caller calls `resize()` explicitly) - * - any game concept (states, needs, physics, interactions) - * - * All coordinates and sizes are in CSS pixels. DPI is handled internally. - */ - -/* ------------------------------------------------------------------ */ -/* Types */ -/* ------------------------------------------------------------------ */ - -export type Anchor = - | "top-left" - | "top-center" - | "top-right" - | "center-left" - | "center" - | "center-right" - | "bottom-left" - | "bottom-center" - | "bottom-right"; - -export interface RendererConfig { - canvas: HTMLCanvasElement; - /** Disable image smoothing and round positions. Default true. */ - pixelArt?: boolean; - /** Cap on devicePixelRatio. Prevents 4x canvases on exotic displays. Default 3. */ - maxDpr?: number; - /** Fill colour applied after clear. Default null (transparent). */ - backgroundColor?: string | null; -} - -export interface SpriteDraw { - image: CanvasImageSource; - /** Anchor position in CSS px. What (x, y) refers to depends on `anchor`. */ - x: number; - y: number; - /** Display size in CSS px. */ - width: number; - height: number; - /** Default 'top-left'. */ - anchor?: Anchor; - /** Flip horizontally. Default false. */ - mirrored?: boolean; - /** Overall opacity 0–1. Default 1. */ - alpha?: number; - /** Additional x scale applied about the anchor. 1 = normal. */ - scaleX?: number; - /** Additional y scale applied about the anchor. 1 = normal. */ - scaleY?: number; -} - -export interface ShadowDraw { - /** Ellipse centre in CSS px. */ - cx: number; - cy: number; - /** Ellipse radii in CSS px. */ - rx: number; - ry: number; - color?: string; - alpha?: number; -} - -export interface ReflectionDraw { - image: CanvasImageSource; - x: number; - y: number; - width: number; - height: number; - anchor?: Anchor; - mirrored?: boolean; - alpha?: number; - /** Fade toward the far edge, 0–1. 0 = no fade, 1 = fully faded. Default 0. */ - fade?: number; - /** Colour wash applied via `source-atop`. */ - tint?: string; - /** Which way the reflection fades. Default 'down'. */ - fadeDirection?: "down" | "up"; -} - -export interface TextDraw { - content: string; - /** Text area in CSS px. */ - x: number; - y: number; - width: number; - height: number; - /** Full CSS font string, e.g. "12px monospace". */ - font?: string; - color?: string; - align?: "left" | "center" | "right"; - /** Anchor for the text block within the rect. Default 'top'. */ - baseline?: "top" | "middle" | "bottom"; - /** Multiplier over font size. Default 1.2. */ - lineHeight?: number; - /** Word-wrap to `width`. Default true. */ - wrap?: boolean; - /** Typewriter reveal: characters 0..charsShown visible. Default Infinity. */ - charsShown?: number; -} - -/** - * A complete frame description. The renderer draws slots in a fixed order: - * shadow → reflection → sprite → bubble → text - * Any slot may be omitted. - */ -export interface RenderFrame { - shadow?: ShadowDraw; - reflection?: ReflectionDraw; - sprite?: SpriteDraw; - bubble?: SpriteDraw; - text?: TextDraw; -} - -/* ------------------------------------------------------------------ */ -/* Helpers */ -/* ------------------------------------------------------------------ */ - -/** - * Offset from the anchor point to the image's top-left corner. - * Use this to compute hit-test rectangles that match what the renderer drew. - */ -export function anchorOffset(anchor: Anchor, w: number, h: number): { ox: number; oy: number } { - const hx = anchor.includes("left") ? 0 : anchor.includes("right") ? -w : -w / 2; - const hy = anchor.startsWith("top") ? 0 : anchor.startsWith("bottom") ? -h : -h / 2; - return { ox: hx, oy: hy }; -} - -function parseFontSize(font?: string): number { - if (!font) return 11; - const m = /(\d+(?:\.\d+)?)px/.exec(font); - return m ? parseFloat(m[1]) : 11; -} - -function wrapText(ctx: CanvasRenderingContext2D, text: string, maxWidth: number): string[] { - const words = text.split(/\s+/).filter(Boolean); - const lines: string[] = []; - let line = ""; - for (const word of words) { - const candidate = line ? `${line} ${word}` : word; - if (ctx.measureText(candidate).width <= maxWidth) { - line = candidate; - } else { - if (line) lines.push(line); - line = word; - } - } - if (line) lines.push(line); - return lines; -} - -/* ------------------------------------------------------------------ */ -/* Renderer */ -/* ------------------------------------------------------------------ */ - -export class Renderer { - readonly canvas: HTMLCanvasElement; - /** Exposed for escape-hatch drawing. Reset on every resize. */ - readonly ctx: CanvasRenderingContext2D; - - private pixelArt: boolean; - private maxDpr: number; - private backgroundColor: string | null; - - private dpr = 1; - private cssW = 0; - private cssH = 0; - - // Scratch canvas for reflection compositing. - private reflCanvas: HTMLCanvasElement; - private reflCtx: CanvasRenderingContext2D; - private reflW = 0; - private reflH = 0; - - constructor(cfg: RendererConfig) { - this.canvas = cfg.canvas; - const ctx = this.canvas.getContext("2d"); - if (!ctx) throw new Error("Renderer: could not acquire 2D context"); - this.ctx = ctx; - - this.pixelArt = cfg.pixelArt ?? true; - this.maxDpr = cfg.maxDpr ?? 3; - this.backgroundColor = cfg.backgroundColor ?? null; - - this.reflCanvas = document.createElement("canvas"); - const rctx = this.reflCanvas.getContext("2d"); - if (!rctx) throw new Error("Renderer: could not acquire reflection context"); - this.reflCtx = rctx; - } - - /* -------------------------------------------------------------- */ - /* Sizing */ - /* -------------------------------------------------------------- */ - - /** - * Sync the canvas backing store to its displayed size. - * Safe to call every frame — early-returns if nothing changed. - * Handles dpr changes when the window moves between displays. - */ - resize(cssW: number, cssH: number): void { - const w = Math.max(1, cssW); - const h = Math.max(1, cssH); - const newDpr = Math.min(typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1, this.maxDpr); - - if (w === this.cssW && h === this.cssH && newDpr === this.dpr) return; - - this.cssW = w; - this.cssH = h; - this.dpr = newDpr; - - this.canvas.width = Math.round(w * newDpr); - this.canvas.height = Math.round(h * newDpr); - this.ctx.setTransform(newDpr, 0, 0, newDpr, 0, 0); - this.ctx.imageSmoothingEnabled = !this.pixelArt; - } - - get size(): { width: number; height: number; dpr: number } { - return { width: this.cssW, height: this.cssH, dpr: this.dpr }; - } - - /* -------------------------------------------------------------- */ - /* Frame */ - /* -------------------------------------------------------------- */ - - - render(frame: RenderFrame): void { - this.clear(); - if (frame.shadow) this.drawShadow(frame.shadow); - if (frame.reflection) this.drawReflection(frame.reflection); - if (frame.sprite) this.drawSprite(frame.sprite); - if (frame.bubble) this.drawSprite(frame.bubble); - if (frame.text) this.drawText(frame.text); - } - - /** Clear the canvas. Fills with `backgroundColor` if set. */ - clear(): void { - this.ctx.clearRect(0, 0, this.cssW, this.cssH); - if (this.backgroundColor) { - this.ctx.fillStyle = this.backgroundColor; - this.ctx.fillRect(0, 0, this.cssW, this.cssH); - } - } - - /* -------------------------------------------------------------- */ - /* Primitives */ - /* -------------------------------------------------------------- */ - - /** Draw a filled ellipse. Used for contact shadows. */ - drawShadow(s: ShadowDraw): void { - const { ctx } = this; - const alpha = s.alpha ?? 0.3; - if (alpha <= 0) return; - - ctx.save(); - ctx.globalAlpha = alpha; - ctx.fillStyle = s.color ?? "#000"; - ctx.beginPath(); - ctx.ellipse(s.cx, s.cy, s.rx, s.ry, 0, 0, Math.PI * 2); - ctx.fill(); - ctx.restore(); - } - - /** Draw an image with anchor, mirroring, and about-anchor scaling. */ - drawSprite(d: SpriteDraw): void { - const { ctx } = this; - const alpha = d.alpha ?? 1; - if (alpha <= 0) return; - - const { ox, oy } = anchorOffset(d.anchor ?? "top-left", d.width, d.height); - const ax = this.round(d.x); - const ay = this.round(d.y); - - const sx = (d.mirrored ? -1 : 1) * (d.scaleX ?? 1); - const sy = d.scaleY ?? 1; - - ctx.save(); - ctx.globalAlpha = alpha; - - if (sx !== 1 || sy !== 1) { - // Scale about the anchor point so squash keeps the feet planted. - ctx.translate(ax, ay); - ctx.scale(sx, sy); - ctx.drawImage(d.image, ox, oy, d.width, d.height); - } else { - ctx.drawImage(d.image, ax + ox, ay + oy, d.width, d.height); - } - - ctx.restore(); - } - - /** - * Draw a mirrored reflection. Composited via an offscreen scratch canvas - * so tint and fade can be applied as compound operations, then drawn to - * the main canvas in one pass. - */ - drawReflection(r: ReflectionDraw): void { - const alpha = r.alpha ?? 1; - if (alpha <= 0.01) return; - - const pw = Math.max(1, Math.round(r.width * this.dpr)); - const ph = Math.max(1, Math.round(r.height * this.dpr)); - - if (this.reflW !== pw || this.reflH !== ph) { - this.reflCanvas.width = pw; - this.reflCanvas.height = ph; - this.reflW = pw; - this.reflH = ph; - } - - const rc = this.reflCtx; - rc.setTransform(1, 0, 0, 1, 0, 0); - rc.globalCompositeOperation = "source-over"; - rc.globalAlpha = 1; - rc.clearRect(0, 0, pw, ph); - rc.imageSmoothingEnabled = !this.pixelArt; - - // 1. Draw the image, flipped vertically (and horizontally if mirrored). - rc.save(); - rc.translate(r.mirrored ? pw : 0, ph); - rc.scale(r.mirrored ? -1 : 1, -1); - rc.drawImage(r.image, 0, 0, pw, ph); - rc.restore(); - - // 2. Colour wash — only paints over pixels that exist. - if (r.tint) { - rc.globalCompositeOperation = "source-atop"; - rc.fillStyle = r.tint; - rc.fillRect(0, 0, pw, ph); - } - - // 3. Fade — erases pixels progressively toward the far edge. - const fade = Math.min(Math.max(r.fade ?? 0, 0), 1); - if (fade > 0) { - rc.globalCompositeOperation = "destination-out"; - const grad = rc.createLinearGradient(0, 0, 0, ph); - const topA = r.fadeDirection === "up" ? fade : 0; - const botA = r.fadeDirection === "up" ? 0 : fade; - grad.addColorStop(0, `rgba(0,0,0,${topA})`); - grad.addColorStop(1, `rgba(0,0,0,${botA})`); - rc.fillStyle = grad; - rc.fillRect(0, 0, pw, ph); - } - rc.globalCompositeOperation = "source-over"; - - // 4. Composite to the main canvas at device-aligned position. - const { ox, oy } = anchorOffset(r.anchor ?? "top-left", r.width, r.height); - const x = this.round(r.x) + ox; - const y = this.round(r.y) + oy; - - const ctx = this.ctx; - ctx.save(); - ctx.globalAlpha = alpha; - ctx.drawImage(this.reflCanvas, x, y, r.width, r.height); - ctx.restore(); - } - - /** - * Draw text within a rect. Optional word-wrap and typewriter reveal. - * Reveal is cumulative across wrapped lines, so "hello world" with - * charsShown = 7 shows "hello w" with nothing on the second line. - */ - drawText(t: TextDraw): void { - if (!t.content) return; - - const { ctx } = this; - const fontSize = parseFontSize(t.font); - const lineHeight = (t.lineHeight ?? 1.2) * fontSize; - const align = t.align ?? "center"; - const baseline = t.baseline ?? "top"; - const charsShown = t.charsShown ?? Infinity; - - ctx.save(); - ctx.font = t.font ?? "11px monospace"; - ctx.fillStyle = t.color ?? "#000"; - ctx.textBaseline = baseline === "middle" ? "middle" : baseline; - ctx.textAlign = align; - - const lines = t.wrap === false ? [t.content] : wrapText(ctx, t.content, t.width); - - // Horizontal anchor for textAlign. - const anchorX = align === "left" ? t.x : align === "right" ? t.x + t.width : t.x + t.width / 2; - - // Vertical anchor for the text block. - const baseY = baseline === "top" ? t.y : baseline === "bottom" ? t.y + t.height : t.y + t.height / 2; - - let cursor = 0; - for (let i = 0; i < lines.length; i++) { - const line = lines[i]; - const visible = Math.max(0, Math.min(line.length, charsShown - cursor)); - if (visible <= 0) break; - - const yy = - baseline === "top" - ? baseY + i * lineHeight - : baseline === "bottom" - ? baseY - (lines.length - 1 - i) * lineHeight - : baseY - ((lines.length - 1) / 2 - i) * lineHeight; - - ctx.fillText(line.slice(0, visible), anchorX, yy); - - cursor += line.length; - if (visible < line.length) break; - } - - ctx.restore(); - } - - /* -------------------------------------------------------------- */ - - private round(v: number): number { - return this.pixelArt ? Math.round(v) : v; - } -}