diff --git a/package-lock.json b/package-lock.json index f1d1f67..a8a3b7e 100755 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "version": "0.0.69", "dependencies": { "@lucide/svelte": "^0.548.0", + "animejs": "^4.5.0", "gl-matrix": "^3.4.4", "zod": "^4.3.6" }, @@ -2189,6 +2190,28 @@ "url": "https://github.com/sponsors/epoberezkin" } }, + "node_modules/animejs": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/animejs/-/animejs-4.5.0.tgz", + "integrity": "sha512-NQimYX+lz8WaXonGS9zVVoviCIAjONeJayxacUditaivYLqyXgGjFKjuyl0aUUhFKm5MriX9ty1TGovNzoJQWA==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/juliangarnier" + }, + "peerDependencies": { + "@types/three": ">=0.150.0", + "three": ">=0.150.0" + }, + "peerDependenciesMeta": { + "@types/three": { + "optional": true + }, + "three": { + "optional": true + } + } + }, "node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", diff --git a/package.json b/package.json index e3e443e..757274f 100755 --- a/package.json +++ b/package.json @@ -52,6 +52,7 @@ }, "dependencies": { "@lucide/svelte": "^0.548.0", + "animejs": "^4.5.0", "gl-matrix": "^3.4.4", "zod": "^4.3.6" } diff --git a/src/lib/assets/character/bubbles/bubble_1.png b/src/lib/assets/character/bubbles/bubble_1.png new file mode 100644 index 0000000..095a5d0 Binary files /dev/null and b/src/lib/assets/character/bubbles/bubble_1.png differ diff --git a/src/lib/assets/character/bubbles/bubble_2.png b/src/lib/assets/character/bubbles/bubble_2.png new file mode 100644 index 0000000..095a5d0 Binary files /dev/null and b/src/lib/assets/character/bubbles/bubble_2.png differ diff --git a/src/lib/assets/character/bubbles/chatter/bubble_1.png b/src/lib/assets/character/bubbles/chatter/bubble_1.png new file mode 100644 index 0000000..095a5d0 Binary files /dev/null and b/src/lib/assets/character/bubbles/chatter/bubble_1.png differ diff --git a/src/lib/assets/character/bubbles/sleepy/sleepy_1.png b/src/lib/assets/character/bubbles/sleepy/sleepy_1.png new file mode 100644 index 0000000..177f1b5 Binary files /dev/null and b/src/lib/assets/character/bubbles/sleepy/sleepy_1.png differ diff --git a/src/lib/assets/character/sounds/sleepy/yawn.mp3 b/src/lib/assets/character/sounds/sleepy/yawn.mp3 new file mode 100644 index 0000000..cde39f0 Binary files /dev/null and b/src/lib/assets/character/sounds/sleepy/yawn.mp3 differ diff --git a/src/lib/assets/character/states/falling/falling.png b/src/lib/assets/character/states/falling/falling.png new file mode 100644 index 0000000..72c278d Binary files /dev/null and b/src/lib/assets/character/states/falling/falling.png differ diff --git a/src/lib/assets/character/states/held/held.png b/src/lib/assets/character/states/held/held.png new file mode 100644 index 0000000..34927a0 Binary files /dev/null and b/src/lib/assets/character/states/held/held.png differ diff --git a/src/lib/assets/character/states/idle/idle_1.png b/src/lib/assets/character/states/idle/idle_1.png new file mode 100644 index 0000000..48efeb3 Binary files /dev/null and b/src/lib/assets/character/states/idle/idle_1.png differ diff --git a/src/lib/assets/character/states/idle/idle_2.png b/src/lib/assets/character/states/idle/idle_2.png new file mode 100644 index 0000000..dbe86c0 Binary files /dev/null and b/src/lib/assets/character/states/idle/idle_2.png differ diff --git a/src/lib/assets/character/states/idle/idle_3.png b/src/lib/assets/character/states/idle/idle_3.png new file mode 100644 index 0000000..cf92cd8 Binary files /dev/null and b/src/lib/assets/character/states/idle/idle_3.png differ diff --git a/src/lib/assets/character/states/idle/idle_4.png b/src/lib/assets/character/states/idle/idle_4.png new file mode 100644 index 0000000..d6ea234 Binary files /dev/null and b/src/lib/assets/character/states/idle/idle_4.png differ diff --git a/src/lib/assets/character/states/idle/idle_5.png b/src/lib/assets/character/states/idle/idle_5.png new file mode 100644 index 0000000..e657dd0 Binary files /dev/null and b/src/lib/assets/character/states/idle/idle_5.png differ diff --git a/src/lib/assets/character/states/idle/idle_6.png b/src/lib/assets/character/states/idle/idle_6.png new file mode 100644 index 0000000..75973e1 Binary files /dev/null and b/src/lib/assets/character/states/idle/idle_6.png differ diff --git a/src/lib/assets/character/states/idle/idle_7.png b/src/lib/assets/character/states/idle/idle_7.png new file mode 100644 index 0000000..e013109 Binary files /dev/null and b/src/lib/assets/character/states/idle/idle_7.png differ diff --git a/src/lib/assets/character/states/idle/idle_8.png b/src/lib/assets/character/states/idle/idle_8.png new file mode 100644 index 0000000..ec9bfd4 Binary files /dev/null and b/src/lib/assets/character/states/idle/idle_8.png differ diff --git a/src/lib/assets/character/states/sleep/sleep_2.png b/src/lib/assets/character/states/sleep/sleep_2.png new file mode 100644 index 0000000..d113afa Binary files /dev/null and b/src/lib/assets/character/states/sleep/sleep_2.png differ diff --git a/src/lib/assets/character/states/sleep/sleep_3.png b/src/lib/assets/character/states/sleep/sleep_3.png new file mode 100644 index 0000000..a80034b Binary files /dev/null and b/src/lib/assets/character/states/sleep/sleep_3.png differ diff --git a/src/lib/assets/character/states/sleep/sleep_4.png b/src/lib/assets/character/states/sleep/sleep_4.png new file mode 100644 index 0000000..0b8fbca Binary files /dev/null and b/src/lib/assets/character/states/sleep/sleep_4.png differ diff --git a/src/lib/assets/character/states/sleep/sleep_5.png b/src/lib/assets/character/states/sleep/sleep_5.png new file mode 100644 index 0000000..03f7ff2 Binary files /dev/null and b/src/lib/assets/character/states/sleep/sleep_5.png differ diff --git a/src/lib/assets/character/states/sleep/sleep_6.png b/src/lib/assets/character/states/sleep/sleep_6.png new file mode 100644 index 0000000..96c0340 Binary files /dev/null and b/src/lib/assets/character/states/sleep/sleep_6.png differ diff --git a/src/lib/assets/character/states/sleep/sleep_7.png b/src/lib/assets/character/states/sleep/sleep_7.png new file mode 100644 index 0000000..ae85ddd Binary files /dev/null and b/src/lib/assets/character/states/sleep/sleep_7.png differ diff --git a/src/lib/assets/character/states/sleep/sleep_8.png b/src/lib/assets/character/states/sleep/sleep_8.png new file mode 100644 index 0000000..f07130e Binary files /dev/null and b/src/lib/assets/character/states/sleep/sleep_8.png differ diff --git a/src/lib/assets/character/states/walk/walk_1.png b/src/lib/assets/character/states/walk/walk_1.png new file mode 100644 index 0000000..9b32e3a Binary files /dev/null and b/src/lib/assets/character/states/walk/walk_1.png differ diff --git a/src/lib/assets/character/states/walk/walk_10.png b/src/lib/assets/character/states/walk/walk_10.png new file mode 100644 index 0000000..008d961 Binary files /dev/null and b/src/lib/assets/character/states/walk/walk_10.png differ diff --git a/src/lib/assets/character/states/walk/walk_11.png b/src/lib/assets/character/states/walk/walk_11.png new file mode 100644 index 0000000..8ba98b5 Binary files /dev/null and b/src/lib/assets/character/states/walk/walk_11.png differ diff --git a/src/lib/assets/character/states/walk/walk_12.png b/src/lib/assets/character/states/walk/walk_12.png new file mode 100644 index 0000000..c8edd4c Binary files /dev/null and b/src/lib/assets/character/states/walk/walk_12.png differ diff --git a/src/lib/assets/character/states/walk/walk_2.png b/src/lib/assets/character/states/walk/walk_2.png new file mode 100644 index 0000000..9352bef Binary files /dev/null and b/src/lib/assets/character/states/walk/walk_2.png differ diff --git a/src/lib/assets/character/states/walk/walk_3.png b/src/lib/assets/character/states/walk/walk_3.png new file mode 100644 index 0000000..bc1c79c Binary files /dev/null and b/src/lib/assets/character/states/walk/walk_3.png differ diff --git a/src/lib/assets/character/states/walk/walk_4.png b/src/lib/assets/character/states/walk/walk_4.png new file mode 100644 index 0000000..ec79c9b Binary files /dev/null and b/src/lib/assets/character/states/walk/walk_4.png differ diff --git a/src/lib/assets/character/states/walk/walk_5.png b/src/lib/assets/character/states/walk/walk_5.png new file mode 100644 index 0000000..abf1a7d Binary files /dev/null and b/src/lib/assets/character/states/walk/walk_5.png differ diff --git a/src/lib/assets/character/states/walk/walk_6.png b/src/lib/assets/character/states/walk/walk_6.png new file mode 100644 index 0000000..46ef574 Binary files /dev/null and b/src/lib/assets/character/states/walk/walk_6.png differ diff --git a/src/lib/assets/character/states/walk/walk_7.png b/src/lib/assets/character/states/walk/walk_7.png new file mode 100644 index 0000000..1b3355f Binary files /dev/null and b/src/lib/assets/character/states/walk/walk_7.png differ diff --git a/src/lib/assets/character/states/walk/walk_8.png b/src/lib/assets/character/states/walk/walk_8.png new file mode 100644 index 0000000..22b447e Binary files /dev/null and b/src/lib/assets/character/states/walk/walk_8.png differ diff --git a/src/lib/assets/character/states/walk/walk_9.png b/src/lib/assets/character/states/walk/walk_9.png new file mode 100644 index 0000000..664d393 Binary files /dev/null and b/src/lib/assets/character/states/walk/walk_9.png differ diff --git a/src/lib/mwinlib/mwin_controller.svelte.ts b/src/lib/mwinlib/mwin_controller.svelte.ts new file mode 100644 index 0000000..d133550 --- /dev/null +++ b/src/lib/mwinlib/mwin_controller.svelte.ts @@ -0,0 +1,573 @@ +import { + getWrapperManager, + MWIN_MANAGER, + resolveElement, + type MWinAPI, + type MWinNormalizedParams, + type MWinParams, + type MWinState, + type ResizeDirection +} from './mwin_util'; + +export function mwin_movable(node: HTMLElement, options: MWinParams) { + const controller = new MWinController(node, options); + const api: MWinAPI = { + state: controller.state, + minimize: () => controller.minimize(), + maximize: () => controller.maximize(), + close: () => controller.close() + }; + + options.onAPI?.(api); + return { + destroy: () => controller.destroy() + }; +} + +class MWinController { + #rafID: number | null = null; + #pendingApply = false; + + #node: HTMLElement; + #wrapper: HTMLElement; + #opts: MWinNormalizedParams; + #savedTransition: string; + #savedStyles: string; + #wrapperObserver: ResizeObserver | null = null; + + #wrapperWidth: number = 0; + #wrapperHeight: number = 0; + #wrapperLeft: number = 0; + #wrapperTop: number = 0; + #wrapperBorderLeft: number = 0; + #wrapperBorderTop: number = 0; + + #dragOffsetX: number = 0; + #dragOffsetY: number = 0; + #resizeDirection: ResizeDirection = null; + #resizeStartRect = { x: 0, y: 0, width: 0, height: 0 }; + #resizeStartPos = { x: 0, y: 0 }; + #restoreRect: { x: number; y: number; width: number; height: number } | null = null; + + state = $state({ + x: 0, + y: 0, + width: 0, + height: 0, + minimized: false, + maximized: false, + moving: false, + resizing: false, + zIndex: 0 + }); + + constructor(node: HTMLElement, options: MWinParams) { + this.#node = node; + + const wrapper = resolveElement(options.wrapper, node); + if (!wrapper) throw new Error('[Movable] - Wrapper element not found!'); + this.#wrapper = wrapper; + + const wrapperStyle = getComputedStyle(this.#wrapper); + this.#wrapperBorderLeft = parseFloat(wrapperStyle.borderLeftWidth); + this.#wrapperBorderTop = parseFloat(wrapperStyle.borderTopWidth); + + const resizableOpts = typeof options.resizable === 'object' ? options.resizable : {}; + + this.#opts = { + handle: resolveElement(options.handle, node), + initX: options.initX, + initY: options.initY, + initWidth: options.initWidth, + initHeight: options.initHeight, + baseZIndex: options.baseZIndex ?? 1, + resizeHandle: resolveElement(options.resizeHandle, node), + resizable: !!options.resizable, + threshold: resizableOpts.threshold ?? 8, + minWidth: resizableOpts.minWidth ?? 24, //MinWidth should be min-content + minHeight: resizableOpts.minHeight ?? 24, //MinHeight should be min-content + maxWidth: resizableOpts.maxWidth ?? Infinity, + maxHeight: resizableOpts.maxHeight ?? Infinity, + onClose: options.onClose, + onMinimize: options.onMinimize, + onMaximize: options.onMaximize + }; + this.#savedStyles = this.#node.style.cssText; + this.#savedTransition = this.#node.style.transition; + this.#node.style.transition = 'none'; + this.#node.style.willChange = 'transform'; + + this.#wrapper.style.position = 'relative'; + this.#node.style.position = 'absolute'; + + const wRect = this.#wrapper.getBoundingClientRect(); + const nRect = this.#node.getBoundingClientRect(); + + this.state.x = this.#opts.initX ?? nRect.left - wRect.left; + this.state.y = this.#opts.initY ?? nRect.top - wRect.top; + this.state.width = this.#opts.initWidth ?? nRect.width; + this.state.height = this.#opts.initHeight ?? nRect.height; + + this.#node.style.left = '0'; + this.#node.style.top = '0'; + this.#node.classList.add('[Movable]'); + + const mgr = getWrapperManager(this.#wrapper); + mgr.refCount++; + + if (!node.hasAttribute('tabindex')) { + node.setAttribute('tabindex', '0'); + } + + node.setAttribute('role', 'region'); + node.setAttribute('aria-label', 'Movable window'); + + this.#cacheWrapperRect(); + + node.addEventListener('pointerdown', this.#onPointerDown); + node.addEventListener('pointermove', this.#updateCursor); + node.addEventListener('pointerleave', this.#resetCursor); + + this.#clampAndApply(); + this.#bringToFront(); + + this.#wrapperObserver = new ResizeObserver(() => { + this.#wrapperWidth = this.#wrapper.clientWidth; + this.#wrapperHeight = this.#wrapper.clientHeight; + + this.#onWrapperResize(); + }); + this.#wrapperObserver.observe(this.#wrapper); + } + + #cacheWrapperRect() { + const wrapperRect = this.#wrapper.getBoundingClientRect(); + + this.#wrapperLeft = wrapperRect.left + this.#wrapperBorderLeft; + this.#wrapperTop = wrapperRect.top + this.#wrapperBorderTop; + this.#wrapperWidth = this.#wrapper.clientWidth; + this.#wrapperHeight = this.#wrapper.clientHeight; + } + + #bringToFront() { + const mgr = getWrapperManager(this.#wrapper); + mgr.zCounter++; + + this.state.zIndex = this.#opts.baseZIndex + mgr.zCounter; + this.#node.style.zIndex = String(this.state.zIndex); + } + + #clampAndApply() { + this.#clampRect(); + this.#apply(); + } + + #clampRect() { + const bw = this.#wrapperWidth; + const bh = this.#wrapperHeight; + + let w = Math.min(this.state.width, bw, this.#opts.maxWidth); + w = Math.max(w, this.#opts.minWidth, 0); + let h = Math.min(this.state.height, bh, this.#opts.maxHeight); + h = Math.max(h, this.#opts.minHeight, 0); + + this.state.width = w; + this.state.height = h; + + const maxX = Math.max(0, bw - w); + const maxY = Math.max(0, bh - h); + this.state.x = Math.min(Math.max(this.state.x, 0), maxX); + this.state.y = Math.min(Math.max(this.state.y, 0), maxY); + } + + #apply() { + this.#node.style.transform = `translate(${this.state.x}px, ${this.state.y}px)`; + this.#node.style.setProperty('--x', this.state.x.toString()); + this.#node.style.setProperty('--y', this.state.y.toString()); + this.#node.style.setProperty('--w', this.state.width.toString()); + this.#node.style.setProperty('--h', this.state.height.toString()); + this.#node.style.width = this.state.width + 'px'; + this.#node.style.height = this.state.height + 'px'; + } + + #getCornerDirection(e: PointerEvent): ResizeDirection { + if (!this.#opts.resizable) return null; + const t = this.#opts.threshold; + + let dirY: string = ''; + if (e.clientY - this.state.y < t) dirY = 'n'; + else if (this.state.y + this.state.height - e.clientY < t) dirY = 's'; + + let dirX: string = ''; + if (e.clientX - this.state.x < t) dirX = 'w'; + else if (this.state.x + this.state.width - e.clientX < t) dirX = 'e'; + + if (dirY && dirX) { + return (dirY + dirX) as ResizeDirection; + } + return null; + } + + #onPointerCancel = () => this.#onPointerUp(); + + #onPointerDown = (e: PointerEvent): void => { + if (this.#isInteractive(e.target as HTMLElement)) return; + if (this.state.minimized) return; + + if (this.state.maximized) { + const target = e.target as HTMLElement; + const canDrag = this.#opts.handle?.contains(target) || !this.#opts.handle; + if (canDrag) this.#unmaximizeAtCursor(e); + return; + } + + if (this.#opts.resizeHandle?.contains(e.target as HTMLElement)) { + this.#startResize(e, 'se'); + return; + } + + const dir = this.#getCornerDirection(e); + if (dir) { + this.#startResize(e, dir); + return; + } + + if (this.#opts.handle?.contains(e.target as HTMLElement)) { + this.#startMove(e); + return; + } + + if (!this.#opts.handle) { + this.#startMove(e); + } + }; + + #startMove(e: PointerEvent, skipOffset = false): void { + e.preventDefault(); + this.#bringToFront(); + this.state.moving = true; + this.#node.style.cursor = 'grabbing'; + + this.#cacheWrapperRect(); + + if (!skipOffset) { + const rect = this.#node.getBoundingClientRect(); + this.#dragOffsetX = e.clientX - rect.left; + this.#dragOffsetY = e.clientY - rect.top; + } + + this.#prepareInteraction(); + } + + #startResize(e: PointerEvent, direction: ResizeDirection): void { + e.preventDefault(); + e.stopPropagation(); + this.#bringToFront(); + this.state.resizing = true; + + this.#cacheWrapperRect(); + + this.#resizeDirection = direction; + this.#resizeStartRect = { + x: this.state.x, + y: this.state.y, + width: this.state.width, + height: this.state.height + }; + + this.#resizeStartPos = { x: e.clientX - this.#wrapperLeft, y: e.clientY - this.#wrapperTop }; + + this.#prepareInteraction(); + } + + #unmaximizeAtCursor(e: PointerEvent): void { + this.#cacheWrapperRect(); + + const cursorX = e.clientX - this.#wrapperLeft; + const cursorY = e.clientY - this.#wrapperTop; + + const fracX = this.#wrapperWidth > 0 ? cursorX / this.#wrapperWidth : 0; + const fracY = this.#wrapperHeight > 0 ? cursorY / this.#wrapperHeight : 0; + + if (this.#restoreRect) { + this.state.width = this.#restoreRect.width; + this.state.height = this.#restoreRect.height; + this.state.maximized = false; + this.#restoreRect = null; + } else { + // fallback: no saved rect, just keep current size + this.state.maximized = false; + } + + // Position so the same relative point stays under the cursor + let newX = cursorX - fracX * this.state.width; + let newY = cursorY - fracY * this.state.height; + + // Clamp inside the boundary + const maxX = Math.max(0, this.#wrapperWidth - this.state.width); + const maxY = Math.max(0, this.#wrapperHeight - this.state.height); + newX = Math.min(Math.max(newX, 0), maxX); + newY = Math.min(Math.max(newY, 0), maxY); + + this.state.x = newX; + this.state.y = newY; + this.#scheduleApply(); + + this.#dragOffsetX = cursorX - newX; + this.#dragOffsetY = cursorY - newY; + + this.#bringToFront(); + this.state.moving = true; + this.#node.style.cursor = 'grabbing'; + this.#prepareInteraction(); + return; + } + + #prepareInteraction(): void { + document.body.style.userSelect = 'none'; + this.#node.style.transition = 'none'; + this.#node.style.willChange = 'transform, width, height'; + this.#node.style.touchAction = 'none'; + + window.addEventListener('pointermove', this.#onPointerMove, { passive: true }); + window.addEventListener('pointerup', this.#onPointerUp, { passive: true }); + window.addEventListener('pointercancel', this.#onPointerCancel, { passive: true }); + } + + #onPointerMove = (e: PointerEvent): void => { + this.#cacheWrapperRect(); + const events = e.getCoalescedEvents?.() ?? [e]; + + for (const event of events) { + if (this.state.moving) { + this.#updateMove(event); + } else if (this.state.resizing) { + this.#updateResize(event); + } + } + + this.#scheduleApply(); + }; + + #scheduleApply(): void { + if (!this.#pendingApply) { + this.#pendingApply = true; + this.#rafID = requestAnimationFrame(() => { + if (!this.state.moving && !this.state.resizing) { + this.#node.style.willChange = 'auto'; + } + + this.#rafID = null; + this.#pendingApply = false; + this.#apply(); + }); + } + } + + #updateMove(e: PointerEvent): void { + let newX = e.clientX - this.#wrapperLeft - this.#dragOffsetX; + let newY = e.clientY - this.#wrapperTop - this.#dragOffsetY; + + newX = Math.max(0, Math.min(newX, this.#wrapperWidth - this.state.width)); + newY = Math.max(0, Math.min(newY, this.#wrapperHeight - this.state.height)); + + this.state.x = newX; + this.state.y = newY; + } + + #updateResize(e: PointerEvent): void { + const dir = this.#resizeDirection!; + const start = this.#resizeStartRect; + const dx = e.clientX - this.#wrapperLeft - this.#resizeStartPos.x; + const dy = e.clientY - this.#wrapperTop - this.#resizeStartPos.y; + + const anchorLeft = dir.includes('e') ? start.x : start.x + start.width; + const anchorTop = dir.includes('s') ? start.y : start.y + start.height; + + let movingX = anchorLeft; + let movingY = anchorTop; + + if (dir.includes('e')) movingX = start.x + start.width + dx; + else movingX = start.x + dx; + + if (dir.includes('s')) movingY = start.y + start.height + dy; + else movingY = start.y + dy; + + const minWidth = this.#opts.minWidth; + const minHeight = this.#opts.minHeight; + const maxWidth = Math.min(this.#opts.maxWidth, this.#wrapperWidth); + const maxHeight = Math.min(this.#opts.maxHeight, this.#wrapperHeight); + + if (dir.includes('e')) { + movingX = Math.max(anchorLeft + minWidth, Math.min(movingX, anchorLeft + maxWidth)); + movingX = Math.min(movingX, this.#wrapperWidth); + } else { + movingX = Math.min(anchorLeft - minWidth, Math.max(movingX, anchorLeft - maxWidth)); + movingX = Math.max(movingX, 0); + } + + if (dir.includes('s')) { + movingY = Math.max(anchorTop + minHeight, Math.min(movingY, anchorTop + maxHeight)); + movingY = Math.min(movingY, this.#wrapperHeight); + } else { + movingY = Math.min(anchorTop - minHeight, Math.max(movingY, anchorTop - maxHeight)); + movingY = Math.max(movingY, 0); + } + + const newX = Math.min(anchorLeft, movingX); + const newY = Math.min(anchorTop, movingY); + const newWidth = Math.abs(movingX - anchorLeft); + const newHeight = Math.abs(movingY - anchorTop); + + this.state.x = newX; + this.state.y = newY; + this.state.width = newWidth; + this.state.height = newHeight; + } + + #onPointerUp = (): void => { + if (this.#rafID !== null) { + cancelAnimationFrame(this.#rafID); + this.#rafID = null; + this.#pendingApply = false; + } + + this.state.moving = false; + this.state.resizing = false; + this.#resizeDirection = null; + + document.body.style.userSelect = ''; + this.#node.style.transition = this.#savedTransition; + this.#node.style.willChange = 'auto'; + this.#node.style.touchAction = ''; + this.#node.style.cursor = 'auto'; + + window.removeEventListener('pointermove', this.#onPointerMove); + window.removeEventListener('pointerup', this.#onPointerUp); + window.removeEventListener('pointercancel', this.#onPointerCancel); + + this.#apply(); + }; + + #onWrapperResize(): void { + const style = getComputedStyle(this.#wrapper); + this.#wrapperBorderLeft = parseFloat(style.borderLeftWidth); + this.#wrapperBorderTop = parseFloat(style.borderTopWidth); + + if (this.state.maximized) { + this.state.width = this.#wrapperWidth; + this.state.height = this.#wrapperHeight; + this.state.x = 0; + this.state.y = 0; + } else { + this.#clampRect(); + } + + this.#apply(); + } + + #updateCursor = (e: PointerEvent): void => { + if (this.state.moving || this.state.resizing) return; + const target = e.target as HTMLElement; + + if (this.#isInteractive(target)) { + this.#resetCursor(); + return; + } + + if (this.#opts.resizeHandle?.contains(target)) { + this.#node.style.cursor = 'se-resize'; + return; + } + + const dir = this.#getCornerDirection(e); + if (dir) { + this.#node.style.cursor = dir === 'nw' || dir === 'se' ? 'nwse-resize' : 'nesw-resize'; + return; + } + + if (this.#opts.handle) { + if (this.#opts.handle.contains(target)) { + this.#node.style.cursor = 'grab'; + } else { + this.#node.style.cursor = ''; + } + } else { + this.#node.style.cursor = ''; + } + }; + + #resetCursor = (): void => { + this.#node.style.cursor = ''; + }; + + #isInteractive(target: HTMLElement): boolean { + const tag = target.tagName; + if (['INPUT', 'BUTTON', 'TEXTAREA', 'SELECT', 'A'].includes(tag)) return true; + if (target.isContentEditable) return true; + return !!target.closest('[role="button"], [role="textbox"]'); + } + + minimize(): void { + this.state.minimized = !this.state.minimized; + this.#opts.onMinimize?.(); + } + + maximize(): void { + if (this.state.maximized) { + if (this.#restoreRect) { + Object.assign(this.state, this.#restoreRect); + this.#restoreRect = null; + } + this.state.maximized = false; + } else { + this.#restoreRect = { + x: this.state.x, + y: this.state.y, + width: this.state.width, + height: this.state.height + }; + this.state.x = 0; + this.state.y = 0; + this.state.width = this.#wrapperWidth; + this.state.height = this.#wrapperHeight; + this.state.maximized = true; + } + this.#apply(); + } + + close(): void { + this.#opts.onClose?.(); + } + + destroy(): void { + if (this.#rafID !== null) { + cancelAnimationFrame(this.#rafID); + } + + this.#node.removeEventListener('pointerdown', this.#onPointerDown); + this.#node.removeEventListener('pointermove', this.#updateCursor); + this.#node.removeEventListener('pointerleave', this.#resetCursor); + //this.#node.removeEventListener('keydown', this.#onKeyDown); + + window.removeEventListener('pointermove', this.#onPointerMove); + window.removeEventListener('pointerup', this.#onPointerUp); + window.removeEventListener('pointercancel', this.#onPointerCancel); + + if (this.#wrapperObserver) { + this.#wrapperObserver.disconnect(); + } + + const mgr = getWrapperManager(this.#wrapper); + mgr.refCount--; + if (mgr.refCount === 0) { + delete (this.#wrapper as any)[MWIN_MANAGER]; + } + + document.body.style.userSelect = ''; + this.#node.style.cssText = this.#savedStyles; + this.#node.style.transition = this.#savedTransition; + this.#node.style.willChange = 'auto'; + this.#node.style.touchAction = ''; + } +} diff --git a/src/lib/mwinlib/mwin_util.ts b/src/lib/mwinlib/mwin_util.ts new file mode 100644 index 0000000..fdc9167 --- /dev/null +++ b/src/lib/mwinlib/mwin_util.ts @@ -0,0 +1,96 @@ +export interface MWinParams { + wrapper: HTMLElement | (() => HTMLElement) | string; // changed + handle?: HTMLElement | (() => HTMLElement) | string; + initX?: number; + initY?: number; + initWidth?: number; + initHeight?: number; + baseZIndex?: number; + resizable?: boolean | MWinResizeParams; + resizeHandle?: HTMLElement | (() => HTMLElement) | string; + onClose?: () => void; + onMinimize?: () => void; + onMaximize?: () => void; + onAPI?: (api: MWinAPI) => void; +} + +export interface MWinNormalizedParams { + handle: HTMLElement | null; + initX?: number; + initY?: number; + initWidth?: number; + initHeight?: number; + baseZIndex: number; + resizeHandle: HTMLElement | null; + resizable: boolean; + threshold: number; + minWidth: number; + minHeight: number; + maxWidth: number; + maxHeight: number; + onClose?: () => void; + onMinimize?: () => void; + onMaximize?: () => void; +} + +export interface MWinResizeParams { + threshold?: number; + minWidth?: number; + minHeight?: number; + maxWidth?: number; + maxHeight?: number; +} + +export interface MWinState { + x: number; + y: number; + width: number; + height: number; + minimized: boolean; + maximized: boolean; + moving: boolean; + resizing: boolean; + zIndex: number; +} + +export interface MWinAPI { + state: MWinState; + minimize: () => void; + maximize: () => void; + close: () => void; +} + +export class WrapperManager { + zCounter: number = 0; + refCount: number = 0; +} + +export type ResizeDirection = 'ne' | 'se' | 'sw' | 'nw' | null; + +export const MWIN_MANAGER = Symbol('mwinlib'); + +export function getWrapperManager(wrapper: HTMLElement): WrapperManager { + let mgr = (wrapper as any)[MWIN_MANAGER] as WrapperManager | undefined; + if (!mgr) { + mgr = { zCounter: 0, refCount: 0 }; + (wrapper as any)[MWIN_MANAGER] = mgr; + } + return mgr; +} + +export function resolveElement( + input: HTMLElement | (() => HTMLElement) | string | undefined, + relativeTo: HTMLElement +): HTMLElement | null { + if (!input) return null; + + if (input instanceof HTMLElement) return input; + + if (typeof input === 'function') return input(); + + if (typeof input === 'string') { + return relativeTo.closest(input) as HTMLElement | null; + } + + return null; +} diff --git a/src/lib/server/db/index.ts b/src/lib/server/db/index.ts index f89ebb1..66c2636 100644 --- a/src/lib/server/db/index.ts +++ b/src/lib/server/db/index.ts @@ -1,10 +1,5 @@ -import { drizzle } from 'drizzle-orm/mysql2'; -import mysql from 'mysql2/promise'; -import * as schema from './schema'; -import { env } from '$env/dynamic/private'; +//if (!env.DATABASE_URL) throw new Error('DATABASE_URL is not set'); -if (!env.DATABASE_URL) throw new Error('DATABASE_URL is not set'); +//const client = mysql.createPool(env.DATABASE_URL); -const client = mysql.createPool(env.DATABASE_URL); - -export const db = drizzle(client, { schema, mode: 'default', logger: true }); +//export const db = drizzle(client, { schema, mode: 'default', logger: true }); diff --git a/src/lib/shimagic/.svelte-kit/ambient.d.ts b/src/lib/shimagic/.svelte-kit/ambient.d.ts new file mode 100644 index 0000000..877f268 --- /dev/null +++ b/src/lib/shimagic/.svelte-kit/ambient.d.ts @@ -0,0 +1,382 @@ + +// this file is generated — do not edit it + + +/// + +/** + * This module provides access to environment variables that are injected _statically_ into your bundle at build time and are limited to _private_ access. + * + * | | Runtime | Build time | + * | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ | + * | Private | [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private) | [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private) | + * | Public | [`$env/dynamic/public`](https://svelte.dev/docs/kit/$env-dynamic-public) | [`$env/static/public`](https://svelte.dev/docs/kit/$env-static-public) | + * + * Static environment variables are [loaded by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files) from `.env` files and `process.env` at build time and then statically injected into your bundle at build time, enabling optimisations like dead code elimination. + * + * **_Private_ access:** + * + * - This module cannot be imported into client-side code + * - This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](https://svelte.dev/docs/kit/configuration#env) (if configured) + * + * For example, given the following build time environment: + * + * ```env + * ENVIRONMENT=production + * PUBLIC_BASE_URL=http://site.com + * ``` + * + * With the default `publicPrefix` and `privatePrefix`: + * + * ```ts + * import { ENVIRONMENT, PUBLIC_BASE_URL } from '$env/static/private'; + * + * console.log(ENVIRONMENT); // => "production" + * console.log(PUBLIC_BASE_URL); // => throws error during build + * ``` + * + * The above values will be the same _even if_ different values for `ENVIRONMENT` or `PUBLIC_BASE_URL` are set at runtime, as they are statically replaced in your code with their build time values. + */ +declare module '$env/static/private' { + export const APP2UNIT_SLICES: string; + export const CHROME_DESKTOP: string; + export const CLUTTER_BACKEND: string; + export const DBUS_SESSION_BUS_ADDRESS: string; + export const DEBUGINFOD_URLS: string; + export const DESKTOP_SESSION: string; + export const DISPLAY: string; + export const EDITOR: string; + export const ELECTRON_NO_ATTACH_CONSOLE: string; + export const ELECTRON_OZONE_PLATFORM_HINT: string; + export const FC_FONTATIONS: string; + export const GDK_BACKEND: string; + export const HL_INITIAL_WORKSPACE_TOKEN: string; + export const HOME: string; + export const HYPRLAND_CMD: string; + export const HYPRLAND_INSTANCE_SIGNATURE: string; + export const INVOCATION_ID: string; + export const JOURNAL_STREAM: string; + export const LANG: string; + export const LC_ADDRESS: string; + export const LC_IDENTIFICATION: string; + export const LC_MEASUREMENT: string; + export const LC_MONETARY: string; + export const LC_NAME: string; + export const LC_NUMERIC: string; + export const LC_PAPER: string; + export const LC_TELEPHONE: string; + export const LC_TIME: string; + export const LOGNAME: string; + export const MAIL: string; + export const MANAGERPID: string; + export const MANAGERPIDFDID: string; + export const MEMORY_PRESSURE_WATCH: string; + export const MEMORY_PRESSURE_WRITE: string; + export const MOTD_SHOWN: string; + export const MOZ_ENABLE_WAYLAND: string; + export const NOTIFY_SOCKET: string; + export const NO_AT_BRIDGE: string; + export const PATH: string; + export const PWD: string; + export const QS_ICON_THEME: string; + export const QT_AUTO_SCREEN_SCALE_FACTOR: string; + export const QT_QPA_PLATFORM: string; + export const QT_QPA_PLATFORMTHEME: string; + export const QT_WAYLAND_DISABLE_WINDOWDECORATION: string; + export const SDL_VIDEODRIVER: string; + export const SHELL: string; + export const SHLVL: string; + export const SYSTEMD_EXEC_PID: string; + export const USER: string; + export const UWSM_FINALIZE_VARNAMES: string; + export const UWSM_WAIT_VARNAMES: string; + export const VIRTUAL_ENV_DISABLE_PROMPT: string; + export const VSCODE_CLI: string; + export const VSCODE_CODE_CACHE_PATH: string; + export const VSCODE_CRASH_REPORTER_PROCESS_TYPE: string; + export const VSCODE_CWD: string; + export const VSCODE_ESM_ENTRYPOINT: string; + export const VSCODE_HANDLES_UNCAUGHT_ERRORS: string; + export const VSCODE_IPC_HOOK: string; + export const VSCODE_NLS_CONFIG: string; + export const VSCODE_PID: string; + export const VSSCRIPT_PATH: string; + export const WAYLAND_DISPLAY: string; + export const XCURSOR_SIZE: string; + export const XCURSOR_THEME: string; + export const XDG_BACKEND: string; + export const XDG_CACHE_HOME: string; + export const XDG_CONFIG_DIRS: string; + export const XDG_CONFIG_HOME: string; + export const XDG_CURRENT_DESKTOP: string; + export const XDG_DATA_DIRS: string; + export const XDG_DATA_HOME: string; + export const XDG_MENU_PREFIX: string; + export const XDG_RUNTIME_DIR: string; + export const XDG_SEAT: string; + export const XDG_SEAT_PATH: string; + export const XDG_SESSION_CLASS: string; + export const XDG_SESSION_DESKTOP: string; + export const XDG_SESSION_ID: string; + export const XDG_SESSION_PATH: string; + export const XDG_SESSION_TYPE: string; + export const XDG_STATE_HOME: string; + export const XDG_VTNR: string; + export const _: string; + export const _JAVA_AWT_WM_NONREPARENTING: string; + export const ELECTRON_RUN_AS_NODE: string; + export const VSCODE_L10N_BUNDLE_LOCATION: string; + export const VITEST_VSCODE_LOG: string; + export const VITEST_VSCODE: string; + export const TEST: string; + export const VITEST_WS_ADDRESS: string; + export const VITEST: string; + export const NODE_ENV: string; + export const FORCE_COLOR: string; + export const PROD: string; + export const DEV: string; + export const BASE_URL: string; + export const MODE: string; +} + +/** + * This module provides access to environment variables that are injected _statically_ into your bundle at build time and are _publicly_ accessible. + * + * | | Runtime | Build time | + * | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ | + * | Private | [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private) | [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private) | + * | Public | [`$env/dynamic/public`](https://svelte.dev/docs/kit/$env-dynamic-public) | [`$env/static/public`](https://svelte.dev/docs/kit/$env-static-public) | + * + * Static environment variables are [loaded by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files) from `.env` files and `process.env` at build time and then statically injected into your bundle at build time, enabling optimisations like dead code elimination. + * + * **_Public_ access:** + * + * - This module _can_ be imported into client-side code + * - **Only** variables that begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) (which defaults to `PUBLIC_`) are included + * + * For example, given the following build time environment: + * + * ```env + * ENVIRONMENT=production + * PUBLIC_BASE_URL=http://site.com + * ``` + * + * With the default `publicPrefix` and `privatePrefix`: + * + * ```ts + * import { ENVIRONMENT, PUBLIC_BASE_URL } from '$env/static/public'; + * + * console.log(ENVIRONMENT); // => throws error during build + * console.log(PUBLIC_BASE_URL); // => "http://site.com" + * ``` + * + * The above values will be the same _even if_ different values for `ENVIRONMENT` or `PUBLIC_BASE_URL` are set at runtime, as they are statically replaced in your code with their build time values. + */ +declare module '$env/static/public' { + +} + +/** + * This module provides access to environment variables set _dynamically_ at runtime and that are limited to _private_ access. + * + * | | Runtime | Build time | + * | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ | + * | Private | [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private) | [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private) | + * | Public | [`$env/dynamic/public`](https://svelte.dev/docs/kit/$env-dynamic-public) | [`$env/static/public`](https://svelte.dev/docs/kit/$env-static-public) | + * + * Dynamic environment variables are defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node) (or running [`vite preview`](https://svelte.dev/docs/kit/cli)), this is equivalent to `process.env`. + * + * **_Private_ access:** + * + * - This module cannot be imported into client-side code + * - This module includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](https://svelte.dev/docs/kit/configuration#env) (if configured) + * + * > [!NOTE] In `dev`, `$env/dynamic` includes environment variables from `.env`. In `prod`, this behavior will depend on your adapter. + * + * > [!NOTE] To get correct types, environment variables referenced in your code should be declared (for example in an `.env` file), even if they don't have a value until the app is deployed: + * > + * > ```env + * > MY_FEATURE_FLAG= + * > ``` + * > + * > You can override `.env` values from the command line like so: + * > + * > ```sh + * > MY_FEATURE_FLAG="enabled" npm run dev + * > ``` + * + * For example, given the following runtime environment: + * + * ```env + * ENVIRONMENT=production + * PUBLIC_BASE_URL=http://site.com + * ``` + * + * With the default `publicPrefix` and `privatePrefix`: + * + * ```ts + * import { env } from '$env/dynamic/private'; + * + * console.log(env.ENVIRONMENT); // => "production" + * console.log(env.PUBLIC_BASE_URL); // => undefined + * ``` + */ +declare module '$env/dynamic/private' { + export const env: { + APP2UNIT_SLICES: string; + CHROME_DESKTOP: string; + CLUTTER_BACKEND: string; + DBUS_SESSION_BUS_ADDRESS: string; + DEBUGINFOD_URLS: string; + DESKTOP_SESSION: string; + DISPLAY: string; + EDITOR: string; + ELECTRON_NO_ATTACH_CONSOLE: string; + ELECTRON_OZONE_PLATFORM_HINT: string; + FC_FONTATIONS: string; + GDK_BACKEND: string; + HL_INITIAL_WORKSPACE_TOKEN: string; + HOME: string; + HYPRLAND_CMD: string; + HYPRLAND_INSTANCE_SIGNATURE: string; + INVOCATION_ID: string; + JOURNAL_STREAM: string; + LANG: string; + LC_ADDRESS: string; + LC_IDENTIFICATION: string; + LC_MEASUREMENT: string; + LC_MONETARY: string; + LC_NAME: string; + LC_NUMERIC: string; + LC_PAPER: string; + LC_TELEPHONE: string; + LC_TIME: string; + LOGNAME: string; + MAIL: string; + MANAGERPID: string; + MANAGERPIDFDID: string; + MEMORY_PRESSURE_WATCH: string; + MEMORY_PRESSURE_WRITE: string; + MOTD_SHOWN: string; + MOZ_ENABLE_WAYLAND: string; + NOTIFY_SOCKET: string; + NO_AT_BRIDGE: string; + PATH: string; + PWD: string; + QS_ICON_THEME: string; + QT_AUTO_SCREEN_SCALE_FACTOR: string; + QT_QPA_PLATFORM: string; + QT_QPA_PLATFORMTHEME: string; + QT_WAYLAND_DISABLE_WINDOWDECORATION: string; + SDL_VIDEODRIVER: string; + SHELL: string; + SHLVL: string; + SYSTEMD_EXEC_PID: string; + USER: string; + UWSM_FINALIZE_VARNAMES: string; + UWSM_WAIT_VARNAMES: string; + VIRTUAL_ENV_DISABLE_PROMPT: string; + VSCODE_CLI: string; + VSCODE_CODE_CACHE_PATH: string; + VSCODE_CRASH_REPORTER_PROCESS_TYPE: string; + VSCODE_CWD: string; + VSCODE_ESM_ENTRYPOINT: string; + VSCODE_HANDLES_UNCAUGHT_ERRORS: string; + VSCODE_IPC_HOOK: string; + VSCODE_NLS_CONFIG: string; + VSCODE_PID: string; + VSSCRIPT_PATH: string; + WAYLAND_DISPLAY: string; + XCURSOR_SIZE: string; + XCURSOR_THEME: string; + XDG_BACKEND: string; + XDG_CACHE_HOME: string; + XDG_CONFIG_DIRS: string; + XDG_CONFIG_HOME: string; + XDG_CURRENT_DESKTOP: string; + XDG_DATA_DIRS: string; + XDG_DATA_HOME: string; + XDG_MENU_PREFIX: string; + XDG_RUNTIME_DIR: string; + XDG_SEAT: string; + XDG_SEAT_PATH: string; + XDG_SESSION_CLASS: string; + XDG_SESSION_DESKTOP: string; + XDG_SESSION_ID: string; + XDG_SESSION_PATH: string; + XDG_SESSION_TYPE: string; + XDG_STATE_HOME: string; + XDG_VTNR: string; + _: string; + _JAVA_AWT_WM_NONREPARENTING: string; + ELECTRON_RUN_AS_NODE: string; + VSCODE_L10N_BUNDLE_LOCATION: string; + VITEST_VSCODE_LOG: string; + VITEST_VSCODE: string; + TEST: string; + VITEST_WS_ADDRESS: string; + VITEST: string; + NODE_ENV: string; + FORCE_COLOR: string; + PROD: string; + DEV: string; + BASE_URL: string; + MODE: string; + [key: `PUBLIC_${string}`]: undefined; + [key: `${string}`]: string | undefined; + } +} + +/** + * This module provides access to environment variables set _dynamically_ at runtime and that are _publicly_ accessible. + * + * | | Runtime | Build time | + * | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ | + * | Private | [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private) | [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private) | + * | Public | [`$env/dynamic/public`](https://svelte.dev/docs/kit/$env-dynamic-public) | [`$env/static/public`](https://svelte.dev/docs/kit/$env-static-public) | + * + * Dynamic environment variables are defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node) (or running [`vite preview`](https://svelte.dev/docs/kit/cli)), this is equivalent to `process.env`. + * + * **_Public_ access:** + * + * - This module _can_ be imported into client-side code + * - **Only** variables that begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) (which defaults to `PUBLIC_`) are included + * + * > [!NOTE] In `dev`, `$env/dynamic` includes environment variables from `.env`. In `prod`, this behavior will depend on your adapter. + * + * > [!NOTE] To get correct types, environment variables referenced in your code should be declared (for example in an `.env` file), even if they don't have a value until the app is deployed: + * > + * > ```env + * > MY_FEATURE_FLAG= + * > ``` + * > + * > You can override `.env` values from the command line like so: + * > + * > ```sh + * > MY_FEATURE_FLAG="enabled" npm run dev + * > ``` + * + * For example, given the following runtime environment: + * + * ```env + * ENVIRONMENT=production + * PUBLIC_BASE_URL=http://example.com + * ``` + * + * With the default `publicPrefix` and `privatePrefix`: + * + * ```ts + * import { env } from '$env/dynamic/public'; + * console.log(env.ENVIRONMENT); // => undefined, not public + * console.log(env.PUBLIC_BASE_URL); // => "http://example.com" + * ``` + * + * ``` + * + * ``` + */ +declare module '$env/dynamic/public' { + export const env: { + [key: `PUBLIC_${string}`]: string | undefined; + } +} diff --git a/src/lib/shimagic/.svelte-kit/generated/client/app.js b/src/lib/shimagic/.svelte-kit/generated/client/app.js new file mode 100644 index 0000000..436066e --- /dev/null +++ b/src/lib/shimagic/.svelte-kit/generated/client/app.js @@ -0,0 +1,28 @@ +export { matchers } from './matchers.js'; + +export const nodes = [ + () => import('./nodes/0'), + () => import('./nodes/1') +]; + +export const server_loads = []; + +export const dictionary = { + + }; + +export const hooks = { + handleError: (({ error }) => { console.error(error) }), + + reroute: (() => {}), + transport: {} +}; + +export const decoders = Object.fromEntries(Object.entries(hooks.transport).map(([k, v]) => [k, v.decode])); +export const encoders = Object.fromEntries(Object.entries(hooks.transport).map(([k, v]) => [k, v.encode])); + +export const hash = false; + +export const decode = (type, value) => decoders[type](value); + +export { default as root } from '../root.js'; \ No newline at end of file diff --git a/src/lib/shimagic/.svelte-kit/generated/client/matchers.js b/src/lib/shimagic/.svelte-kit/generated/client/matchers.js new file mode 100644 index 0000000..f6bd30a --- /dev/null +++ b/src/lib/shimagic/.svelte-kit/generated/client/matchers.js @@ -0,0 +1 @@ +export const matchers = {}; \ No newline at end of file diff --git a/src/lib/shimagic/.svelte-kit/generated/client/nodes/0.js b/src/lib/shimagic/.svelte-kit/generated/client/nodes/0.js new file mode 100644 index 0000000..f35a737 --- /dev/null +++ b/src/lib/shimagic/.svelte-kit/generated/client/nodes/0.js @@ -0,0 +1 @@ +export { default as component } from "../../../../../../../node_modules/@sveltejs/kit/src/runtime/components/svelte-5/layout.svelte"; \ No newline at end of file diff --git a/src/lib/shimagic/.svelte-kit/generated/client/nodes/1.js b/src/lib/shimagic/.svelte-kit/generated/client/nodes/1.js new file mode 100644 index 0000000..235187d --- /dev/null +++ b/src/lib/shimagic/.svelte-kit/generated/client/nodes/1.js @@ -0,0 +1 @@ +export { default as component } from "../../../../../../../node_modules/@sveltejs/kit/src/runtime/components/svelte-5/error.svelte"; \ No newline at end of file diff --git a/src/lib/shimagic/.svelte-kit/tsconfig.json b/src/lib/shimagic/.svelte-kit/tsconfig.json new file mode 100644 index 0000000..2f1e7dc --- /dev/null +++ b/src/lib/shimagic/.svelte-kit/tsconfig.json @@ -0,0 +1,52 @@ +{ + "compilerOptions": { + "paths": { + "$app/types": [ + "./types/index.d.ts" + ] + }, + "rootDirs": [ + "..", + "./types" + ], + "verbatimModuleSyntax": true, + "isolatedModules": true, + "lib": [ + "esnext", + "DOM", + "DOM.Iterable" + ], + "moduleResolution": "bundler", + "module": "esnext", + "noEmit": true, + "target": "esnext", + "types": [ + "node" + ] + }, + "include": [ + "ambient.d.ts", + "non-ambient.d.ts", + "./types/**/$types.d.ts", + "../vite.config.js", + "../vite.config.ts", + "../src/**/*.js", + "../src/**/*.ts", + "../src/**/*.svelte", + "../test/**/*.js", + "../test/**/*.ts", + "../test/**/*.svelte", + "../tests/**/*.js", + "../tests/**/*.ts", + "../tests/**/*.svelte" + ], + "exclude": [ + "../node_modules/**", + "../src/service-worker.js", + "../src/service-worker/**/*.js", + "../src/service-worker.ts", + "../src/service-worker/**/*.ts", + "../src/service-worker.d.ts", + "../src/service-worker/**/*.d.ts" + ] +} \ No newline at end of file diff --git a/src/lib/shimagic/Shimeji.svelte b/src/lib/shimagic/Shimeji.svelte new file mode 100644 index 0000000..92ecd37 --- /dev/null +++ b/src/lib/shimagic/Shimeji.svelte @@ -0,0 +1,478 @@ + + + + +
+
+ + {#if loadError} +

{loadError}

+ {/if} +
+ + diff --git a/src/lib/shimagic/assets.ts b/src/lib/shimagic/assets.ts new file mode 100644 index 0000000..01db10d --- /dev/null +++ b/src/lib/shimagic/assets.ts @@ -0,0 +1,75 @@ +const files = import.meta.glob('$lib/assets/character/bubbles/**/*.png', { + eager: true, + query: '?url', + import: 'default' +}) as Record; + +const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }); +const BUBBLE_RE = /\/bubbles\/([^/]+)\/[^/]+\.png$/i; + +export interface BubblePack { + name: string; + frames: string[]; + fps: number; + duration: number; +} + +export interface BubblePackOptions { + fps?: number; + duration?: number; +} + +export function loadBubblePacks(opts: BubblePackOptions = {}): Record { + const { fps = 8, duration = 2.5 } = opts; + const groups = new Map>(); + + for (const [path, url] of Object.entries(files)) { + const m = BUBBLE_RE.exec(path); + if (!m) continue; + const name = m[1].toLowerCase(); + if (!groups.has(name)) groups.set(name, []); + groups.get(name)!.push([path, url]); + } + + const out: Record = {}; + for (const [name, entries] of groups) { + const frames = entries.sort(([a], [b]) => collator.compare(a, b)).map(([, url]) => url); + out[name] = { name, frames, fps, duration }; + } + return out; +} + +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/shimagic/chatter.ts b/src/lib/shimagic/chatter.ts new file mode 100644 index 0000000..36967cc --- /dev/null +++ b/src/lib/shimagic/chatter.ts @@ -0,0 +1,53 @@ +export interface ChatterConfig { + pack: string; + interval: [number, number]; + lines: string[]; + fontFamily?: string; + fontSize?: number; + color?: string; + align?: 'center' | 'left'; + padding?: { top?: number; right?: number; bottom?: number; left?: number }; + /** Distance from bubble top to the top of the first line, in sprite px. */ + textTop?: number; + lineHeight?: number; + /** Bubble frame index at which text appears. */ + textFrame?: number; + /** Typewriter speed in characters per second. */ + typeSpeed?: number; + /** Sound pack for typing clicks. */ + typeSound?: string; + typeSoundEvery?: number; + typeSoundVolume?: number; + /** Seconds the last frame holds after typing completes. */ + holdLast?: number; +} + +export const CHATTER: ChatterConfig = { + pack: 'chatter', + interval: [12, 28], + lines: [ + 'mrrrp?', + 'i could go for a nap', + 'nice day for it', + '...', + 'you again', + 'meow', + 'did you see that bird', + 'my bowl is looking empty', + 'i meant to do that', + 'five more minutes' + ], + fontFamily: "'Micro 5', sans-serif", + fontSize: 11, + color: '#1a1a1a', + align: 'center', + padding: { top: 8, right: 8, bottom: 8, left: 8 }, + textTop: 8, + lineHeight: 1.2, + textFrame: 1, + typeSpeed: 24, + typeSound: 'type', + typeSoundEvery: 2, + typeSoundVolume: 0.3, + holdLast: 1.6 +}; diff --git a/src/lib/shimagic/index.ts b/src/lib/shimagic/index.ts new file mode 100644 index 0000000..8bbb028 --- /dev/null +++ b/src/lib/shimagic/index.ts @@ -0,0 +1,43 @@ +export type { Facing, PhysicsInput } from './types'; + +export { collectStateUrls, loadStates, resolveStateName, STATE_CONFIG, StateClock } from './states'; +export type { + InteractionState, + ResolverConfig, + StateConfig, + StateConfigMap, + StateContext, + StatePack, + StateSide +} from './states'; + +export { ImageCache, loadBubblePacks } from './assets'; +export type { BubblePack, BubblePackOptions } from './assets'; + +export { clamp, Physics } from './physics'; +export type { PhysicsBounds, PhysicsConfig } from './physics'; + +export { KeyboardInput } from './input'; + +export { NEEDS, NeedsSimulator } from './needs'; +export type { + ActiveEvent, + ChatterHooks, + FiredEvent, + NeedBand, + NeedDef, + NeedsConfig, + NeedSideEffect +} from './needs'; + +export { CHATTER } from './chatter'; +export type { ChatterConfig } from './chatter'; + +export { CharacterRenderer } from './render'; +export type { RenderInput } from './render'; + +export { loadSoundPacks, SoundPlayer } from './sounds'; +export type { SoundPack } from './sounds'; + +export { INTERACTION, PointerController } from './interactions'; +export type { InteractionConfig, PointerBounds } from './interactions'; diff --git a/src/lib/shimagic/input.ts b/src/lib/shimagic/input.ts new file mode 100644 index 0000000..4492eba --- /dev/null +++ b/src/lib/shimagic/input.ts @@ -0,0 +1,67 @@ +const JUMP_KEYS = new Set([' ', 'w', 'arrowup']); +const MOVE_KEYS = new Set(['arrowleft', 'arrowright', 'a', 'd']); + +export class KeyboardInput { + private held = new Set(); + private jumpQueued = false; + private listeners: Array<[string, EventListener]> = []; + + attach(target: Window): void { + const down: EventListener = (e) => this.onKeyDown(e as KeyboardEvent); + const up: EventListener = (e) => this.onKeyUp(e as KeyboardEvent); + const blur: EventListener = () => this.clear(); + + target.addEventListener('keydown', down); + target.addEventListener('keyup', up); + target.addEventListener('blur', blur); + + this.listeners = [ + ['keydown', down], + ['keyup', up], + ['blur', blur] + ]; + } + + detach(target: Window): void { + for (const [type, fn] of this.listeners) target.removeEventListener(type, fn); + this.listeners = []; + } + + direction(): -1 | 0 | 1 { + let d = 0; + if (this.held.has('arrowleft') || this.held.has('a')) d -= 1; + if (this.held.has('arrowright') || this.held.has('d')) d += 1; + return d as -1 | 0 | 1; + } + + consumeJump(): boolean { + const j = this.jumpQueued; + this.jumpQueued = false; + return j; + } + + clear(): void { + this.held.clear(); + this.jumpQueued = false; + } + + private onKeyDown(e: KeyboardEvent): void { + const k = e.key.toLowerCase(); + + if (JUMP_KEYS.has(k)) { + e.preventDefault(); + if (!this.held.has(k)) this.jumpQueued = true; + this.held.add(k); + return; + } + + if (MOVE_KEYS.has(k)) { + e.preventDefault(); + this.held.add(k); + } + } + + private onKeyUp(e: KeyboardEvent): void { + this.held.delete(e.key.toLowerCase()); + } +} diff --git a/src/lib/shimagic/interactions.ts b/src/lib/shimagic/interactions.ts new file mode 100644 index 0000000..1038158 --- /dev/null +++ b/src/lib/shimagic/interactions.ts @@ -0,0 +1,266 @@ +import type { InteractionState } from './states'; + +export interface PointerBounds { + left: number; + top: number; + width: number; + height: number; +} + +export interface InteractionConfig { + enabled?: boolean; + landingDuration?: number; + petDelay?: number; + petLinger?: number; + petSoundInterval?: number; + pickupSound?: string; + dropSound?: string; + landingSound?: string; + purrSound?: string; + purrVolume?: number; + /** Hard cap on throw speed, px/s. Prevents a fast flick launching the cat off-screen. */ + maxThrowVelocity?: number; + /** Cursor-velocity smoothing, 0–1. Higher = twitchier throws, lower = smoother. */ + throwSmoothing?: number; +} + +export const INTERACTION: InteractionConfig = { + enabled: true, + landingDuration: 0.5, + petDelay: 0.25, + petLinger: 0.3, + petSoundInterval: 0.9, + pickupSound: 'pickup', + dropSound: 'drop', + landingSound: 'landing', + purrSound: 'purr', + purrVolume: 0.35, + maxThrowVelocity: 1200, + throwSmoothing: 0.35 +}; + +function clamp(v: number, lo: number, hi: number): number { + return Math.min(Math.max(v, lo), hi); +} + +function lerp(a: number, b: number, t: number): number { + return a + (b - a) * t; +} + +export class PointerController { + cursorX = 0; + cursorY = 0; + state: InteractionState = 'free'; + timeInState = 0; + + onGrab?: () => void; + onRelease?: () => void; + onLanding?: () => void; + onPetStart?: () => void; + onPetSound?: () => void; + + private cfg: Required< + Pick< + InteractionConfig, + | 'landingDuration' + | 'petDelay' + | 'petLinger' + | 'petSoundInterval' + | 'maxThrowVelocity' + | 'throwSmoothing' + > + > & { enabled: boolean }; + + private bounds: PointerBounds | null = null; + private grabAnchor: { x: number; y: number } | null = null; + private grabPointer = { x: 0, y: 0 }; + private hoverTime = 0; + private lingerTime = 0; + private purrTimer = 0; + private listeners: Array<[string, EventListener]> = []; + + // Cursor velocity tracking (screen coordinates, px/s). + private prevCursorX = 0; + private prevCursorY = 0; + private prevCursorSet = false; + private smoothVX = 0; + private smoothVY = 0; + + constructor(cfg: InteractionConfig) { + this.cfg = { + enabled: cfg.enabled ?? true, + landingDuration: cfg.landingDuration ?? 0.5, + petDelay: cfg.petDelay ?? 0.25, + petLinger: cfg.petLinger ?? 0.3, + petSoundInterval: cfg.petSoundInterval ?? 0.9, + maxThrowVelocity: cfg.maxThrowVelocity ?? 1200, + throwSmoothing: clamp(cfg.throwSmoothing ?? 0.35, 0.05, 1) + }; + } + + attach(target: Window): void { + if (!this.cfg.enabled) return; + + const down: EventListener = (e) => this.onPointerDown(e as PointerEvent); + const up: EventListener = () => this.onPointerUp(); + const move: EventListener = (e) => this.onPointerMove(e as PointerEvent); + const leave: EventListener = () => this.onPointerLeave(); + + const pairs: Array<[string, EventListener]> = [ + ['pointerdown', down], + ['pointerup', up], + ['pointermove', move], + ['pointerleave', leave] + ]; + for (const [type, fn] of pairs) target.addEventListener(type, fn); + this.listeners = pairs; + } + + detach(target: Window): void { + for (const [type, fn] of this.listeners) target.removeEventListener(type, fn); + this.listeners = []; + } + + setBounds(b: PointerBounds): void { + this.bounds = b; + } + + setGrabAnchor(x: number, y: number): void { + this.grabAnchor = { x, y }; + } + + getHeldPosition(): { x: number; y: number } | null { + if (this.state !== 'held' || !this.grabAnchor) return null; + const dx = this.cursorX - this.grabPointer.x; + const dy = this.cursorY - this.grabPointer.y; + return { x: this.grabAnchor.x + dx, y: this.grabAnchor.y - dy }; + } + + /** + * Cursor velocity at the moment of release, converted to internal coordinates. + * `x` matches screen x; `y` is flipped because internal y grows upward. + */ + getThrowVelocity(): { vx: number; vy: number } { + const cap = this.cfg.maxThrowVelocity; + return { + vx: clamp(this.smoothVX, -cap, cap), + vy: clamp(-this.smoothVY, -cap, cap) + }; + } + + setState(s: InteractionState): void { + if (this.state === s) return; + this.state = s; + this.timeInState = 0; + + if (s === 'held') this.onGrab?.(); + if (s === 'falling') this.onRelease?.(); + if (s === 'landing') this.onLanding?.(); + if (s === 'petted') { + this.purrTimer = 0; + this.onPetStart?.(); + } + } + + update(dt: number): void { + this.timeInState += dt; + + // Cursor velocity tracking. Only meaningful while held; otherwise decay + // to zero so a stale flick doesn't linger between grabs. + if (this.state === 'held' && this.prevCursorSet && dt > 0) { + const rawVX = (this.cursorX - this.prevCursorX) / dt; + const rawVY = (this.cursorY - this.prevCursorY) / dt; + const a = this.cfg.throwSmoothing; + this.smoothVX = lerp(this.smoothVX, rawVX, a); + this.smoothVY = lerp(this.smoothVY, rawVY, a); + } else if (this.state !== 'held') { + this.smoothVX = 0; + this.smoothVY = 0; + } + this.prevCursorX = this.cursorX; + this.prevCursorY = this.cursorY; + this.prevCursorSet = true; + + if (this.state === 'landing' && this.timeInState >= this.cfg.landingDuration) { + this.setState('free'); + } + + if (this.state === 'free') { + if (this.hoveringHead()) { + this.hoverTime += dt; + if (this.hoverTime >= this.cfg.petDelay) { + this.hoverTime = 0; + this.setState('petted'); + } + } else { + this.hoverTime = 0; + } + } else { + this.hoverTime = 0; + } + + if (this.state === 'petted') { + if (this.hoveringHead()) { + this.lingerTime = 0; + } else { + this.lingerTime += dt; + if (this.lingerTime >= this.cfg.petLinger) { + this.lingerTime = 0; + this.setState('free'); + } + } + + this.purrTimer += dt; + if (this.purrTimer >= this.cfg.petSoundInterval) { + this.purrTimer = 0; + this.onPetSound?.(); + } + } + } + + private hoveringHead(): boolean { + const b = this.bounds; + if (!b) return false; + return ( + this.cursorX >= b.left && + this.cursorX <= b.left + b.width && + this.cursorY >= b.top && + this.cursorY <= b.top + b.height / 2 + ); + } + + private hoveringBody(): boolean { + const b = this.bounds; + if (!b) return false; + return ( + this.cursorX >= b.left && + this.cursorX <= b.left + b.width && + this.cursorY >= b.top && + this.cursorY <= b.top + b.height + ); + } + + private onPointerDown(e: PointerEvent): void { + if (this.state !== 'free' && this.state !== 'petted') return; + this.cursorX = e.clientX; + this.cursorY = e.clientY; + if (!this.hoveringBody()) return; + + e.preventDefault(); + this.grabPointer = { x: this.cursorX, y: this.cursorY }; + this.setState('held'); + } + + private onPointerUp(): void { + if (this.state === 'held') this.setState('falling'); + } + + private onPointerMove(e: PointerEvent): void { + this.cursorX = e.clientX; + this.cursorY = e.clientY; + } + + private onPointerLeave(): void { + if (this.state === 'held') this.setState('falling'); + } +} diff --git a/src/lib/shimagic/needs.ts b/src/lib/shimagic/needs.ts new file mode 100644 index 0000000..c799403 --- /dev/null +++ b/src/lib/shimagic/needs.ts @@ -0,0 +1,338 @@ +import type { BubblePack } from './assets'; +import type { StatePack } from './states'; + +export interface NeedBand { + at: number; + bubble: string; + action?: string; + sound?: string; + soundVolume?: number; + bubbleDuration?: number; + /** Seconds after the bubble disappears that the action begins. */ + actionDelay?: number; + satisfyDuration?: number; + priority?: number; +} + +export interface NeedSideEffect { + need: string; + perSecond: number; +} + +export interface NeedDef { + id: string; + label: string; + riseRate: number; + max: number; + /** Multipliers on `riseRate` keyed by state name (idle, walk, run, jump, ...). */ + activityMultipliers: Record; + curve?: number; + bands: NeedBand[]; + resetBelow: number; + priority: number; + satisfyDuration: number; + satisfyTo: number; + satisfySideEffects?: NeedSideEffect[]; + /** Default bubbleDuration for this need's bands. */ + bubbleDuration?: number; + /** Default actionDelay for this need's bands. */ + actionDelay?: number; +} + +export const NEEDS: NeedDef[] = [ + { + id: 'thirst', + label: 'Thirst', + riseRate: 0.9, + max: 100, + activityMultipliers: { idle: 1, walk: 1.3, run: 2.0, jump: 1.6 }, + curve: 0.5, + bands: [ + { + at: 85, + bubble: 'thirst_urgent', + action: 'drink', + sound: 'thirst_urgent', + soundVolume: 0.6, + bubbleDuration: 1.6, + actionDelay: 0.4, + satisfyDuration: 4 + }, + { at: 50, bubble: 'thirst_mild', bubbleDuration: 2 } + ], + resetBelow: 15, + priority: 2, + satisfyDuration: 3, + satisfyTo: 0 + }, + { + id: 'boredom', + label: 'Boredom', + riseRate: 1.4, + max: 100, + activityMultipliers: { idle: 1.8, walk: 0.6, run: 0.3, jump: 0.5 }, + curve: 0.3, + bands: [ + { + at: 80, + bubble: 'bored_urgent', + action: 'play', + bubbleDuration: 1.6, + actionDelay: 0.4, + satisfyDuration: 5 + }, + { at: 40, bubble: 'bored_mild', bubbleDuration: 2 } + ], + resetBelow: 10, + priority: 1, + satisfyDuration: 4, + satisfyTo: 0 + }, + { + id: 'sleepiness', + label: 'Sleepiness', + riseRate: 0.6, + max: 100, + activityMultipliers: { idle: 1, walk: 1.2, run: 1.5, jump: 1.3 }, + curve: 0.4, + bands: [ + { + at: 90, + bubble: 'sleepy_urgent', + action: 'sleep', + bubbleDuration: 1.6, + actionDelay: 0.4, + satisfyDuration: 8 + }, + { at: 60, bubble: 'sleepy_mild', bubbleDuration: 2 } + ], + resetBelow: 5, + priority: 3, + satisfyDuration: 6, + satisfyTo: 0, + satisfySideEffects: [{ need: 'thirst', perSecond: 0.4 }] + } +]; + +export interface FiredEvent { + needId: string | null; + def: NeedDef | null; + band: NeedBand; + priority: number; + text?: string; +} + +export interface ActiveEvent { + needId: string | null; + def: NeedDef | null; + bubblePack: BubblePack | null; + actionState: StatePack | null; + elapsed: number; + totalDuration: number; + satisfyTo: number; + text?: string; + soundPack?: string | null; + soundVolume?: number; + lastCharsShown: number; + bubbleDuration: number; + actionDelay: number; + satisfyDuration: number; + actionStart: number; +} + +export interface ChatterHooks { + pack: string; + interval: [number, number]; + lines: string[]; + typeSpeed?: number; + typeSound?: string; + typeSoundEvery?: number; + typeSoundVolume?: number; + /** Total seconds the bubble stays up, computed by the caller. */ + bubbleDuration: (line: string, pack: BubblePack) => number; +} + +export interface NeedsConfig { + defs: NeedDef[]; + bubblePacks: Record; + states: Record; + chatter: ChatterHooks | null; + onSound: (name: string, volume: number) => void; +} + +const MAX_QUEUE = 8; + +export class NeedsSimulator { + values: Record = {}; + firedBands = new Set(); + queue: FiredEvent[] = []; + active: ActiveEvent | null = null; + chatterTimer = 0; + chatterTarget = -1; + private initialized = false; + + get isLocked(): boolean { + return !!this.active?.actionState && this.active.elapsed >= this.active.actionStart; + } + + step(dt: number, activity: string, cfg: NeedsConfig): void { + if (!cfg.defs.length) return; + + if (!this.initialized) { + for (const d of cfg.defs) this.values[d.id] = 0; + this.initialized = true; + } + + this.rise(dt, activity, cfg); + this.applySideEffects(dt, cfg); + this.checkBands(cfg); + this.maybeChatter(dt, cfg); + this.drainQueue(cfg); + this.advance(dt, cfg); + } + + private rise(dt: number, activity: string, cfg: NeedsConfig): void { + for (const def of cfg.defs) { + if (this.active?.needId === def.id) continue; + const v = this.values[def.id] ?? 0; + const mult = def.activityMultipliers[activity] ?? 1; + const curve = def.curve ? Math.pow(1 + v / def.max, def.curve) : 1; + this.values[def.id] = Math.min(def.max, v + def.riseRate * mult * curve * dt); + } + } + + private applySideEffects(dt: number, cfg: NeedsConfig): void { + const fx = this.active?.def?.satisfySideEffects; + if (!fx) return; + for (const e of fx) { + const other = cfg.defs.find((n) => n.id === e.need); + if (!other) continue; + const cur = this.values[other.id] ?? 0; + this.values[other.id] = Math.min(other.max, cur + e.perSecond * dt); + } + } + + private checkBands(cfg: NeedsConfig): void { + for (const def of cfg.defs) { + const v = this.values[def.id] ?? 0; + for (const band of def.bands) { + const key = `${def.id}:${band.at}`; + if (v >= band.at && !this.firedBands.has(key)) { + this.firedBands.add(key); + if (this.queue.length < MAX_QUEUE) { + this.queue.push({ + needId: def.id, + def, + band, + priority: band.priority ?? def.priority + }); + } + } else if (v < def.resetBelow && this.firedBands.has(key)) { + this.firedBands.delete(key); + } + } + } + } + + private maybeChatter(dt: number, cfg: NeedsConfig): void { + const c = cfg.chatter; + if (!c || !c.lines.length) return; + const pack = cfg.bubblePacks[c.pack]; + if (!pack) return; + + if (this.chatterTarget < 0) this.chatterTarget = randBetween(...c.interval); + + if (this.active || this.queue.length > 0) return; + + this.chatterTimer += dt; + if (this.chatterTimer < this.chatterTarget) return; + + this.chatterTimer = 0; + this.chatterTarget = randBetween(...c.interval); + + const line = c.lines[Math.floor(Math.random() * c.lines.length)]; + this.queue.push({ + needId: null, + def: null, + band: { + at: 0, + bubble: c.pack, + bubbleDuration: c.bubbleDuration(line, pack) + }, + priority: -1000, + text: line + }); + } + + private drainQueue(cfg: NeedsConfig): void { + if (this.queue.length > 1) this.queue.sort((a, b) => b.priority - a.priority); + if (this.active || !this.queue.length) return; + + const fired = this.queue.shift()!; + this.active = buildActiveEvent(fired, cfg); + + if (this.active.soundPack) { + cfg.onSound(this.active.soundPack, this.active.soundVolume ?? 1); + } + } + + private advance(dt: number, cfg: NeedsConfig): void { + const a = this.active; + if (!a) return; + + a.elapsed += dt; + + const c = cfg.chatter; + if (a.text && c?.typeSound && a.elapsed < a.bubbleDuration) { + const speed = c.typeSpeed ?? 0; + if (speed > 0) { + const charsShown = Math.min(a.text.length, Math.floor(a.elapsed * speed)); + const every = Math.max(1, c.typeSoundEvery ?? 2); + const before = Math.floor(a.lastCharsShown / every); + const now = Math.floor(charsShown / every); + if (now > before) cfg.onSound(c.typeSound, c.typeSoundVolume ?? 0.3); + a.lastCharsShown = charsShown; + } + } + + if (a.elapsed >= a.totalDuration) { + if (a.needId && a.def) this.values[a.needId] = a.satisfyTo; + this.active = null; + } + } +} + +function buildActiveEvent(fired: FiredEvent, cfg: NeedsConfig): ActiveEvent { + const bubblePack = fired.band.bubble ? (cfg.bubblePacks[fired.band.bubble] ?? null) : null; + const actionState = fired.band.action ? (cfg.states[fired.band.action] ?? null) : null; + + const bubbleDuration = + fired.band.bubbleDuration ?? fired.def?.bubbleDuration ?? bubblePack?.duration ?? 2.5; + const satisfyDuration = fired.band.satisfyDuration ?? fired.def?.satisfyDuration ?? 0; + const actionDelay = actionState ? (fired.band.actionDelay ?? fired.def?.actionDelay ?? 0.4) : 0; + + const actionStart = bubbleDuration + actionDelay; + const totalDuration = actionState ? actionStart + satisfyDuration : bubbleDuration; + + return { + needId: fired.needId, + def: fired.def, + bubblePack, + actionState, + elapsed: 0, + totalDuration, + satisfyTo: fired.def?.satisfyTo ?? 0, + text: fired.text, + soundPack: fired.band.sound ?? null, + soundVolume: fired.band.soundVolume ?? 1, + lastCharsShown: 0, + bubbleDuration, + actionDelay, + satisfyDuration, + actionStart + }; +} + +function randBetween(min: number, max: number): number { + return min + Math.random() * (max - min); +} diff --git a/src/lib/shimagic/physics.ts b/src/lib/shimagic/physics.ts new file mode 100644 index 0000000..d8bcbc4 --- /dev/null +++ b/src/lib/shimagic/physics.ts @@ -0,0 +1,102 @@ +import type { Facing, PhysicsInput } from './types'; + +export interface PhysicsConfig { + maxSpeed: number; + acceleration: number; + friction: number; + jumpVelocity: number; + gravity: number; + wrapEdges: boolean; +} + +export interface PhysicsBounds { + viewW: number; + viewH: number; + floorHeight: number; + spriteW: number; + scale: number; +} + +export function clamp(v: number, lo: number, hi: number): number { + return Math.min(Math.max(v, lo), hi); +} + +export class Physics { + x = 0; + vx = 0; + y = 0; + vy = 0; + grounded = true; + squash = 0; + facing: Facing = 'right'; + + place(viewW: number, fraction: number): void { + this.x = viewW * fraction; + } + + step(dt: number, input: PhysicsInput, cfg: PhysicsConfig, bounds: PhysicsBounds): void { + /* --- horizontal --- */ + if (input.direction !== 0) { + this.vx = clamp( + this.vx + input.direction * cfg.acceleration * dt, + -cfg.maxSpeed, + cfg.maxSpeed + ); + this.facing = input.direction > 0 ? 'right' : 'left'; + } else if (this.vx !== 0) { + // Air drag is much lighter than ground friction, so a thrown cat + // carries its momentum instead of stopping in a body length. + const f = this.grounded ? cfg.friction : cfg.friction * 0.15; + const drop = f * dt; + this.vx = Math.abs(this.vx) <= drop ? 0 : this.vx - Math.sign(this.vx) * drop; + } + + const target = this.x + this.vx * dt; + const bounded = this.boundX(target, cfg, bounds); + if (!cfg.wrapEdges && bounded !== target) this.vx = 0; + this.x = bounded; + + /* --- vertical --- */ + if (input.jump && this.grounded) { + this.vy = cfg.jumpVelocity; + this.grounded = false; + } + + if (!this.grounded) { + this.vy -= cfg.gravity * dt; + this.y += this.vy * dt; + if (this.y <= 0) { + const impact = -this.vy; + this.y = 0; + this.vy = 0; + this.grounded = true; + this.squash = clamp(impact / 900, 0, 1); + } + } + + if (this.squash > 0) this.squash = Math.max(0, this.squash - dt * 5); + } + + rebound(cfg: PhysicsConfig, bounds: PhysicsBounds): void { + this.x = this.boundX(this.x, cfg, bounds); + } + + groundY(bounds: PhysicsBounds): number { + return bounds.viewH - bounds.floorHeight; + } + + private boundX(value: number, cfg: PhysicsConfig, bounds: PhysicsBounds): number { + if (bounds.viewW <= 0) return value; + const half = (bounds.spriteW * bounds.scale) / 2; + + if (cfg.wrapEdges) { + const wrapWidth = bounds.viewW + bounds.spriteW * bounds.scale; + return ((((value + half) % wrapWidth) + wrapWidth) % wrapWidth) - half; + } + + const lo = half; + const hi = bounds.viewW - half; + if (hi <= lo) return bounds.viewW / 2; + return clamp(value, lo, hi); + } +} diff --git a/src/lib/shimagic/render.ts b/src/lib/shimagic/render.ts new file mode 100644 index 0000000..9cdb710 --- /dev/null +++ b/src/lib/shimagic/render.ts @@ -0,0 +1,228 @@ +import type { ChatterConfig } from './chatter'; + +export interface RenderInput { + ctx: CanvasRenderingContext2D; + viewW: number; + viewH: number; + groundY: number; + dpr: number; + + body: HTMLImageElement; + mirrored: boolean; + x: number; + y: number; + squash: number; + + bubble: { img: HTMLImageElement; index: number } | null; + bubbleText: string | null; + charsShown: number; + bubbleTextFrame: number; + + scale: number; + showShadow: boolean; + reflectionOpacity: number; + reflectionFade: number; + reflectionTint: string; + bubbleAnchorX: number; + bubbleAnchorY: number; + + chatter: ChatterConfig | null; +} + +export class CharacterRenderer { + private reflCanvas: HTMLCanvasElement | null = null; + private reflCtx: CanvasRenderingContext2D | null = null; + private reflW = 0; + private reflH = 0; + + draw(input: RenderInput): void { + const { ctx, viewW, viewH } = input; + ctx.clearRect(0, 0, viewW, viewH); + + const dw = input.body.naturalWidth * input.scale; + const dh = input.body.naturalHeight * input.scale; + const half = dw / 2; + + if (input.x + half <= 0 || input.x - half >= viewW) return; + + const leftX = Math.round(input.x - half); + const feetY = input.groundY - input.y; + const topY = feetY - dh; + + this.drawShadow(input, half); + this.drawReflection(input, leftX, dw, dh); + this.drawBody(input, leftX, feetY, dw, dh, half); + this.drawBubble(input, topY); + } + + private drawShadow(input: RenderInput, half: number): void { + if (!input.showShadow) return; + const { ctx, groundY, x, y } = input; + const t = Math.min(Math.max(y / 200, 0), 1); + const rx = half * 0.75 * (1 - t * 0.5); + const ry = Math.max(2, rx * 0.22); + ctx.save(); + ctx.globalAlpha = 0.32 * (1 - t * 0.85); + ctx.fillStyle = '#000'; + ctx.beginPath(); + ctx.ellipse(x, groundY, rx, ry, 0, 0, Math.PI * 2); + ctx.fill(); + ctx.restore(); + } + + private drawReflection(input: RenderInput, leftX: number, dw: number, dh: number): void { + const { y, reflectionOpacity, reflectionFade, reflectionTint, groundY, dpr } = input; + const heightFade = Math.max(0, 1 - y / (dh * 4)); + const alpha = Math.min(Math.max(reflectionOpacity * heightFade, 0), 1); + if (alpha <= 0.01) return; + + const rc = this.ensureRefl(dw, dh, dpr); + if (!rc) return; + + const pw = this.reflW; + const ph = this.reflH; + + rc.save(); + rc.translate(input.mirrored ? pw : 0, ph); + rc.scale(input.mirrored ? -1 : 1, -1); + rc.drawImage(input.body, 0, 0, pw, ph); + rc.restore(); + + rc.globalCompositeOperation = 'source-atop'; + rc.fillStyle = reflectionTint; + rc.fillRect(0, 0, pw, ph); + + rc.globalCompositeOperation = 'destination-out'; + const grad = rc.createLinearGradient(0, 0, 0, ph); + grad.addColorStop(0, 'rgba(0,0,0,0)'); + grad.addColorStop(1, `rgba(0,0,0,${Math.min(Math.max(reflectionFade, 0), 1)})`); + rc.fillStyle = grad; + rc.fillRect(0, 0, pw, ph); + rc.globalCompositeOperation = 'source-over'; + + input.ctx.globalAlpha = alpha; + input.ctx.drawImage(this.reflCanvas!, leftX, Math.round(groundY + input.y), dw, dh); + input.ctx.globalAlpha = 1; + } + + private drawBody( + input: RenderInput, + leftX: number, + feetY: number, + dw: number, + dh: number, + half: number + ): void { + const { ctx, mirrored, squash, body } = input; + const sx = 1 + squash * 0.22; + const sy = 1 - squash * 0.22; + ctx.save(); + ctx.translate(leftX + half, feetY); + ctx.scale(mirrored ? -sx : sx, sy); + ctx.drawImage(body, -half, -dh, dw, dh); + ctx.restore(); + } + + private drawBubble(input: RenderInput, topY: number): void { + const bf = input.bubble; + if (!bf) return; + const { ctx, scale, bubbleAnchorX, bubbleAnchorY, x, chatter } = input; + + const bw = bf.img.naturalWidth * scale; + const bh = bf.img.naturalHeight * scale; + const ax = x + bubbleAnchorX * scale; + const ay = topY - bubbleAnchorY * scale; + const bx = Math.round(ax - bw / 2); + const by = Math.round(ay - bh); + + ctx.drawImage(bf.img, bx, by, bw, bh); + + if (!input.bubbleText || !chatter) return; + if (bf.index < input.bubbleTextFrame) return; + drawBubbleText(ctx, input.bubbleText, bx, by, bw, bh, scale, input.charsShown, chatter); + } + + private ensureRefl(wCss: number, hCss: number, dpr: number): CanvasRenderingContext2D | null { + const pw = Math.max(1, Math.round(wCss * dpr)); + const ph = Math.max(1, Math.round(hCss * dpr)); + if (!this.reflCanvas) { + this.reflCanvas = document.createElement('canvas'); + this.reflCtx = this.reflCanvas.getContext('2d'); + } + if (!this.reflCtx) return null; + if (this.reflW !== pw || this.reflH !== ph) { + this.reflCanvas.width = pw; + this.reflCanvas.height = ph; + this.reflW = pw; + this.reflH = ph; + } + this.reflCtx.setTransform(1, 0, 0, 1, 0, 0); + this.reflCtx.globalCompositeOperation = 'source-over'; + this.reflCtx.globalAlpha = 1; + this.reflCtx.clearRect(0, 0, pw, ph); + this.reflCtx.imageSmoothingEnabled = false; + return this.reflCtx; + } +} + +function wrapText(c: 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 (c.measureText(candidate).width <= maxWidth) line = candidate; + else { + if (line) lines.push(line); + line = word; + } + } + if (line) lines.push(line); + return lines; +} + +function drawBubbleText( + c: CanvasRenderingContext2D, + text: string, + bx: number, + by: number, + bw: number, + bh: number, + scale: number, + charsShown: number, + chatter: ChatterConfig +): void { + const padLeft = (chatter.padding?.left ?? 8) * scale; + const padRight = (chatter.padding?.right ?? 8) * scale; + const padBottom = (chatter.padding?.bottom ?? 8) * scale; + const textTop = (chatter.textTop ?? chatter.padding?.top ?? 8) * scale; + + const maxW = bw - padLeft - padRight; + const maxH = bh - textTop - padBottom; + if (maxW <= 0 || maxH <= 0) return; + + const size = chatter.fontSize ?? 11; + const lineHeight = size * (chatter.lineHeight ?? 1.2); + + c.save(); + c.font = `${size}px ${chatter.fontFamily ?? 'monospace'}`; + c.textBaseline = 'top'; + c.textAlign = chatter.align === 'left' ? 'left' : 'center'; + c.fillStyle = chatter.color ?? '#1a1a1a'; + + const lines = wrapText(c, text, maxW); + const x = chatter.align === 'left' ? bx + padLeft : bx + bw / 2; + const y0 = by + textTop; + + 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; + c.fillText(line.slice(0, visible), x, y0 + i * lineHeight); + cursor += line.length; + if (visible < line.length) break; + } + + c.restore(); +} diff --git a/src/lib/shimagic/shimagic.ts b/src/lib/shimagic/shimagic.ts deleted file mode 100644 index c2cc07f..0000000 --- a/src/lib/shimagic/shimagic.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { WebG } from './renderer/web_g_engine'; - -export namespace Shimagic { - export class Shimeji { - private WebGEngine: WebG.Engine; - //private PhysisEngine: Physis.Engine; - private size!: number; - - private AnimID: number | null = null; - private pDeltaT: number = 0; - - constructor(webgengine: WebG.Engine /* physis: Physis.Engine */) { - this.WebGEngine = webgengine; - } - - /** - * Factory method: Initializes all sub-systems like WebG & Physis aswell as initializes the Shimeji and starts its animation - * @async - * @public - * @param {ShimejiConfig} config - Shimeji configuration - * @returns {Promise} that resolves when the Shimeji is done initializing - */ - public static async Initialize(config: ShimejiConfig): Promise { - const webg = await WebG.Engine.Initialize(config.webG); - //const physis = await Physis.Engine.Initialize(config.physis); - - const shimeji = new Shimeji(webg); - shimeji.size = config.size; - - const AFrame = (delta: number) => { - shimeji.pDeltaT = delta; - shimeji.AnimID = requestAnimationFrame(shimeji._anim); - }; - - shimeji.AnimID = requestAnimationFrame(AFrame); - - return shimeji; - } - - private _anim(delta: number) { - let dt = (delta - this.pDeltaT) / 1000; - dt = Math.min(dt, 0.05 /* * this.Physis.TIMESCALE */); - this.pDeltaT = delta; - - this.UpdatePhysics(dt); - this.UpdateFrame(dt); - - this.AnimID = requestAnimationFrame(this._anim); - } - - /** - * A function called automatically every "frame" where the code for calculating the next physics frame of the Shimeji is placed - * @param delta - Automatically passed in deltaT value; - */ - private UpdatePhysics(delta: number): void {} - - /** - * A function called automatically every "frame" where the code for drawing the next frame of the Shimeji is placed - * @param delta - Automatically passed in deltaT value; - */ - private UpdateFrame(delta: number): void {} - } - - interface ShimejiConfig { - sprite: string; //temp soultion to - size: number; - webG: WebG.EngineConfig; - //physis: Physis.EngineConfig; - } -} diff --git a/src/lib/shimagic/sounds.ts b/src/lib/shimagic/sounds.ts new file mode 100644 index 0000000..d8e06c0 --- /dev/null +++ b/src/lib/shimagic/sounds.ts @@ -0,0 +1,97 @@ +const SOUND_RE = /\/sounds\/([^/]+)\/[^/]+\.(wav|mp3|ogg)$/i; + +const files = import.meta.glob('$lib/assets/character/sounds/**/*.{wav,mp3,ogg}', { + eager: true, + query: '?url', + import: 'default' +}) as Record; + +export interface SoundPack { + name: string; + buffers: AudioBuffer[]; +} + +const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }); + +function soundPackUrls(): Record { + const groups: Record = {}; + + for (const [path, url] of Object.entries(files)) { + const m = SOUND_RE.exec(path); + if (!m) continue; + const name = m[1].toLowerCase(); + (groups[name] ??= []).push([path, url]); + } + + const out: Record = {}; + for (const [name, entries] of Object.entries(groups)) { + out[name] = entries.sort(([a], [b]) => collator.compare(a, b)).map(([, url]) => url); + } + return out; +} + +export async function loadSoundPacks(ctx: AudioContext): Promise> { + const urls = soundPackUrls(); + const out: Record = {}; + + await Promise.all( + Object.entries(urls).map(async ([name, list]) => { + const buffers: AudioBuffer[] = []; + for (const url of list) { + try { + const res = await fetch(url); + const raw = await res.arrayBuffer(); + buffers.push(await ctx.decodeAudioData(raw)); + } catch (err) { + console.warn(`[sound] failed to load "${url}"`, err); + } + } + if (buffers.length) out[name] = { name, buffers }; + }) + ); + + return out; +} + +export class SoundPlayer { + private cursor: Record = {}; + private muted = false; + + constructor( + private ctx: AudioContext, + private packs: Record + ) {} + + has(name: string): boolean { + return !!this.packs[name]; + } + + setMuted(muted: boolean) { + this.muted = muted; + } + + isMuted(): boolean { + return this.muted; + } + + play(name: string, volume = 1): void { + if (this.muted) return; + + const pack = this.packs[name]; + if (!pack || !pack.buffers.length) return; + + if (this.ctx.state === 'suspended') void this.ctx.resume(); + + const i = (this.cursor[name] ?? 0) % pack.buffers.length; + this.cursor[name] = i + 1; + + const src = this.ctx.createBufferSource(); + src.buffer = pack.buffers[i]; + + const gain = this.ctx.createGain(); + gain.gain.value = Math.max(0, Math.min(1, volume)); + + src.connect(gain).connect(this.ctx.destination); + src.start(); + } +} diff --git a/src/lib/shimagic/states.ts b/src/lib/shimagic/states.ts new file mode 100644 index 0000000..90a2eab --- /dev/null +++ b/src/lib/shimagic/states.ts @@ -0,0 +1,211 @@ +import type { Facing } from './types'; + +export type { Facing }; + +const files = import.meta.glob('$lib/assets/character/states/**/*.png', { + eager: true, + query: '?url', + import: 'default' +}) as Record; + +const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }); + +/** Matches states//.png OR states///.png */ +const STATE_RE = /\/states\/([^/]+)\/(?:(left|right)\/)?[^/]+\.png$/i; + +export interface StateSide { + frames: string[]; + /** True if these frames must be drawn flipped. */ + mirrored: boolean; +} + +export interface StatePack { + name: string; + fps: number; + left: StateSide; + right: StateSide; + /** Reference speed in px/s. When set, playback scales with |vx| / speed. */ + speed?: number; + /** If true, loops. If false, holds on the last frame after one pass. */ + loop: boolean; +} + +export interface StateConfig { + fps?: number; + speed?: number; + loop?: boolean; +} + +export type StateConfigMap = Record; + +export const STATE_CONFIG: StateConfigMap = { + idle: { fps: 6 }, + walk: { fps: 8, speed: 120 }, + run: { fps: 12, speed: 280 }, + jump: { fps: 8, loop: false }, + held: { fps: 8 }, + falling: { fps: 8 }, + landing: { fps: 8, loop: false }, + love: { fps: 8 }, + drink: { fps: 8, loop: false }, + play: { fps: 8, loop: false }, + sleep: { fps: 8, loop: false } +}; + +export function loadStates(config: StateConfigMap = {}): Record { + const merged: StateConfigMap = { ...STATE_CONFIG, ...config }; + + const grouped = new Map< + string, + { + left: Array<[string, string]>; + right: Array<[string, string]>; + flat: Array<[string, string]>; + } + >(); + + for (const [path, url] of Object.entries(files)) { + const m = STATE_RE.exec(path); + if (!m) continue; + const name = m[1].toLowerCase(); + const side = m[2]?.toLowerCase(); + + let bucket = grouped.get(name); + if (!bucket) { + bucket = { left: [], right: [], flat: [] }; + grouped.set(name, bucket); + } + if (side === 'left') bucket.left.push([path, url]); + else if (side === 'right') bucket.right.push([path, url]); + else bucket.flat.push([path, url]); + } + + const out: Record = {}; + + for (const [name, buckets] of grouped) { + const sortUrls = (arr: Array<[string, string]>) => + arr.sort(([a], [b]) => collator.compare(a, b)).map(([, url]) => url); + + const leftUrls = sortUrls(buckets.left); + const rightUrls = sortUrls(buckets.right); + const flatUrls = sortUrls(buckets.flat); + const cfg = merged[name] ?? {}; + + let left: StateSide; + let right: StateSide; + + if (leftUrls.length || rightUrls.length) { + if (leftUrls.length && rightUrls.length) { + left = { frames: leftUrls, mirrored: false }; + right = { frames: rightUrls, mirrored: false }; + } else if (leftUrls.length) { + left = { frames: leftUrls, mirrored: false }; + right = { frames: leftUrls, mirrored: true }; + } else { + right = { frames: rightUrls, mirrored: false }; + left = { frames: rightUrls, mirrored: true }; + } + } else if (flatUrls.length) { + left = { frames: flatUrls, mirrored: true }; + right = { frames: flatUrls, mirrored: false }; + } else { + continue; + } + + out[name] = { + name, + fps: cfg.fps ?? 8, + left, + right, + speed: cfg.speed, + loop: cfg.loop ?? true + }; + } + + return out; +} + +export function collectStateUrls(packs: Record): string[] { + const out = new Set(); + for (const pack of Object.values(packs)) { + for (const url of pack.left.frames) out.add(url); + for (const url of pack.right.frames) out.add(url); + } + return [...out]; +} + +/* ------------------------------------------------------------------ */ +/* State resolution */ +/* ------------------------------------------------------------------ */ + +export type InteractionState = 'free' | 'held' | 'falling' | 'landing' | 'petted'; + +export interface StateContext { + interaction: InteractionState; + grounded: boolean; + speed: number; + /** Active need-action state name (e.g. 'drink'), or null. */ + needAction: string | null; +} + +export interface ResolverConfig { + idleThreshold: number; + runThreshold: number; +} + +/** Interaction-state → state-pack-name overrides, in priority order. */ +const INTERACTION_MAP: Array<[InteractionState, string]> = [ + ['held', 'held'], + ['falling', 'falling'], + ['landing', 'landing'], + ['petted', 'love'] +]; + +export function resolveStateName( + ctx: StateContext, + cfg: ResolverConfig, + packs: Record +): string { + for (const [interactionState, packName] of INTERACTION_MAP) { + if (ctx.interaction === interactionState && packs[packName]) return packName; + } + + if (ctx.needAction && packs[ctx.needAction]) return ctx.needAction; + + if (!ctx.grounded && packs.jump) return 'jump'; + if (ctx.speed >= cfg.runThreshold && packs.run) return 'run'; + if (ctx.speed >= cfg.idleThreshold && packs.walk) return 'walk'; + return 'idle'; +} + +/* ------------------------------------------------------------------ */ +/* Animation clock */ +/* ------------------------------------------------------------------ */ + +export class StateClock { + private lastName = ''; + private elapsed = 0; + + update(dt: number, name: string, pack: StatePack | undefined, speed: number): void { + if (name !== this.lastName) { + this.lastName = name; + this.elapsed = 0; + return; + } + if (!pack) return; + + const rate = pack.speed && pack.speed > 0 ? Math.min(Math.max(speed / pack.speed, 0.25), 3) : 1; + this.elapsed += dt * rate; + } + + get time(): number { + return this.elapsed; + } + + frameIndex(pack: StatePack, side: StateSide): number { + const count = side.frames.length; + if (!count) return 0; + const raw = Math.floor(this.elapsed * pack.fps); + return pack.loop ? raw % count : Math.min(raw, count - 1); + } +} diff --git a/src/lib/shimagic/types.ts b/src/lib/shimagic/types.ts new file mode 100644 index 0000000..9d4f9d5 --- /dev/null +++ b/src/lib/shimagic/types.ts @@ -0,0 +1,36 @@ +export type Facing = 'left' | 'right'; +export type AnimName = 'idle' | 'walk' | 'run' | 'jump'; + +export interface Clip { + frames: string[]; + fps: number; + speed?: number; +} + +export interface FacingClips { + mirrored: boolean; + idle: Clip; + walk: Clip; + run?: Clip; + jump?: Clip; +} + +export type CharacterSprites = Record; + +export interface BubblePack { + name: string; + frames: string[]; + fps: number; + duration: number; +} + +export interface ActionPack { + name: string; + frames: string[]; + fps: number; +} + +export interface PhysicsInput { + direction: -1 | 0 | 1; + jump: boolean; +} diff --git a/src/lib/stores/petals.ts b/src/lib/stores/petals.ts new file mode 100644 index 0000000..b25b093 --- /dev/null +++ b/src/lib/stores/petals.ts @@ -0,0 +1,191 @@ +// $lib/stores/petals.ts + +function mulberry32(seed: number): () => number { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) | 0; + let t = Math.imul(a ^ (a >>> 15), 1 | a); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function accelPosition(u: number, k: number): number { + if (k < 0.01) return u * u; + if (k > 50) return u; + const denom = k - 1 + Math.exp(-k); + return (k * u - 1 + Math.exp(-k * u)) / denom; +} + +export interface PetalsOptions { + duration?: number; + fallAccel?: number; + fallDistance?: number; + leadIn?: number; + swayAmp?: number; + swayCycles?: number; + windX?: number; + spin?: number; + maxKeyframes?: number; + seed?: number; + hideOriginals?: boolean; +} + +export type PetalsCleanup = () => void; + +let callCounter = 0; + +function viewportBottom(): number { + const vv = window.visualViewport; + if (vv) return vv.height + vv.offsetTop; + return Math.max(document.documentElement.clientHeight, window.innerHeight); +} + +export function petals( + node: HTMLElement, + { + duration = 15000, + fallAccel = 4, + fallDistance, + leadIn = 0.18, + swayAmp = 22, + swayCycles = 2.0, + windX = 60, + spin = 300, + maxKeyframes = 90, + seed, + hideOriginals = true + }: PetalsOptions = {} +): PetalsCleanup { + const chars = Array.from(node.querySelectorAll('.char')).filter( + (el) => el.textContent?.trim() !== '' + ); + + if (chars.length === 0) return () => {}; + + const effectiveSeed = seed ?? Date.now() ^ (callCounter++ * 0x9e3779b9); + + const rect = node.getBoundingClientRect(); + const vb = viewportBottom(); + + // ── Clone + fixed overlay ──────────────────────────────────────────── + const clone = node.cloneNode(true) as HTMLElement; + clone.removeAttribute('id'); + clone.querySelectorAll('[id]').forEach((n) => n.removeAttribute('id')); + + clone.querySelectorAll('.prompt, .cursor').forEach((n) => { + n.style.visibility = 'hidden'; + }); + + clone.style.cssText = ` + position: fixed; + top: ${rect.top}px; + left: ${rect.left}px; + margin: 0; + overflow: visible; + pointer-events: none; + z-index: 9999; + contain: layout style; + `; + + const origFont = getComputedStyle(node); + clone.style.fontSize = origFont.fontSize; + clone.style.fontFamily = origFont.fontFamily; + clone.style.fontWeight = origFont.fontWeight; + clone.style.fontStyle = origFont.fontStyle; + clone.style.fontVariant = origFont.fontVariant; + clone.style.fontStretch = origFont.fontStretch; + clone.style.lineHeight = origFont.lineHeight; + clone.style.letterSpacing = origFont.letterSpacing; + clone.style.wordSpacing = origFont.wordSpacing; + clone.style.color = 'var(--color-text-primary)'; + clone.style.transition = 'var(--transition-standard)'; + + document.body.appendChild(clone); + + if (hideOriginals) { + chars.forEach((el) => { + el.style.visibility = 'hidden'; + }); + } + + const cloneChars = Array.from(clone.querySelectorAll('.char')); + const petalRects: DOMRect[] = []; + for (let i = 0; i < cloneChars.length; i++) { + petalRects.push(cloneChars[i].getBoundingClientRect()); + } + + const anims: Animation[] = []; + + cloneChars.forEach((el, i) => { + const rand = mulberry32(effectiveSeed + i * 100003); + + const charDuration = duration * (1.85 + rand() * 1.43); + const charAccel = fallAccel * (0.9 + rand() * 0.2); + const charSwayCycles = swayCycles * (0.7 + rand() * 0.7); + const charLeadIn = leadIn * (0.85 + rand() * 0.3); + + const phase = rand() * Math.PI * 2; + const dir: 1 | -1 = rand() < 0.5 ? -1 : 1; + const amp = swayAmp * (0.5 + rand() * 0.9); + const spinTotal = spin * (0.7 + rand() * 0.6) * dir; + const charWindX = windX * (0.5 + rand() * 1.0); + + let charFall: number; + if (fallDistance != null) { + charFall = fallDistance * (0.95 + rand() * 0.15); + } else { + const petalRect = petalRects[i]; + const neededFall = vb - petalRect.top + petalRect.height + 40; + charFall = neededFall * (1 + rand() * 0.35); + } + + const N = Math.min(maxKeyframes, Math.max(40, Math.round(charDuration / 200))); + const frames: Keyframe[] = []; + + for (let k = 0; k <= N; k++) { + const t = k / N; + const y = charFall * accelPosition(t, charAccel); + + const lead = Math.min(1, t / charLeadIn); + const leadSmooth = lead * lead * (3 - 2 * lead); + + const sway = amp * leadSmooth * Math.sin(2 * Math.PI * charSwayCycles * t + phase); + const wind = charWindX * t; + const x = sway + wind; + + const r = spinTotal * t; + + frames.push({ + transform: `translate(${x.toFixed(2)}px, ${y.toFixed(2)}px) rotate(${r.toFixed(2)}deg)`, + offset: t + }); + } + + anims.push( + el.animate(frames, { + duration: charDuration, + delay: 0, + easing: 'linear', + fill: 'forwards' + }) + ); + }); + + let cleaned = false; + const doCleanup = (): void => { + if (cleaned) return; + cleaned = true; + for (const a of anims) a.cancel(); + clone.remove(); + if (hideOriginals) { + chars.forEach((el) => { + el.style.visibility = ''; + }); + } + }; + + void Promise.allSettled(anims.map((a) => a.finished)).then(doCleanup); + + return doCleanup; +} diff --git a/src/lib/stores/shimeji2.ts b/src/lib/stores/shimeji2.ts index 3c0dc08..9c70d59 100644 --- a/src/lib/stores/shimeji2.ts +++ b/src/lib/stores/shimeji2.ts @@ -1,336 +1,370 @@ -import Vector2 from "../vector"; - export class Shimeji { - private element: HTMLElement; - private canvas: HTMLCanvasElement; - private rect: DOMRect; - - private pos: Vector2 = Vector2.zero; - private vel: Vector2 = Vector2.zero; + private element: HTMLElement; - private angle: number = 0; // radians - private angularVelocity: number = 0; // rad/s - private inertia: number; // kg·m² - private localGrip: Vector2 = Vector2.zero; // offset from center (body‑fixed) + // Position and velocity + private x: number = 0; + private y: number = 0; + private velocityX: number = 0; + private velocityY: number = 0; - private mousePos: Vector2 = Vector2.zero; + // Mouse tracking + private mouseX: number = 0; + private mouseY: number = 0; + private mouseAccelX: number = 0; + private mouseAccelY: number = 0; - private pivot: Vector2 = Vector2.zero; + // Throw detection - track mouse movement history + private mouseHistory: Array<{ x: number; y: number; time: number }> = []; + private readonly HISTORY_LENGTH: number = 5; - private isBeingDragged: boolean = false; - - private rafId: number | null = null; - private prevDeltaTime: number = 0; + private isBeingDragged: boolean = false; + private rafId: number | null = null; - private readonly RESTITUTION: number = 0.6; - private readonly STIFFNESS: number = 500; - private readonly DAMPING: number = 1; - private readonly MASS: number = 10.0; - private readonly FRICTION: number = 0.9; - private readonly GRAVITY: number = 10; - - private bounds: { minX: number; minY: number; maxX: number; maxY: number }; - - constructor(element: HTMLElement, canvas: HTMLCanvasElement) { - this.element = element; - this.canvas= canvas; - this.rect = element.getBoundingClientRect(); - - this.bounds = { - minX: 0, - minY: 0, - maxX: window.innerWidth, - maxY: window.innerHeight - }; + // Physics parameters + private readonly STIFFNESS: number = 0.85; + private readonly DAMPING: number = 0.6; + private readonly MASS: number = 1.0; - this.inertia = (1 / 12) * - this.MASS * (this.rect.width * this.rect.width + this.rect.height * this.rect.height); - - this.pos.set(window.innerWidth / 2, window.innerHeight/ 2); - - this.updateBounds(); - window.addEventListener('resize', () => this.updateBounds()); + // Gravity (pixels per frame squared) + private gravity: number = 10; - console.log(this.element.getBoundingClientRect()); - - this.setupDragEvents(); - } - - private updateBounds(): void { - this.bounds = { - minX: 0, - minY: 0, - maxX: window.innerWidth, - maxY: window.innerHeight - }; - - this.canvas.width = window.innerWidth; - this.canvas.height = window.innerHeight; - } - - start(): void { - if (this.rafId !== null) return; + // Bounce coefficients (energy retention - lower = less bounce) + private readonly WALL_BOUNCE: number = 0.5; // Walls lose 50% energy + private readonly FLOOR_BOUNCE: number = 0.6; // Floor loses 40% energy (realistic) + private readonly CEILING_BOUNCE: number = 0.4; // Ceiling loses 60% energy - const firstFrame = (delta: number) => { - this.prevDeltaTime = delta; - this.rafId = requestAnimationFrame(animate); - } + // Minimum velocity to continue bouncing + private readonly MIN_BOUNCE_VELOCITY: number = 2; - const animate = (delta: number) => { - const dt: number = Math.min(delta - this.prevDeltaTime, 0.05); - this.prevDeltaTime = delta; + // Boundaries + private bounds: { minX: number; minY: number; maxX: number; maxY: number }; - this.updatePhysics(dt); - this.applyBoundaries(); - this.render(); - this.rafId = requestAnimationFrame(animate); - }; - - this.rafId = requestAnimationFrame(firstFrame); - } - - stop(): void { - if (this.rafId !== null) { - cancelAnimationFrame(this.rafId); - this.rafId = null; - } - } + // Optional forces + private wind: number = 0; + private friction: number = 0.98; - private getCornerWorld(lx: number, ly: number): Vector2 { - // lx, ly are in local coordinates (relative to center, with rotation) - const cos = Math.cos(this.angle); - const sin = Math.sin(this.angle); - return new Vector2( - this.pos.x + (lx * cos - ly * sin), - this.pos.y + (lx * sin + ly * cos) - ); - } + // Track if on ground for additional effects + private wasOnGround: boolean = false; + private bounceCount: number = 0; - private setupDragEvents(): void { - this.element.addEventListener('mousedown', (e) => { - e.preventDefault(); - this.isBeingDragged = true; - this.element.style.cursor = 'grabbing'; + constructor(element: HTMLElement) { + this.element = element; - const parent = this.element.parentElement; - if(parent) parent.style.cursor = 'grabbing'; + // Initialize bounds (will update on resize) + this.bounds = { + minX: 0, + minY: 0, + maxX: window.innerWidth, + maxY: window.innerHeight + }; - const clickWorld = new Vector2(e.pageX, e.pageY); - const center = this.pos; - const offset = clickWorld.sub(center) - const cos = Math.cos(-this.angle); - const sin = Math.sin(-this.angle); + // Start with element at center + this.x = window.innerWidth / 2; + this.y = window.innerHeight / 2; - this.localGrip = new Vector2( - offset.x * cos - offset.y * sin, - offset.x * sin + offset.y * cos - ); + this.updateBounds(); + window.addEventListener('resize', () => this.updateBounds()); - this.pivot.x = e.offsetX - this.rect.width / 2; - this.pivot.y = e.offsetY - this.rect.height / 2; - - }); + this.setupDragEvents(); + } - document.addEventListener('mousemove', (e) => { - this.mousePos.x = e.pageX; - this.mousePos.y = e.pageY; - }); + private updateBounds(): void { + this.bounds = { + minX: 0, + minY: 0, + maxX: window.innerWidth, + maxY: window.innerHeight + }; + } - document.addEventListener('mouseup', (e) => { - if(this.isBeingDragged) { - this.isBeingDragged = false; - this.element.style.cursor = 'grab'; + start(): void { + if (this.rafId !== null) return; - const parent = this.element.parentElement; - if(parent) parent.style.cursor = 'auto'; + const animate = () => { + this.updatePhysics(); + this.applyBoundaries(); + this.render(); + this.rafId = requestAnimationFrame(animate); + }; - this.pivot = Vector2.zero; - } + this.rafId = requestAnimationFrame(animate); + } - this.canvas.getContext('2d')!.clearRect(0, 0, this.canvas.width, this.canvas.height); - }); + stop(): void { + if (this.rafId !== null) { + cancelAnimationFrame(this.rafId); + this.rafId = null; + } + } - this.element.addEventListener('dragstart', (e) => { - e.preventDefault(); - }); - } - - private updatePhysics(dt: number): void { + private setupDragEvents(): void { + this.element.addEventListener('mousedown', (e) => { + e.preventDefault(); + this.isBeingDragged = true; + this.element.style.cursor = 'grabbing'; - const cos = Math.cos(this.angle); - const sin = Math.sin(this.angle); - const gripWorld = new Vector2( - this.pos.x + (this.localGrip.x * cos - this.localGrip.y * sin), - this.pos.y + (this.localGrip.x * sin + this.localGrip.y * cos) - ); + // Clear mouse history on new drag + this.mouseHistory = []; + }); - if (this.isBeingDragged) { - const direction: Vector2 = this.mousePos.sub(gripWorld); - - const force: Vector2 = direction.mul(this.STIFFNESS); + // Track mouse movement globally for better throw detection + document.addEventListener('mousemove', (e) => { + if (this.isBeingDragged) { + this.mouseX = e.pageX; + this.mouseY = e.pageY; + this.mouseAccelX = e.movementX; + this.mouseAccelY = e.movementY; - const acceleration: Vector2 = force.div(this.MASS).deadZone(0.001); - - acceleration.mulEq(dt); + // Store mouse position history for throw calculation + this.mouseHistory.push({ + x: e.pageX, + y: e.pageY, + time: Date.now() + }); - this.vel.addEq(acceleration); - this.vel.mulEq(0.8); + // Keep only recent history + if (this.mouseHistory.length > this.HISTORY_LENGTH) { + this.mouseHistory.shift(); + } + } + }); - const r = gripWorld.sub(this.pos); - const torque = r.cross(force); - this.angularVelocity += (torque / this.inertia) * dt; - } - - this.vel.y += this.GRAVITY; - this.vel.mulEq(this.DAMPING); - - if (this.pos.y + this.rect.width >= this.bounds.maxY) { - this.vel.x *= this.FRICTION; - } + this.element.addEventListener('mouseup', (e) => { + if (this.isBeingDragged) { + this.isBeingDragged = false; + this.element.style.cursor = 'grab'; - const outVel = this.vel.mul(dt); - this.pos.addEq(outVel); + // Calculate throw velocity based on mouse movement speed + this.applyThrowVelocity(); - this.angle += this.angularVelocity * dt; - this.angle %= 2 * Math.PI; - } - - private applyBoundaries(): void { - const w = this.rect.width / 2; - const h = this.rect.height / 2; + // Reset mouse history + this.mouseHistory = []; + } + }); - // List of corners in local coordinates (four combinations) - const corners = [ - { lx: w, ly: h }, // top‑right - { lx: w, ly: -h }, // bottom‑right - { lx: -w, ly: h }, // top‑left - { lx: -w, ly: -h } // bottom‑left - ]; + this.element.addEventListener('dragstart', (e) => { + e.preventDefault(); + }); + } - // Check each wall - // Left wall (x = leftBound) - const leftBound = w; - for (const corner of corners) { - const world = this.getCornerWorld(corner.lx, corner.ly); - if (world.x < leftBound) { - // Penetration depth (distance from wall to corner) - const penetration = leftBound - world.x; - // Normal points to the right (+x) - const normal = new Vector2(1, 0); - // Contact point is the wall at corner's y (or clamp to avoid escaping) - const contactY = Math.min(Math.max(world.y, this.bounds.minY + h), this.bounds.maxY - h); - const contactPoint = new Vector2(leftBound, contactY); - this.resolveCollision(normal, contactPoint); - // Reposition to avoid continuous penetration - this.pos.x = leftBound - w; - return; // after one correction, stop checking further walls to avoid multiple impulses - } - } + private applyThrowVelocity(): void { + if (this.mouseHistory.length < 2) return; - // Right wall (x = rightBound) - const rightBound = this.bounds.maxX - w; - for (const corner of corners) { - const world = this.getCornerWorld(corner.lx, corner.ly); - if (world.x > rightBound) { - const penetration = world.x - rightBound; - const normal = new Vector2(-1, 0); - const contactY = Math.min(Math.max(world.y, this.bounds.minY + h), this.bounds.maxY - h); - const contactPoint = new Vector2(rightBound, contactY); - this.resolveCollision(normal, contactPoint); - this.pos.x = rightBound + w; - return; - } - } + // Get oldest and newest mouse positions + const oldest = this.mouseHistory[0]; + const newest = this.mouseHistory[this.mouseHistory.length - 1]; - // Top wall (y = topBound) - const topBound = h; - for (const corner of corners) { - const world = this.getCornerWorld(corner.lx, corner.ly); - if (world.y < topBound) { - const penetration = topBound - world.y; - const normal = new Vector2(0, 1); - const contactX = Math.min(Math.max(world.x, leftBound), rightBound); - const contactPoint = new Vector2(contactX, topBound); - this.resolveCollision(normal, contactPoint); - this.pos.y = topBound - h; - return; - } - } + // Calculate time delta in seconds + const timeDelta = (newest.time - oldest.time) / 1000; + if (timeDelta === 0) return; - // Bottom wall (y = bottomBound) - const bottomBound = this.bounds.maxY - h; - for (const corner of corners) { - const world = this.getCornerWorld(corner.lx, corner.ly); - if (world.y > bottomBound) { - const penetration = world.y - bottomBound; - const normal = new Vector2(0, -1); - const contactX = Math.min(Math.max(world.x, leftBound), rightBound); - const contactPoint = new Vector2(contactX, bottomBound); - this.resolveCollision(normal, contactPoint); - this.pos.y = bottomBound + h; - return; - } - } + // Calculate velocity in pixels per second + let throwVelX = (newest.x - oldest.x) / timeDelta; + let throwVelY = (newest.y - oldest.y) / timeDelta; + + // Cap maximum throw velocity to prevent ridiculous speeds + const MAX_THROW_SPEED = 50; + throwVelX = Math.min(Math.max(throwVelX, -MAX_THROW_SPEED), MAX_THROW_SPEED); + throwVelY = Math.min(Math.max(throwVelY, -MAX_THROW_SPEED), MAX_THROW_SPEED); + + // Apply throw velocity (divide by ~60 to convert from per-second to per-frame) + this.velocityX += throwVelX / 60; + this.velocityY += throwVelY / 60; + + // Add a little extra oomph based on acceleration + if (Math.abs(this.mouseAccelX) > 5) { + this.velocityX += this.mouseAccelX / 30; + } + if (Math.abs(this.mouseAccelY) > 5) { + this.velocityY += this.mouseAccelY / 30; + } + } + + private updatePhysics(): void { + // Apply spring force toward mouse when dragging + if (this.isBeingDragged) { + const dx = this.mouseX - this.x; + const dy = this.mouseY - this.y; + + const forceX = dx * this.STIFFNESS; + const forceY = dy * this.STIFFNESS; + + // Apply force to acceleration (F = ma) + const accelerationX = (forceX + this.mouseAccelX) / this.MASS; + const accelerationY = (forceY + this.mouseAccelY) / this.MASS; + + // Update velocity with acceleration + this.velocityX += accelerationX; + this.velocityY += accelerationY; + } + + // Apply gravity (always present, but stronger when not dragging) + if (!this.isBeingDragged) { + this.velocityY += this.gravity; + } else { + // Slight gravity even when dragging for realism + this.velocityY += this.gravity * 0.3; + } + + // Apply wind (optional horizontal force) + if (this.y > 10) this.velocityX += this.wind; + + // Apply damping (air resistance) + this.velocityX *= this.DAMPING; + this.velocityY *= this.DAMPING; + + // Update position with velocity + this.x += this.velocityX; + this.y += this.velocityY; + } + + private getElementHeight(): number { + return this.element.offsetHeight; + } + + private getElementWidth(): number { + return this.element.offsetWidth; + } + + private applyBoundaries(): void { + const elementWidth = this.getElementWidth(); + const elementHeight = this.getElementHeight(); + + // X-axis boundaries with realistic bounce + const leftBound = elementWidth / 2; + const rightBound = this.bounds.maxX - elementWidth / 2; + + if (this.x < leftBound) { + this.x = leftBound; + // Bounce with energy loss + this.velocityX = -Math.abs(this.velocityX) * this.WALL_BOUNCE; + + // Stop if bounce is too small + if (Math.abs(this.velocityX) < this.MIN_BOUNCE_VELOCITY) { + this.velocityX = 0; + } + } else if (this.x > rightBound) { + this.x = rightBound; + this.velocityX = -Math.abs(this.velocityX) * this.WALL_BOUNCE; + + if (Math.abs(this.velocityX) < this.MIN_BOUNCE_VELOCITY) { + this.velocityX = 0; + } + } + + // Y-axis boundaries with realistic bounce + const topBound = elementHeight / 2; + const bottomBound = this.bounds.maxY - elementHeight / 2; + + // Ceiling collision + if (this.y < topBound) { + this.y = topBound; + this.velocityY = -this.velocityY * this.CEILING_BOUNCE; + + // Stop tiny bouncing on ceiling + if (Math.abs(this.velocityY) < this.MIN_BOUNCE_VELOCITY) { + this.velocityY = 0; + } + } + // Floor collision + else if (this.y > bottomBound) { + this.y = bottomBound; + + const impactSpeed = Math.abs(this.velocityY); + + // Only bounce if impact speed is significant + if (impactSpeed > this.MIN_BOUNCE_VELOCITY) { + // Apply floor bounce with energy loss + this.velocityY = -this.velocityY * this.FLOOR_BOUNCE; + + // Bounce gets smaller each time naturally due to energy loss + this.bounceCount++; + + // Apply ground friction on bounce + this.velocityX *= this.groundFriction; + + // Optional: Visual feedback for bounce + // console.log(`Bounce ${this.bounceCount}: impact speed ${impactSpeed.toFixed(2)}, new velocity ${this.velocityY.toFixed(2)}`); + } else { + // Stop bouncing when energy is too low + this.velocityY = 0; + this.wasOnGround = true; + } + } else { + this.wasOnGround = false; + // Reset bounce count when in air + if (!this.isBeingDragged && this.velocityY !== 0) { + this.bounceCount = 0; + } + } + } + + private get groundFriction(): number { + // More friction when moving fast + const speed = Math.abs(this.velocityX); + if (speed > 10) return this.friction * 0.9; + if (speed > 5) return this.friction * 0.95; + return this.friction; + } + + private render(): void { + this.element.style.transform = `translate(${this.x}px, ${this.y}px) translateY(-50%)`; + } + + // Public methods to control physics + setGravity(value: number): void { + this.gravity = value; + } + + setWind(value: number): void { + this.wind = value; + } + + setPhysics(stiffness: number, damping: number, mass: number = 1.0): void { + (this as any).STIFFNESS = stiffness; + (this as any).DAMPING = damping; + (this as any).MASS = mass; + } + + setFriction(value: number): void { + this.friction = value; + } + + // Configure bounce properties + setBounceProperties(wall: number, floor: number, ceiling: number = 0.4): void { + (this as any).WALL_BOUNCE = Math.min(Math.max(wall, 0), 1); + (this as any).FLOOR_BOUNCE = Math.min(Math.max(floor, 0), 1); + (this as any).CEILING_BOUNCE = Math.min(Math.max(ceiling, 0), 1); + } + + // Add impulse (like a jump) + addImpulse(x: number, y: number): void { + this.velocityX += x; + this.velocityY += y; + } + + // Reset position + resetPosition(x?: number, y?: number): void { + this.x = x ?? this.bounds.maxX / 2; + this.y = y ?? this.bounds.maxY / 2; + this.velocityX = 0; + this.velocityY = 0; + this.isBeingDragged = false; + this.bounceCount = 0; + } + + getState() { + return { + x: this.x, + y: this.y, + velocityX: this.velocityX, + velocityY: this.velocityY, + mouseX: this.mouseX, + mouseY: this.mouseY, + isBeingDragged: this.isBeingDragged, + isOnGround: this.wasOnGround, + bounceCount: this.bounceCount + }; + } } - - private resolveCollision(normal: Vector2, contactPoint: Vector2): void { - // Vector from center to contact point - const r = contactPoint.sub(this.pos); - - // Velocity of the contact point - const v_rel = this.vel.clone(); - // Add tangential component from angular velocity: ω × r - v_rel.x -= this.angularVelocity * r.y; - v_rel.y += this.angularVelocity * r.x; - - // Relative velocity along normal - const vn = v_rel.dot(normal); - if (vn > 0) return; // Already separating - - // Impulse numerator - const numerator = -(1 + this.RESTITUTION) * vn; - - // Denominator: 1/m + (r × n)^2 / I - const r_cross_n = r.cross(normal); - const denominator = 1 / this.MASS + (r_cross_n * r_cross_n) / this.inertia; - - const j = numerator / denominator; - const impulse = normal.mul(j); - - // Apply impulse - this.vel.addEq(impulse.div(this.MASS)); - this.angularVelocity += r.cross(impulse) / this.inertia; - } - - private drawRay(pos1: {x: number, y: number}, pos2: {x: number, y: number}) { - const ctx = this.canvas.getContext("2d")!; - ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); - ctx.strokeStyle = "white"; - ctx.lineWidth = 0.1 - ctx.beginPath(); - ctx.moveTo(pos1.x, pos1.y); - ctx.lineTo(pos2.x, pos2.y); - ctx.stroke(); - } - - private render(): void { - this.element.style.transform = `translate(${this.pos.x}px, ${this.pos.y}px) rotate(${this.angle * 180 / Math.PI}deg)`; - - /* if(this.isBeingDragged) { - this.drawRay( - {x: this.mousePos.x, y: this.mousePos.y}, - {x: this.pos.x + this.pivot.x, y: this.pos.y + this.pivot.y} - ) - } */ - } - - addImpulse(x: number, y: number): void { - this.vel.x += x; - this.vel.y += y; - } - - moveTo(pos: number) { - - } -} \ No newline at end of file diff --git a/src/modules/Shimeji.svelte b/src/modules/Shimeji.svelte deleted file mode 100644 index 1ec5cb7..0000000 --- a/src/modules/Shimeji.svelte +++ /dev/null @@ -1,90 +0,0 @@ - - -
- - -
diff --git a/src/modules/Terminal.svelte b/src/modules/Terminal.svelte index 155aeba..2c776d6 100644 --- a/src/modules/Terminal.svelte +++ b/src/modules/Terminal.svelte @@ -1,12 +1,10 @@ -