dunut2
@@ -9,6 +9,7 @@
|
|||||||
"version": "0.0.69",
|
"version": "0.0.69",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@lucide/svelte": "^0.548.0",
|
"@lucide/svelte": "^0.548.0",
|
||||||
|
"animejs": "^4.5.0",
|
||||||
"gl-matrix": "^3.4.4",
|
"gl-matrix": "^3.4.4",
|
||||||
"zod": "^4.3.6"
|
"zod": "^4.3.6"
|
||||||
},
|
},
|
||||||
@@ -2189,6 +2190,28 @@
|
|||||||
"url": "https://github.com/sponsors/epoberezkin"
|
"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": {
|
"node_modules/ansi-regex": {
|
||||||
"version": "5.0.1",
|
"version": "5.0.1",
|
||||||
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
|
||||||
|
|||||||
@@ -52,6 +52,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@lucide/svelte": "^0.548.0",
|
"@lucide/svelte": "^0.548.0",
|
||||||
|
"animejs": "^4.5.0",
|
||||||
"gl-matrix": "^3.4.4",
|
"gl-matrix": "^3.4.4",
|
||||||
"zod": "^4.3.6"
|
"zod": "^4.3.6"
|
||||||
}
|
}
|
||||||
|
|||||||
|
After Width: | Height: | Size: 158 B |
|
After Width: | Height: | Size: 158 B |
|
After Width: | Height: | Size: 158 B |
|
After Width: | Height: | Size: 205 B |
|
After Width: | Height: | Size: 597 B |
|
After Width: | Height: | Size: 560 B |
|
After Width: | Height: | Size: 615 B |
|
After Width: | Height: | Size: 597 B |
|
After Width: | Height: | Size: 628 B |
|
After Width: | Height: | Size: 585 B |
|
After Width: | Height: | Size: 604 B |
|
After Width: | Height: | Size: 601 B |
|
After Width: | Height: | Size: 632 B |
|
After Width: | Height: | Size: 612 B |
|
After Width: | Height: | Size: 467 B |
|
After Width: | Height: | Size: 471 B |
|
After Width: | Height: | Size: 471 B |
|
After Width: | Height: | Size: 476 B |
|
After Width: | Height: | Size: 468 B |
|
After Width: | Height: | Size: 459 B |
|
After Width: | Height: | Size: 472 B |
|
After Width: | Height: | Size: 628 B |
|
After Width: | Height: | Size: 649 B |
|
After Width: | Height: | Size: 638 B |
|
After Width: | Height: | Size: 656 B |
|
After Width: | Height: | Size: 648 B |
|
After Width: | Height: | Size: 640 B |
|
After Width: | Height: | Size: 629 B |
|
After Width: | Height: | Size: 628 B |
|
After Width: | Height: | Size: 639 B |
|
After Width: | Height: | Size: 657 B |
|
After Width: | Height: | Size: 645 B |
|
After Width: | Height: | Size: 654 B |
@@ -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<MWinState>({
|
||||||
|
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 = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -1,10 +1,5 @@
|
|||||||
import { drizzle } from 'drizzle-orm/mysql2';
|
//if (!env.DATABASE_URL) throw new Error('DATABASE_URL is not set');
|
||||||
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');
|
//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 });
|
|
||||||
|
|||||||
@@ -0,0 +1,382 @@
|
|||||||
|
|
||||||
|
// this file is generated — do not edit it
|
||||||
|
|
||||||
|
|
||||||
|
/// <reference types="@sveltejs/kit" />
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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';
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export const matchers = {};
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export { default as component } from "../../../../../../../node_modules/@sveltejs/kit/src/runtime/components/svelte-5/layout.svelte";
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export { default as component } from "../../../../../../../node_modules/@sveltejs/kit/src/runtime/components/svelte-5/error.svelte";
|
||||||
@@ -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"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,478 @@
|
|||||||
|
<script lang="ts">
|
||||||
|
import { onMount } from 'svelte';
|
||||||
|
import {
|
||||||
|
CharacterRenderer,
|
||||||
|
INTERACTION,
|
||||||
|
ImageCache,
|
||||||
|
KeyboardInput,
|
||||||
|
NeedsSimulator,
|
||||||
|
Physics,
|
||||||
|
PointerController,
|
||||||
|
SoundPlayer,
|
||||||
|
StateClock,
|
||||||
|
collectStateUrls,
|
||||||
|
loadSoundPacks,
|
||||||
|
resolveStateName,
|
||||||
|
type BubblePack,
|
||||||
|
type ChatterConfig,
|
||||||
|
type InteractionConfig,
|
||||||
|
type StatePack
|
||||||
|
} from './';
|
||||||
|
import { CHATTER } from './chatter';
|
||||||
|
import { NEEDS, type ChatterHooks, type NeedDef } from './needs';
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
states: Record<string, StatePack>;
|
||||||
|
bubblePacks?: Record<string, BubblePack>;
|
||||||
|
needsConfig?: NeedDef[];
|
||||||
|
chatter?: ChatterConfig | null;
|
||||||
|
interactions?: InteractionConfig;
|
||||||
|
scale?: number;
|
||||||
|
maxSpeed?: number;
|
||||||
|
idleThreshold?: number;
|
||||||
|
runThreshold?: number;
|
||||||
|
acceleration?: number;
|
||||||
|
friction?: number;
|
||||||
|
startAt?: number;
|
||||||
|
floorHeight?: number;
|
||||||
|
floorColor?: string;
|
||||||
|
reflectionOpacity?: number;
|
||||||
|
reflectionFade?: number;
|
||||||
|
reflectionTint?: string;
|
||||||
|
wrapEdges?: boolean;
|
||||||
|
jumpVelocity?: number;
|
||||||
|
gravity?: number;
|
||||||
|
showShadow?: boolean;
|
||||||
|
bubbleAnchorX?: number;
|
||||||
|
bubbleAnchorY?: number;
|
||||||
|
muted?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
let {
|
||||||
|
states,
|
||||||
|
bubblePacks,
|
||||||
|
needsConfig = NEEDS,
|
||||||
|
chatter = CHATTER,
|
||||||
|
interactions = INTERACTION,
|
||||||
|
scale = 4,
|
||||||
|
maxSpeed = 280,
|
||||||
|
idleThreshold = 10,
|
||||||
|
runThreshold = 190,
|
||||||
|
acceleration = 1600,
|
||||||
|
friction = 2400,
|
||||||
|
startAt = 0.5,
|
||||||
|
floorHeight = 90,
|
||||||
|
floorColor = '#242830',
|
||||||
|
reflectionOpacity = 0.45,
|
||||||
|
reflectionFade = 0.9,
|
||||||
|
reflectionTint = 'rgba(120, 160, 200, 0.3)',
|
||||||
|
wrapEdges = true,
|
||||||
|
jumpVelocity = 620,
|
||||||
|
gravity = 2400,
|
||||||
|
showShadow = true,
|
||||||
|
bubbleAnchorX = 0,
|
||||||
|
bubbleAnchorY = 4,
|
||||||
|
muted = false
|
||||||
|
}: Props = $props();
|
||||||
|
|
||||||
|
/* ---------- DOM ---------- */
|
||||||
|
let canvas = $state<HTMLCanvasElement>();
|
||||||
|
let ctx: CanvasRenderingContext2D | null = null;
|
||||||
|
let dpr = 1;
|
||||||
|
let viewW = 0;
|
||||||
|
let viewH = 0;
|
||||||
|
|
||||||
|
/* ---------- Subsystems ---------- */
|
||||||
|
const cache = new ImageCache();
|
||||||
|
const physics = new Physics();
|
||||||
|
const clock = new StateClock();
|
||||||
|
const input = new KeyboardInput();
|
||||||
|
const needs = new NeedsSimulator();
|
||||||
|
const renderer = new CharacterRenderer();
|
||||||
|
const pointer = new PointerController(INTERACTION);
|
||||||
|
|
||||||
|
let soundPlayer: SoundPlayer | null = null;
|
||||||
|
let audioCtx: AudioContext | null = null;
|
||||||
|
|
||||||
|
let ready = false;
|
||||||
|
let placed = false;
|
||||||
|
let heldAnchorSet = false;
|
||||||
|
let loadError = $state<string | null>(null);
|
||||||
|
|
||||||
|
// Last drawn body size — used for pointer hit-testing on the next frame.
|
||||||
|
let lastBodyW = 0;
|
||||||
|
let lastBodyH = 0;
|
||||||
|
|
||||||
|
/* ---------- Asset loading ---------- */
|
||||||
|
const urlKey = $derived(
|
||||||
|
[
|
||||||
|
...collectStateUrls(states),
|
||||||
|
...Object.values(bubblePacks ?? {}).flatMap((p) => p.frames)
|
||||||
|
].join('\n')
|
||||||
|
);
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
const key = urlKey;
|
||||||
|
ready = false;
|
||||||
|
loadError = null;
|
||||||
|
if (!key) {
|
||||||
|
loadError = 'No state frames found. Check $lib/assets/character/states/.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let cancelled = false;
|
||||||
|
|
||||||
|
cache
|
||||||
|
.load(key.split('\n'))
|
||||||
|
.then(() => {
|
||||||
|
if (cancelled) return;
|
||||||
|
rebound();
|
||||||
|
ready = true;
|
||||||
|
})
|
||||||
|
.catch((err: Error) => {
|
||||||
|
if (cancelled) return;
|
||||||
|
loadError = err.message;
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
/* ---------- Bounds ---------- */
|
||||||
|
function bounds() {
|
||||||
|
const { w } = cache.largestSize(collectStateUrls(states));
|
||||||
|
return { viewW, viewH, floorHeight, spriteW: w, scale };
|
||||||
|
}
|
||||||
|
|
||||||
|
function resize() {
|
||||||
|
if (!canvas || !ctx) return;
|
||||||
|
dpr = Math.min(window.devicePixelRatio || 1, 3);
|
||||||
|
const rect = canvas.getBoundingClientRect();
|
||||||
|
viewW = rect.width;
|
||||||
|
viewH = rect.height;
|
||||||
|
canvas.width = Math.max(1, Math.round(rect.width * dpr));
|
||||||
|
canvas.height = Math.max(1, Math.round(rect.height * dpr));
|
||||||
|
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
||||||
|
ctx.imageSmoothingEnabled = false;
|
||||||
|
if (!placed && viewW > 0) {
|
||||||
|
placed = true;
|
||||||
|
physics.place(viewW, startAt);
|
||||||
|
}
|
||||||
|
rebound();
|
||||||
|
}
|
||||||
|
|
||||||
|
function rebound() {
|
||||||
|
physics.rebound(
|
||||||
|
{ maxSpeed, acceleration, friction, jumpVelocity, gravity, wrapEdges },
|
||||||
|
bounds()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Audio ---------- */
|
||||||
|
const GESTURES = ['pointerdown', 'keydown', 'touchstart'] as const;
|
||||||
|
|
||||||
|
function unlockAudio() {
|
||||||
|
if (audioCtx) return;
|
||||||
|
try {
|
||||||
|
const Ctor = window.AudioContext ?? (window as any).webkitAudioContext;
|
||||||
|
if (!Ctor) return;
|
||||||
|
audioCtx = new Ctor();
|
||||||
|
void audioCtx.resume();
|
||||||
|
void loadSoundPacks(audioCtx).then((packs) => {
|
||||||
|
if (!audioCtx) return;
|
||||||
|
soundPlayer = new SoundPlayer(audioCtx, packs);
|
||||||
|
soundPlayer.setMuted(muted);
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('[character] audio unavailable', err);
|
||||||
|
}
|
||||||
|
for (const g of GESTURES) window.removeEventListener(g, unlockAudio);
|
||||||
|
}
|
||||||
|
|
||||||
|
function installAudioUnlocker() {
|
||||||
|
for (const g of GESTURES) window.addEventListener(g, unlockAudio, { passive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
soundPlayer?.setMuted(muted);
|
||||||
|
});
|
||||||
|
|
||||||
|
function playSound(name: string, volume: number) {
|
||||||
|
soundPlayer?.play(name, volume);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- State resolution ---------- */
|
||||||
|
function activeStateName(): string {
|
||||||
|
const needAction =
|
||||||
|
needs.active?.actionState && needs.active.elapsed >= needs.active.actionStart
|
||||||
|
? needs.active.actionState.name
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return resolveStateName(
|
||||||
|
{
|
||||||
|
interaction: pointer.state,
|
||||||
|
grounded: physics.grounded,
|
||||||
|
speed: Math.abs(physics.vx),
|
||||||
|
needAction
|
||||||
|
},
|
||||||
|
{ idleThreshold, runThreshold },
|
||||||
|
states
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sideFor(pack: StatePack) {
|
||||||
|
return physics.facing === 'left' ? pack.left : pack.right;
|
||||||
|
}
|
||||||
|
|
||||||
|
function bodyFor(name: string): HTMLImageElement | null {
|
||||||
|
const pack = states[name];
|
||||||
|
if (!pack) return null;
|
||||||
|
const side = sideFor(pack);
|
||||||
|
if (!side.frames.length) return null;
|
||||||
|
const i = clock.frameIndex(pack, side);
|
||||||
|
return cache.get(side.frames[i]) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Bubble ---------- */
|
||||||
|
function currentBubble(): { img: HTMLImageElement; index: number } | null {
|
||||||
|
if (pointer.state === 'held' || pointer.state === 'petted') return null;
|
||||||
|
const a = needs.active;
|
||||||
|
if (!a?.bubblePack || !a.bubblePack.frames.length) return null;
|
||||||
|
if (a.elapsed >= a.bubbleDuration) return null;
|
||||||
|
const index = Math.min(
|
||||||
|
Math.floor(a.elapsed * a.bubblePack.fps),
|
||||||
|
a.bubblePack.frames.length - 1
|
||||||
|
);
|
||||||
|
const img = cache.get(a.bubblePack.frames[index]);
|
||||||
|
return img ? { img, index } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function currentCharsShown(): number {
|
||||||
|
const a = needs.active;
|
||||||
|
if (!a?.text || !chatter) return Infinity;
|
||||||
|
const speed = chatter.typeSpeed ?? 0;
|
||||||
|
if (speed <= 0) return Infinity;
|
||||||
|
const pack = a.bubblePack;
|
||||||
|
const textStart = pack ? (chatter.textFrame ?? 0) / pack.fps : 0;
|
||||||
|
const typingElapsed = a.elapsed - textStart;
|
||||||
|
if (typingElapsed <= 0) return 0;
|
||||||
|
return Math.min(a.text.length, Math.floor(typingElapsed * speed));
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildChatterHooks(c: ChatterConfig): ChatterHooks {
|
||||||
|
return {
|
||||||
|
pack: c.pack,
|
||||||
|
interval: c.interval,
|
||||||
|
lines: c.lines,
|
||||||
|
typeSpeed: c.typeSpeed,
|
||||||
|
typeSound: c.typeSound,
|
||||||
|
typeSoundEvery: c.typeSoundEvery,
|
||||||
|
typeSoundVolume: c.typeSoundVolume,
|
||||||
|
bubbleDuration: (line: string, pack: BubblePack) => {
|
||||||
|
const animDur = pack.frames.length / pack.fps;
|
||||||
|
const textStart = (c.textFrame ?? 0) / pack.fps;
|
||||||
|
const speed = c.typeSpeed ?? 0;
|
||||||
|
const typing = speed > 0 ? line.length / speed : 0;
|
||||||
|
return Math.max(animDur, textStart + typing) + (c.holdLast ?? 1.6);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Loop ---------- */
|
||||||
|
let raf = 0;
|
||||||
|
let last = 0;
|
||||||
|
|
||||||
|
function loop(now: number) {
|
||||||
|
raf = requestAnimationFrame(loop);
|
||||||
|
const dt = last ? Math.min((now - last) / 1000, 1 / 20) : 0;
|
||||||
|
last = now;
|
||||||
|
if (!ready || !ctx) return;
|
||||||
|
|
||||||
|
const locked = needs.isLocked || pointer.state === 'held';
|
||||||
|
|
||||||
|
/* --- physics or held --- */
|
||||||
|
if (pointer.state === 'held') {
|
||||||
|
if (!heldAnchorSet) {
|
||||||
|
pointer.setGrabAnchor(physics.x, physics.y);
|
||||||
|
heldAnchorSet = true;
|
||||||
|
}
|
||||||
|
const anchor = pointer.getHeldPosition();
|
||||||
|
if (anchor) {
|
||||||
|
physics.x = anchor.x;
|
||||||
|
physics.y = Math.max(0, anchor.y);
|
||||||
|
physics.vx = 0;
|
||||||
|
physics.vy = 0;
|
||||||
|
physics.grounded = false;
|
||||||
|
physics.squash = 0;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
heldAnchorSet = false;
|
||||||
|
physics.step(
|
||||||
|
dt,
|
||||||
|
{
|
||||||
|
direction: locked ? 0 : input.direction(),
|
||||||
|
jump: locked ? false : input.consumeJump()
|
||||||
|
},
|
||||||
|
{ maxSpeed, acceleration, friction, jumpVelocity, gravity, wrapEdges },
|
||||||
|
bounds()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- falling → landing --- */
|
||||||
|
if (pointer.state === 'falling' && physics.grounded) {
|
||||||
|
pointer.setState('landing');
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- pointer bounds, then tick the pointer --- */
|
||||||
|
if (lastBodyW > 0) {
|
||||||
|
const gy = physics.groundY(bounds());
|
||||||
|
pointer.setBounds({
|
||||||
|
left: physics.x - lastBodyW / 2,
|
||||||
|
top: gy - physics.y - lastBodyH,
|
||||||
|
width: lastBodyW,
|
||||||
|
height: lastBodyH
|
||||||
|
});
|
||||||
|
}
|
||||||
|
pointer.update(dt);
|
||||||
|
|
||||||
|
/* --- resolve state and advance its clock --- */
|
||||||
|
const name = activeStateName();
|
||||||
|
const pack = states[name];
|
||||||
|
clock.update(dt, name, pack, Math.abs(physics.vx));
|
||||||
|
|
||||||
|
/* --- body image --- */
|
||||||
|
const body = bodyFor(name);
|
||||||
|
if (body) {
|
||||||
|
lastBodyW = body.naturalWidth * scale;
|
||||||
|
lastBodyH = body.naturalHeight * scale;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* --- needs --- */
|
||||||
|
needs.step(dt, name, {
|
||||||
|
defs: needsConfig,
|
||||||
|
bubblePacks: bubblePacks ?? {},
|
||||||
|
states,
|
||||||
|
chatter: chatter ? buildChatterHooks(chatter) : null,
|
||||||
|
onSound: playSound
|
||||||
|
});
|
||||||
|
|
||||||
|
/* --- draw --- */
|
||||||
|
if (!body || !pack) return;
|
||||||
|
const side = sideFor(pack);
|
||||||
|
|
||||||
|
renderer.draw({
|
||||||
|
ctx,
|
||||||
|
viewW,
|
||||||
|
viewH,
|
||||||
|
groundY: physics.groundY(bounds()),
|
||||||
|
dpr,
|
||||||
|
body,
|
||||||
|
mirrored: side.mirrored,
|
||||||
|
x: physics.x,
|
||||||
|
y: physics.y,
|
||||||
|
squash: physics.squash,
|
||||||
|
bubble: currentBubble(),
|
||||||
|
bubbleText: needs.active?.text ?? null,
|
||||||
|
charsShown: currentCharsShown(),
|
||||||
|
bubbleTextFrame: chatter?.textFrame ?? 0,
|
||||||
|
scale,
|
||||||
|
showShadow,
|
||||||
|
reflectionOpacity,
|
||||||
|
reflectionFade,
|
||||||
|
reflectionTint,
|
||||||
|
bubbleAnchorX,
|
||||||
|
bubbleAnchorY,
|
||||||
|
chatter
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
if (!canvas) return;
|
||||||
|
ctx = canvas.getContext('2d');
|
||||||
|
if (!ctx) return;
|
||||||
|
|
||||||
|
pointer.onGrab = () => {
|
||||||
|
needs.active = null;
|
||||||
|
needs.queue.length = 0;
|
||||||
|
heldAnchorSet = false;
|
||||||
|
if (interactions.pickupSound) playSound(interactions.pickupSound, 1);
|
||||||
|
};
|
||||||
|
pointer.onRelease = () => {
|
||||||
|
const v = pointer.getThrowVelocity();
|
||||||
|
physics.vx = v.vx;
|
||||||
|
physics.vy = v.vy;
|
||||||
|
// If the throw is upward, lift the cat out of the grounded state.
|
||||||
|
if (physics.vy > 0) physics.grounded = false;
|
||||||
|
if (interactions.dropSound) playSound(interactions.dropSound, 0.8);
|
||||||
|
};
|
||||||
|
pointer.onLanding = () => {
|
||||||
|
if (interactions.landingSound) playSound(interactions.landingSound, 0.8);
|
||||||
|
};
|
||||||
|
pointer.onPetSound = () => {
|
||||||
|
if (interactions.purrSound) playSound(interactions.purrSound, interactions.purrVolume ?? 0.4);
|
||||||
|
};
|
||||||
|
|
||||||
|
resize();
|
||||||
|
const ro = new ResizeObserver(resize);
|
||||||
|
ro.observe(canvas);
|
||||||
|
|
||||||
|
input.attach(window);
|
||||||
|
pointer.attach(window);
|
||||||
|
installAudioUnlocker();
|
||||||
|
raf = requestAnimationFrame(loop);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
cancelAnimationFrame(raf);
|
||||||
|
ro.disconnect();
|
||||||
|
input.detach(window);
|
||||||
|
pointer.detach(window);
|
||||||
|
for (const g of GESTURES) window.removeEventListener(g, unlockAudio);
|
||||||
|
void audioCtx?.close();
|
||||||
|
};
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<svelte:window />
|
||||||
|
|
||||||
|
<div class="layer">
|
||||||
|
<div class="floor" style:height="{floorHeight}px" style:background={floorColor}></div>
|
||||||
|
<canvas bind:this={canvas} aria-hidden="true"></canvas>
|
||||||
|
{#if loadError}
|
||||||
|
<p class="err">{loadError}</p>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.layer {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
pointer-events: none;
|
||||||
|
z-index: 50;
|
||||||
|
}
|
||||||
|
.floor {
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0.06), rgba(0, 0, 0, 0.15));
|
||||||
|
background-blend-mode: overlay;
|
||||||
|
}
|
||||||
|
canvas {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
image-rendering: pixelated;
|
||||||
|
}
|
||||||
|
.err {
|
||||||
|
position: absolute;
|
||||||
|
bottom: 1rem;
|
||||||
|
left: 1rem;
|
||||||
|
margin: 0;
|
||||||
|
font:
|
||||||
|
12px/1.4 ui-monospace,
|
||||||
|
monospace;
|
||||||
|
color: #ff6b6b;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
const files = import.meta.glob('$lib/assets/character/bubbles/**/*.png', {
|
||||||
|
eager: true,
|
||||||
|
query: '?url',
|
||||||
|
import: 'default'
|
||||||
|
}) as Record<string, string>;
|
||||||
|
|
||||||
|
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<string, BubblePack> {
|
||||||
|
const { fps = 8, duration = 2.5 } = opts;
|
||||||
|
const groups = new Map<string, Array<[string, string]>>();
|
||||||
|
|
||||||
|
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<string, BubblePack> = {};
|
||||||
|
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<string, HTMLImageElement>();
|
||||||
|
|
||||||
|
async load(urls: string[]): Promise<void> {
|
||||||
|
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 };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
};
|
||||||
@@ -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';
|
||||||
@@ -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<string>();
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<string, number>;
|
||||||
|
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<string, BubblePack>;
|
||||||
|
states: Record<string, StatePack>;
|
||||||
|
chatter: ChatterHooks | null;
|
||||||
|
onSound: (name: string, volume: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_QUEUE = 8;
|
||||||
|
|
||||||
|
export class NeedsSimulator {
|
||||||
|
values: Record<string, number> = {};
|
||||||
|
firedBands = new Set<string>();
|
||||||
|
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);
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
@@ -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<Shimeji>} that resolves when the Shimeji is done initializing
|
|
||||||
*/
|
|
||||||
public static async Initialize(config: ShimejiConfig): Promise<Shimeji> {
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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<string, string>;
|
||||||
|
|
||||||
|
export interface SoundPack {
|
||||||
|
name: string;
|
||||||
|
buffers: AudioBuffer[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
|
||||||
|
|
||||||
|
function soundPackUrls(): Record<string, string[]> {
|
||||||
|
const groups: Record<string, [string, string][]> = {};
|
||||||
|
|
||||||
|
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<string, string[]> = {};
|
||||||
|
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<Record<string, SoundPack>> {
|
||||||
|
const urls = soundPackUrls();
|
||||||
|
const out: Record<string, SoundPack> = {};
|
||||||
|
|
||||||
|
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<string, number> = {};
|
||||||
|
private muted = false;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private ctx: AudioContext,
|
||||||
|
private packs: Record<string, SoundPack>
|
||||||
|
) {}
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<string, string>;
|
||||||
|
|
||||||
|
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
|
||||||
|
|
||||||
|
/** Matches states/<name>/<file>.png OR states/<name>/<side>/<file>.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<string, StateConfig>;
|
||||||
|
|
||||||
|
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<string, StatePack> {
|
||||||
|
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<string, StatePack> = {};
|
||||||
|
|
||||||
|
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, StatePack>): string[] {
|
||||||
|
const out = new Set<string>();
|
||||||
|
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, StatePack>
|
||||||
|
): 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<Facing, FacingClips>;
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -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<HTMLElement>('.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<HTMLElement>('[id]').forEach((n) => n.removeAttribute('id'));
|
||||||
|
|
||||||
|
clone.querySelectorAll<HTMLElement>('.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<HTMLElement>('.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;
|
||||||
|
}
|
||||||
@@ -1,336 +1,370 @@
|
|||||||
import Vector2 from "../vector";
|
|
||||||
|
|
||||||
export class Shimeji {
|
export class Shimeji {
|
||||||
private element: HTMLElement;
|
private element: HTMLElement;
|
||||||
private canvas: HTMLCanvasElement;
|
|
||||||
private rect: DOMRect;
|
|
||||||
|
|
||||||
private pos: Vector2 = Vector2.zero;
|
|
||||||
private vel: Vector2 = Vector2.zero;
|
|
||||||
|
|
||||||
private angle: number = 0; // radians
|
// Position and velocity
|
||||||
private angularVelocity: number = 0; // rad/s
|
private x: number = 0;
|
||||||
private inertia: number; // kg·m²
|
private y: number = 0;
|
||||||
private localGrip: Vector2 = Vector2.zero; // offset from center (body‑fixed)
|
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 isBeingDragged: boolean = false;
|
||||||
|
|
||||||
private rafId: number | null = null;
|
|
||||||
private prevDeltaTime: number = 0;
|
|
||||||
|
|
||||||
|
private rafId: number | null = null;
|
||||||
|
|
||||||
private readonly RESTITUTION: number = 0.6;
|
// Physics parameters
|
||||||
private readonly STIFFNESS: number = 500;
|
private readonly STIFFNESS: number = 0.85;
|
||||||
private readonly DAMPING: number = 1;
|
private readonly DAMPING: number = 0.6;
|
||||||
private readonly MASS: number = 10.0;
|
private readonly MASS: number = 1.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
|
|
||||||
};
|
|
||||||
|
|
||||||
this.inertia = (1 / 12) *
|
// Gravity (pixels per frame squared)
|
||||||
this.MASS * (this.rect.width * this.rect.width + this.rect.height * this.rect.height);
|
private gravity: number = 10;
|
||||||
|
|
||||||
this.pos.set(window.innerWidth / 2, window.innerHeight/ 2);
|
|
||||||
|
|
||||||
this.updateBounds();
|
|
||||||
window.addEventListener('resize', () => this.updateBounds());
|
|
||||||
|
|
||||||
console.log(this.element.getBoundingClientRect());
|
// Bounce coefficients (energy retention - lower = less bounce)
|
||||||
|
private readonly WALL_BOUNCE: number = 0.5; // Walls lose 50% energy
|
||||||
this.setupDragEvents();
|
private readonly FLOOR_BOUNCE: number = 0.6; // Floor loses 40% energy (realistic)
|
||||||
}
|
private readonly CEILING_BOUNCE: number = 0.4; // Ceiling loses 60% energy
|
||||||
|
|
||||||
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;
|
|
||||||
|
|
||||||
const firstFrame = (delta: number) => {
|
// Minimum velocity to continue bouncing
|
||||||
this.prevDeltaTime = delta;
|
private readonly MIN_BOUNCE_VELOCITY: number = 2;
|
||||||
this.rafId = requestAnimationFrame(animate);
|
|
||||||
}
|
|
||||||
|
|
||||||
const animate = (delta: number) => {
|
// Boundaries
|
||||||
const dt: number = Math.min(delta - this.prevDeltaTime, 0.05);
|
private bounds: { minX: number; minY: number; maxX: number; maxY: number };
|
||||||
this.prevDeltaTime = delta;
|
|
||||||
|
|
||||||
this.updatePhysics(dt);
|
// Optional forces
|
||||||
this.applyBoundaries();
|
private wind: number = 0;
|
||||||
this.render();
|
private friction: number = 0.98;
|
||||||
this.rafId = requestAnimationFrame(animate);
|
|
||||||
};
|
|
||||||
|
|
||||||
this.rafId = requestAnimationFrame(firstFrame);
|
|
||||||
}
|
|
||||||
|
|
||||||
stop(): void {
|
|
||||||
if (this.rafId !== null) {
|
|
||||||
cancelAnimationFrame(this.rafId);
|
|
||||||
this.rafId = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private getCornerWorld(lx: number, ly: number): Vector2 {
|
// Track if on ground for additional effects
|
||||||
// lx, ly are in local coordinates (relative to center, with rotation)
|
private wasOnGround: boolean = false;
|
||||||
const cos = Math.cos(this.angle);
|
private bounceCount: number = 0;
|
||||||
const sin = Math.sin(this.angle);
|
|
||||||
return new Vector2(
|
|
||||||
this.pos.x + (lx * cos - ly * sin),
|
|
||||||
this.pos.y + (lx * sin + ly * cos)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private setupDragEvents(): void {
|
constructor(element: HTMLElement) {
|
||||||
this.element.addEventListener('mousedown', (e) => {
|
this.element = element;
|
||||||
e.preventDefault();
|
|
||||||
this.isBeingDragged = true;
|
|
||||||
this.element.style.cursor = 'grabbing';
|
|
||||||
|
|
||||||
const parent = this.element.parentElement;
|
// Initialize bounds (will update on resize)
|
||||||
if(parent) parent.style.cursor = 'grabbing';
|
this.bounds = {
|
||||||
|
minX: 0,
|
||||||
|
minY: 0,
|
||||||
|
maxX: window.innerWidth,
|
||||||
|
maxY: window.innerHeight
|
||||||
|
};
|
||||||
|
|
||||||
const clickWorld = new Vector2(e.pageX, e.pageY);
|
// Start with element at center
|
||||||
const center = this.pos;
|
this.x = window.innerWidth / 2;
|
||||||
const offset = clickWorld.sub(center)
|
this.y = window.innerHeight / 2;
|
||||||
const cos = Math.cos(-this.angle);
|
|
||||||
const sin = Math.sin(-this.angle);
|
|
||||||
|
|
||||||
this.localGrip = new Vector2(
|
this.updateBounds();
|
||||||
offset.x * cos - offset.y * sin,
|
window.addEventListener('resize', () => this.updateBounds());
|
||||||
offset.x * sin + offset.y * cos
|
|
||||||
);
|
|
||||||
|
|
||||||
this.pivot.x = e.offsetX - this.rect.width / 2;
|
this.setupDragEvents();
|
||||||
this.pivot.y = e.offsetY - this.rect.height / 2;
|
}
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
document.addEventListener('mousemove', (e) => {
|
private updateBounds(): void {
|
||||||
this.mousePos.x = e.pageX;
|
this.bounds = {
|
||||||
this.mousePos.y = e.pageY;
|
minX: 0,
|
||||||
});
|
minY: 0,
|
||||||
|
maxX: window.innerWidth,
|
||||||
|
maxY: window.innerHeight
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
document.addEventListener('mouseup', (e) => {
|
start(): void {
|
||||||
if(this.isBeingDragged) {
|
if (this.rafId !== null) return;
|
||||||
this.isBeingDragged = false;
|
|
||||||
this.element.style.cursor = 'grab';
|
|
||||||
|
|
||||||
const parent = this.element.parentElement;
|
const animate = () => {
|
||||||
if(parent) parent.style.cursor = 'auto';
|
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) => {
|
private setupDragEvents(): void {
|
||||||
e.preventDefault();
|
this.element.addEventListener('mousedown', (e) => {
|
||||||
});
|
e.preventDefault();
|
||||||
}
|
this.isBeingDragged = true;
|
||||||
|
this.element.style.cursor = 'grabbing';
|
||||||
private updatePhysics(dt: number): void {
|
|
||||||
|
|
||||||
const cos = Math.cos(this.angle);
|
// Clear mouse history on new drag
|
||||||
const sin = Math.sin(this.angle);
|
this.mouseHistory = [];
|
||||||
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)
|
|
||||||
);
|
|
||||||
|
|
||||||
if (this.isBeingDragged) {
|
// Track mouse movement globally for better throw detection
|
||||||
const direction: Vector2 = this.mousePos.sub(gripWorld);
|
document.addEventListener('mousemove', (e) => {
|
||||||
|
if (this.isBeingDragged) {
|
||||||
const force: Vector2 = direction.mul(this.STIFFNESS);
|
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);
|
// Store mouse position history for throw calculation
|
||||||
|
this.mouseHistory.push({
|
||||||
acceleration.mulEq(dt);
|
x: e.pageX,
|
||||||
|
y: e.pageY,
|
||||||
|
time: Date.now()
|
||||||
|
});
|
||||||
|
|
||||||
this.vel.addEq(acceleration);
|
// Keep only recent history
|
||||||
this.vel.mulEq(0.8);
|
if (this.mouseHistory.length > this.HISTORY_LENGTH) {
|
||||||
|
this.mouseHistory.shift();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
const r = gripWorld.sub(this.pos);
|
this.element.addEventListener('mouseup', (e) => {
|
||||||
const torque = r.cross(force);
|
if (this.isBeingDragged) {
|
||||||
this.angularVelocity += (torque / this.inertia) * dt;
|
this.isBeingDragged = false;
|
||||||
}
|
this.element.style.cursor = 'grab';
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
const outVel = this.vel.mul(dt);
|
// Calculate throw velocity based on mouse movement speed
|
||||||
this.pos.addEq(outVel);
|
this.applyThrowVelocity();
|
||||||
|
|
||||||
this.angle += this.angularVelocity * dt;
|
// Reset mouse history
|
||||||
this.angle %= 2 * Math.PI;
|
this.mouseHistory = [];
|
||||||
}
|
}
|
||||||
|
});
|
||||||
private applyBoundaries(): void {
|
|
||||||
const w = this.rect.width / 2;
|
|
||||||
const h = this.rect.height / 2;
|
|
||||||
|
|
||||||
// List of corners in local coordinates (four combinations)
|
this.element.addEventListener('dragstart', (e) => {
|
||||||
const corners = [
|
e.preventDefault();
|
||||||
{ lx: w, ly: h }, // top‑right
|
});
|
||||||
{ lx: w, ly: -h }, // bottom‑right
|
}
|
||||||
{ lx: -w, ly: h }, // top‑left
|
|
||||||
{ lx: -w, ly: -h } // bottom‑left
|
|
||||||
];
|
|
||||||
|
|
||||||
// Check each wall
|
private applyThrowVelocity(): void {
|
||||||
// Left wall (x = leftBound)
|
if (this.mouseHistory.length < 2) return;
|
||||||
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
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Right wall (x = rightBound)
|
// Get oldest and newest mouse positions
|
||||||
const rightBound = this.bounds.maxX - w;
|
const oldest = this.mouseHistory[0];
|
||||||
for (const corner of corners) {
|
const newest = this.mouseHistory[this.mouseHistory.length - 1];
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Top wall (y = topBound)
|
// Calculate time delta in seconds
|
||||||
const topBound = h;
|
const timeDelta = (newest.time - oldest.time) / 1000;
|
||||||
for (const corner of corners) {
|
if (timeDelta === 0) return;
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bottom wall (y = bottomBound)
|
// Calculate velocity in pixels per second
|
||||||
const bottomBound = this.bounds.maxY - h;
|
let throwVelX = (newest.x - oldest.x) / timeDelta;
|
||||||
for (const corner of corners) {
|
let throwVelY = (newest.y - oldest.y) / timeDelta;
|
||||||
const world = this.getCornerWorld(corner.lx, corner.ly);
|
|
||||||
if (world.y > bottomBound) {
|
// Cap maximum throw velocity to prevent ridiculous speeds
|
||||||
const penetration = world.y - bottomBound;
|
const MAX_THROW_SPEED = 50;
|
||||||
const normal = new Vector2(0, -1);
|
throwVelX = Math.min(Math.max(throwVelX, -MAX_THROW_SPEED), MAX_THROW_SPEED);
|
||||||
const contactX = Math.min(Math.max(world.x, leftBound), rightBound);
|
throwVelY = Math.min(Math.max(throwVelY, -MAX_THROW_SPEED), MAX_THROW_SPEED);
|
||||||
const contactPoint = new Vector2(contactX, bottomBound);
|
|
||||||
this.resolveCollision(normal, contactPoint);
|
// Apply throw velocity (divide by ~60 to convert from per-second to per-frame)
|
||||||
this.pos.y = bottomBound + h;
|
this.velocityX += throwVelX / 60;
|
||||||
return;
|
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) {
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import Renderer from '$lib/shimagic/renderer/rendererr';
|
|
||||||
import { WebG } from '$lib/shimagic/renderer/web_g_enginee';
|
|
||||||
import { Shimagic } from '$lib/stores/shimeji';
|
|
||||||
import Vector2 from '$lib/vector';
|
|
||||||
import { onMount } from 'svelte';
|
|
||||||
|
|
||||||
const drag: number = 3;
|
|
||||||
const speed: number = 2;
|
|
||||||
|
|
||||||
let shimeji: Shimagic.Shimeji;
|
|
||||||
let renderer: Renderer;
|
|
||||||
let sprite: HTMLElement;
|
|
||||||
let canvas: HTMLCanvasElement;
|
|
||||||
let shown: boolean = $state(false);
|
|
||||||
|
|
||||||
function genRandomPos(min: number, max: number): number {
|
|
||||||
const out = Math.random() * (max - min) + min;
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchShader(path: string): Promise<string> {
|
|
||||||
const response = await fetch(path);
|
|
||||||
if (!response.ok) throw new Error(`failed to fetch the shader file ${response}`);
|
|
||||||
return await response.text();
|
|
||||||
}
|
|
||||||
|
|
||||||
onMount(async () => {
|
|
||||||
canvas.width = window.innerWidth;
|
|
||||||
canvas.height = window.innerHeight;
|
|
||||||
|
|
||||||
//const vert = await fetchShader('src/lib/shimeji/renderer/shaders/vertex_shader.vert');
|
|
||||||
//const frag = await fetchShader('src/lib/shimeji/renderer/shaders/fragment_shader.frag');
|
|
||||||
|
|
||||||
const engineConfig: WebG.EngineConfig = {
|
|
||||||
canvas: canvas,
|
|
||||||
vertexShaderUrl: 'src/lib/shimeji/renderer/shaders/vertex_shader.vert',
|
|
||||||
fragmentShaderUrl: 'src/lib/shimeji/renderer/shaders/fragment_shader.frag',
|
|
||||||
attributes: {
|
|
||||||
aPosition: 0,
|
|
||||||
aColor: 1
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const engine = await WebG.Engine.Initialize(engineConfig);
|
|
||||||
|
|
||||||
const drawArgs: WebG.DrawCallArgs = {
|
|
||||||
vertices: [
|
|
||||||
new Vector2(200, 200),
|
|
||||||
new Vector2(700, 700),
|
|
||||||
new Vector2(700, 200),
|
|
||||||
new Vector2(200, 200),
|
|
||||||
new Vector2(200, 700),
|
|
||||||
new Vector2(700, 700)
|
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
engine.setDrawMode(WebG.EngineDrawMode.TEXTURE);
|
|
||||||
engine.draw(drawArgs);
|
|
||||||
|
|
||||||
/* shimeji = new Shimeji(40, canvas, renderer);
|
|
||||||
shimeji.start();
|
|
||||||
|
|
||||||
shown = true;
|
|
||||||
|
|
||||||
document.addEventListener('keydown', (e) => {
|
|
||||||
if (e.key === 'a') {
|
|
||||||
shimeji.addImpulse(-500, -100);
|
|
||||||
}
|
|
||||||
if (e.key === 'd') {
|
|
||||||
shimeji.addImpulse(500, -100);
|
|
||||||
}
|
|
||||||
if (e.key === 'space') {
|
|
||||||
shimeji.moveTo(genRandomPos(200, window.innerWidth - 200));
|
|
||||||
}
|
|
||||||
}); */
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div class=" absolute z-20 size-full overflow-clip">
|
|
||||||
<canvas
|
|
||||||
bind:this={canvas}
|
|
||||||
style=" stroke-width: 5px;"
|
|
||||||
class=" absolute z-2 size-full stroke-red-500"
|
|
||||||
></canvas>
|
|
||||||
<!-- <div
|
|
||||||
bind:this={sprite}
|
|
||||||
class=" absolute z-30 size-20 origin-center -translate-1/2 cursor-grab bg-amber-400 opacity-15 will-change-transform transform-flat"
|
|
||||||
></div> -->
|
|
||||||
</div>
|
|
||||||
@@ -1,12 +1,10 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import { mwin_movable } from '$lib/mwinlib/mwin_controller.svelte';
|
||||||
|
import type { MWinAPI } from '$lib/mwinlib/mwin_util';
|
||||||
import Input from './terminal/Input.svelte';
|
import Input from './terminal/Input.svelte';
|
||||||
|
|
||||||
let { username }: { username: string } = $props();
|
let { username }: { username: string } = $props();
|
||||||
|
|
||||||
//const clearTerminal = (): void => clear();
|
|
||||||
|
|
||||||
//const printOutput = (e: HTMLElement, d: PrintData): void => print(e, d);
|
|
||||||
|
|
||||||
export async function init(username: string, password: string) {
|
export async function init(username: string, password: string) {
|
||||||
try {
|
try {
|
||||||
//await initTerminal({ username, password }, callbackInit, 'en_US');
|
//await initTerminal({ username, password }, callbackInit, 'en_US');
|
||||||
@@ -48,128 +46,85 @@
|
|||||||
return ctx.measureText('M').width;
|
return ctx.measureText('M').width;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* function inputHandler(event: KeyboardEvent) {
|
|
||||||
const terminalKeyInhibitor = terminal.getKeybindInhibitor();
|
|
||||||
terminalKeyInhibitor.processKeystroke(event);
|
|
||||||
|
|
||||||
const processKeyInhibitor = terminal.getProcessKeyInhibitor();
|
|
||||||
if (processKeyInhibitor != ExitCode.ERROR) {
|
|
||||||
processKeyInhibitor.processKeystroke(event);
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(processKeyInhibitor, terminalKeyInhibitor);
|
|
||||||
switch (event.key) {
|
|
||||||
case 'Enter': {
|
|
||||||
terminal.executeCommand(inputValue);
|
|
||||||
updateTerminal();
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case 'ArrowRight': {
|
|
||||||
//TODO: Move cursor visually
|
|
||||||
}
|
|
||||||
case 'ArrowLeft': {
|
|
||||||
//TODO: Move cursor visually
|
|
||||||
}
|
|
||||||
case 'ArrowUp': {
|
|
||||||
//TODO: Make a traverse history function with up/down args
|
|
||||||
}
|
|
||||||
case 'ArrowDown': {
|
|
||||||
//TODO: Make a traverse history function with up/down args
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const elem = document.getElementById('cout');
|
|
||||||
if (!elem) {
|
|
||||||
throw new Error('cant scroll to bottom, element is null');
|
|
||||||
}
|
|
||||||
|
|
||||||
elem.scrollTop = elem.scrollHeight;
|
|
||||||
} */
|
|
||||||
|
|
||||||
/* //Callback initializer
|
|
||||||
const callbackInit = {
|
|
||||||
print: (data: any) => {
|
|
||||||
const e = document.getElementById('outputWrapper');
|
|
||||||
if (!e) return;
|
|
||||||
printOutput(e, data);
|
|
||||||
},
|
|
||||||
clear: clearTerminal,
|
|
||||||
getWidth: getWidth,
|
|
||||||
getFontSize: getFontSize
|
|
||||||
}; */
|
|
||||||
let cwd: string = $state('');
|
let cwd: string = $state('');
|
||||||
const hostname = 'terminal'; //TODO: Change this to pull from config on db
|
const hostname = 'termos'; //TODO: Change this to pull from config on db
|
||||||
//let isProcessActive = $state(false);
|
//let isProcessActive = $state(false);
|
||||||
|
|
||||||
let inputValue = $state('');
|
let mwin: MWinAPI;
|
||||||
|
let inputValue = $state('Lorem ipsum dolor sit amet consectetur adipisicing elit.');
|
||||||
|
let inputComponent: any;
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<label for="input" class="w-11/12">
|
<div
|
||||||
|
id="terminal-wrapper"
|
||||||
|
class=" relative flex h-screen w-full flex-col items-center justify-center"
|
||||||
|
>
|
||||||
<div
|
<div
|
||||||
|
class="absolute flex size-full h-256 w-420 flex-col rounded-md shadow-subtle transition-discrete will-change-auto"
|
||||||
id="terminal"
|
id="terminal"
|
||||||
class=" terminal-window flex size-full flex-col rounded-md shadow-subtle transition-discrete"
|
use:mwin_movable={{
|
||||||
|
wrapper: '#terminal-wrapper',
|
||||||
|
handle: '#terminal-bar',
|
||||||
|
baseZIndex: 10,
|
||||||
|
resizable: { threshold: 10, minWidth: 500, minHeight: 300 },
|
||||||
|
onClose: () => {
|
||||||
|
mwin.state.height = 0;
|
||||||
|
},
|
||||||
|
onAPI: (api) => (mwin = api)
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
class="terminal-bar flex h-9 w-full flex-row items-center rounded-t-md bg-surface-2 text-center font-terminal text-sm font-bold text-primary"
|
id="terminal-bar"
|
||||||
|
class=" flex h-9 w-full flex-row items-center rounded-t-md bg-surface-2 text-center font-terminal text-sm font-bold text-primary select-none light:bg-surface-3"
|
||||||
>
|
>
|
||||||
<div class="dots-wrapper mx-2.5 flex h-full flex-row items-center justify-center gap-2.5">
|
<div class="dots-wrapper mx-3 flex h-full flex-row items-center justify-center gap-3">
|
||||||
<button class="size-2.5 cursor-pointer rounded-full p-0" title=""></button>
|
<button class="size-[11px] cursor-pointer rounded-full p-0" title=""></button>
|
||||||
<button class="size-2.5 cursor-pointer rounded-full p-0" title=""></button>
|
<button class="size-[11px] cursor-pointer rounded-full p-0" title=""></button>
|
||||||
<button class="size-2.5 cursor-pointer rounded-full p-0" title=""></button>
|
<button class="size-[11px] cursor-pointer rounded-full p-0" title=""></button>
|
||||||
</div>
|
</div>
|
||||||
<div class=" mr-2 flex grow text-sm">
|
<div class=" mr-2 flex grow items-center text-center text-sm">
|
||||||
<p>{username}@{hostname} {cwd}</p>
|
<span class="leading-none">{username}@{hostname} {cwd}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
class="inner-content scroll-hidden grow origin-top overflow-y-auto rounded-b-md bg-surface-1 p-4 text-sm text-text-primary"
|
class="inner-content scroll-hidden grow origin-top overflow-y-auto rounded-b-md bg-surface-1 p-4 text-sm text-text-primary"
|
||||||
id="cout"
|
id="cout"
|
||||||
|
onclick={() => inputComponent?.focusInput()}
|
||||||
|
onkeydown={() => inputComponent?.focusInput()}
|
||||||
|
role="textbox"
|
||||||
|
tabindex="-1"
|
||||||
>
|
>
|
||||||
<div id="outputWrapper"></div>
|
<div id="outputWrapper"></div>
|
||||||
<Input autofocus bind:value={inputValue} blinkDelay={500} />
|
<Input bind:value={inputValue} blinkDelay={500} bind:this={inputComponent} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</label>
|
</div>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
* {
|
|
||||||
transition: var(--transition-standard);
|
|
||||||
}
|
|
||||||
@keyframes fadeIn {
|
|
||||||
from {
|
|
||||||
opacity: 0;
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
to {
|
|
||||||
opacity: 1;
|
|
||||||
display: block;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.dots-wrapper {
|
.dots-wrapper {
|
||||||
& > button {
|
& > button {
|
||||||
|
transition: all 0.05s ease;
|
||||||
border: none;
|
border: none;
|
||||||
&:hover {
|
|
||||||
transform: translateY(-0.1rem);
|
|
||||||
}
|
|
||||||
&:active {
|
&:active {
|
||||||
transform: translate(0);
|
transform: translateY(1px);
|
||||||
}
|
}
|
||||||
&:nth-child(1) {
|
&:nth-child(1) {
|
||||||
background-color: rgb(255, 0, 0);
|
background-color: rgb(220, 65, 65);
|
||||||
&:active {
|
&:active {
|
||||||
background-color: rgb(255, 100, 100);
|
background-color: rgb(200, 45, 45);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
&:nth-child(2) {
|
&:nth-child(2) {
|
||||||
background-color: rgb(255, 165, 0);
|
background-color: rgb(255, 165, 0);
|
||||||
&:active {
|
&:active {
|
||||||
background-color: rgb(255, 215, 50);
|
background-color: rgb(220, 145, 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
&:nth-child(3) {
|
&:nth-child(3) {
|
||||||
background-color: rgb(50, 205, 50);
|
background-color: rgb(55, 170, 60);
|
||||||
&:active {
|
&:active {
|
||||||
background-color: rgb(100, 255, 100);
|
background-color: rgb(35, 150, 40);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import { petals, type PetalsCleanup } from '$lib/stores/petals';
|
||||||
import { onMount } from 'svelte';
|
import { onMount } from 'svelte';
|
||||||
|
|
||||||
let {
|
let {
|
||||||
@@ -13,13 +14,39 @@
|
|||||||
oninput?: (value: string) => void;
|
oninput?: (value: string) => void;
|
||||||
} = $props();
|
} = $props();
|
||||||
|
|
||||||
let container: HTMLDivElement | undefined;
|
let container: HTMLElement;
|
||||||
let cursorPos: number = $derived(value.length);
|
let cursorPos: number = $state(value.length);
|
||||||
let text: string = $state('');
|
let anchorPos: number | null = $state(null);
|
||||||
|
let isDragging: boolean = $state(false);
|
||||||
let focused: boolean = $state(false);
|
let focused: boolean = $state(false);
|
||||||
let blinkPaused: boolean = $state(false); // true → cursor steady, false → blinking
|
let blinkPaused: boolean = $state(false);
|
||||||
let blinkTimer: ReturnType<typeof setTimeout> | null = null;
|
let blinkTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
|
||||||
|
let cleanup: PetalsCleanup | null = null;
|
||||||
|
|
||||||
|
let sel = $derived.by(() => {
|
||||||
|
if (anchorPos === null || anchorPos === cursorPos) {
|
||||||
|
return { active: false, start: -1, end: -1 };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
active: true,
|
||||||
|
start: Math.min(anchorPos, cursorPos),
|
||||||
|
end: Math.max(anchorPos, cursorPos)
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
function isSelected(i: number): boolean {
|
||||||
|
return sel.active && i >= sel.start && i < sel.end;
|
||||||
|
}
|
||||||
|
|
||||||
|
function gust(): void {
|
||||||
|
if (!container) return;
|
||||||
|
petals(container, { duration: 4000, swayAmp: 26, hideOriginals: false });
|
||||||
|
value = '';
|
||||||
|
cursorPos = 0;
|
||||||
|
anchorPos = null;
|
||||||
|
}
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (autofocus && container) {
|
if (autofocus && container) {
|
||||||
container.focus();
|
container.focus();
|
||||||
@@ -35,6 +62,36 @@
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (cursorPos > value.length) cursorPos = value.length;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Global mousemove / mouseup during drag.
|
||||||
|
$effect(() => {
|
||||||
|
if (!isDragging) return;
|
||||||
|
|
||||||
|
const onMove = (e: MouseEvent) => {
|
||||||
|
const idx = charIndexFromEvent(e);
|
||||||
|
if (idx === null) return;
|
||||||
|
cursorPos = idx;
|
||||||
|
pauseBlink();
|
||||||
|
};
|
||||||
|
const onUp = () => {
|
||||||
|
isDragging = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('mousemove', onMove);
|
||||||
|
window.addEventListener('mouseup', onUp);
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('mousemove', onMove);
|
||||||
|
window.removeEventListener('mouseup', onUp);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
export function focusInput(): void {
|
||||||
|
container?.focus();
|
||||||
|
}
|
||||||
|
|
||||||
function pauseBlink() {
|
function pauseBlink() {
|
||||||
blinkPaused = true;
|
blinkPaused = true;
|
||||||
if (blinkTimer) clearTimeout(blinkTimer);
|
if (blinkTimer) clearTimeout(blinkTimer);
|
||||||
@@ -45,64 +102,174 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function handleFocus() {
|
function handleFocus() {
|
||||||
console.log('focused');
|
|
||||||
focused = true;
|
focused = true;
|
||||||
blinkPaused = false; // start blinking immediately
|
blinkPaused = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleBlur() {
|
function handleBlur() {
|
||||||
console.log('blured');
|
|
||||||
|
|
||||||
focused = false;
|
focused = false;
|
||||||
if (blinkTimer) {
|
if (blinkTimer) {
|
||||||
clearTimeout(blinkTimer);
|
clearTimeout(blinkTimer);
|
||||||
blinkTimer = null;
|
blinkTimer = null;
|
||||||
}
|
}
|
||||||
blinkPaused = false;
|
blinkPaused = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function insertChar(char: string) {
|
function charIndexFromEvent(e: MouseEvent): number | null {
|
||||||
text = text.slice(0, cursorPos) + char + text.slice(cursorPos);
|
const el = (e.target as HTMLElement | null)?.closest?.(
|
||||||
cursorPos += char.length;
|
'[data-char-index]'
|
||||||
|
) as HTMLElement | null;
|
||||||
|
if (!el) return null;
|
||||||
|
const raw = el.getAttribute('data-char-index');
|
||||||
|
return raw === null ? null : Number(raw);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSelectedText(): string {
|
||||||
|
if (!sel.active) return '';
|
||||||
|
return value.slice(sel.start, sel.end);
|
||||||
|
}
|
||||||
|
|
||||||
|
function deleteSelection(): void {
|
||||||
|
if (!sel.active) return;
|
||||||
|
value = value.slice(0, sel.start) + value.slice(sel.end);
|
||||||
|
cursorPos = sel.start;
|
||||||
|
anchorPos = null;
|
||||||
|
oninput(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function insertChar(char: string): void {
|
||||||
|
if (sel.active) {
|
||||||
|
value = value.slice(0, sel.start) + char + value.slice(sel.end);
|
||||||
|
cursorPos = sel.start + char.length;
|
||||||
|
anchorPos = null;
|
||||||
|
} else {
|
||||||
|
value = value.slice(0, cursorPos) + char + value.slice(cursorPos);
|
||||||
|
cursorPos += char.length;
|
||||||
|
}
|
||||||
|
oninput(value);
|
||||||
pauseBlink();
|
pauseBlink();
|
||||||
}
|
}
|
||||||
|
|
||||||
function deleteCharBefore() {
|
function deleteCharBefore() {
|
||||||
|
if (sel.active) {
|
||||||
|
deleteSelection();
|
||||||
|
pauseBlink();
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (cursorPos > 0) {
|
if (cursorPos > 0) {
|
||||||
text = text.slice(0, cursorPos - 1) + text.slice(cursorPos);
|
value = value.slice(0, cursorPos - 1) + value.slice(cursorPos);
|
||||||
|
oninput(value);
|
||||||
cursorPos--;
|
cursorPos--;
|
||||||
pauseBlink();
|
pauseBlink();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function deleteCharAfter() {
|
function deleteCharAfter() {
|
||||||
if (cursorPos < text.length) {
|
if (sel.active) {
|
||||||
text = text.slice(0, cursorPos) + text.slice(cursorPos + 1);
|
deleteSelection();
|
||||||
|
pauseBlink();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (cursorPos < value.length) {
|
||||||
|
value = value.slice(0, cursorPos) + value.slice(cursorPos + 1);
|
||||||
|
oninput(value);
|
||||||
pauseBlink();
|
pauseBlink();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function moveCursor(delta: number) {
|
function moveCursor(delta: number, extend: boolean) {
|
||||||
const newPos = cursorPos + delta;
|
const newPos = cursorPos + delta;
|
||||||
if (newPos >= 0 && newPos <= text.length) {
|
if (newPos < 0 || newPos > value.length) return;
|
||||||
cursorPos = newPos;
|
if (extend) {
|
||||||
pauseBlink();
|
if (anchorPos === null) anchorPos = cursorPos;
|
||||||
|
} else {
|
||||||
|
anchorPos = null;
|
||||||
}
|
}
|
||||||
|
cursorPos = newPos;
|
||||||
|
pauseBlink();
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleKeydown(e: KeyboardEvent) {
|
function moveTo(pos: number, extend: boolean) {
|
||||||
console.log(e.key);
|
if (extend) {
|
||||||
|
if (anchorPos === null) anchorPos = cursorPos;
|
||||||
|
} else {
|
||||||
|
anchorPos = null;
|
||||||
|
}
|
||||||
|
cursorPos = pos;
|
||||||
|
pauseBlink();
|
||||||
|
}
|
||||||
|
|
||||||
if (e.ctrlKey) {
|
function prevWordBoundary(pos: number): number {
|
||||||
|
let i = pos;
|
||||||
|
while (i > 0 && !/\s/.test(value[i - 1])) i--;
|
||||||
|
while (i > 0 && /\s/.test(value[i - 1])) i--;
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
function nextWordBoundary(pos: number): number {
|
||||||
|
let i = pos;
|
||||||
|
while (i < value.length && !/\s/.test(value[i])) i++;
|
||||||
|
while (i < value.length && /\s/.test(value[i])) i++;
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleMouseDown(e: MouseEvent): void {
|
||||||
|
e.preventDefault();
|
||||||
|
const idx = charIndexFromEvent(e);
|
||||||
|
const clickPos = idx ?? value.length;
|
||||||
|
|
||||||
|
if (e.shiftKey) {
|
||||||
|
if (anchorPos === null) anchorPos = cursorPos;
|
||||||
|
cursorPos = clickPos;
|
||||||
|
} else {
|
||||||
|
anchorPos = clickPos;
|
||||||
|
cursorPos = clickPos;
|
||||||
|
}
|
||||||
|
isDragging = true;
|
||||||
|
pauseBlink();
|
||||||
|
}
|
||||||
|
|
||||||
|
function handlePaste(e: ClipboardEvent): void {
|
||||||
|
e.preventDefault();
|
||||||
|
const text = e.clipboardData?.getData('text/plain') ?? '';
|
||||||
|
if (text) insertChar(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
function copySelection(): void {
|
||||||
|
if (!sel.active) return;
|
||||||
|
void navigator.clipboard.writeText(getSelectedText());
|
||||||
|
}
|
||||||
|
|
||||||
|
function cutSelection(): void {
|
||||||
|
if (!sel.active) return;
|
||||||
|
void navigator.clipboard.writeText(getSelectedText());
|
||||||
|
deleteSelection();
|
||||||
|
pauseBlink();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleKeydown(e: KeyboardEvent) {
|
||||||
|
if (e.ctrlKey || e.metaKey) {
|
||||||
if (e.key === 'a' || e.key === 'A') {
|
if (e.key === 'a' || e.key === 'A') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
cursorPos = 0;
|
anchorPos = 0;
|
||||||
|
cursorPos = value.length;
|
||||||
pauseBlink();
|
pauseBlink();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (e.key === 'c' || e.key === 'C') {
|
||||||
|
e.preventDefault();
|
||||||
|
copySelection();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (e.key === 'x' || e.key === 'X') {
|
||||||
|
e.preventDefault();
|
||||||
|
cutSelection();
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (e.key === 'e' || e.key === 'E') {
|
if (e.key === 'e' || e.key === 'E') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
cursorPos = text.length;
|
anchorPos = null;
|
||||||
|
cursorPos = value.length;
|
||||||
pauseBlink();
|
pauseBlink();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -111,46 +278,50 @@
|
|||||||
deleteCharAfter();
|
deleteCharAfter();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (e.key === 'Home') {
|
||||||
|
e.preventDefault();
|
||||||
|
moveTo(0, e.shiftKey);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (e.key === 'End') {
|
||||||
|
e.preventDefault();
|
||||||
|
moveTo(value.length, e.shiftKey);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (e.key === 'ArrowLeft') {
|
if (e.key === 'ArrowLeft') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
cursorPos = 0;
|
moveTo(prevWordBoundary(cursorPos), e.shiftKey);
|
||||||
pauseBlink();
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (e.key === 'ArrowRight') {
|
if (e.key === 'ArrowRight') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
cursorPos = text.length;
|
moveTo(nextWordBoundary(cursorPos), e.shiftKey);
|
||||||
pauseBlink();
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// ignore other Ctrl combos
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Arrow keys
|
// Arrow keys
|
||||||
if (e.key === 'ArrowLeft') {
|
if (e.key === 'ArrowLeft') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
moveCursor(-1);
|
moveCursor(-1, e.shiftKey);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (e.key === 'ArrowRight') {
|
if (e.key === 'ArrowRight') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
moveCursor(1);
|
moveCursor(1, e.shiftKey);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Home / End
|
// Home / End
|
||||||
if (e.key === 'Home') {
|
if (e.key === 'Home') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
cursorPos = 0;
|
moveTo(0, e.shiftKey);
|
||||||
pauseBlink();
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (e.key === 'End') {
|
if (e.key === 'End') {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
cursorPos = text.length;
|
moveTo(value.length, e.shiftKey);
|
||||||
pauseBlink();
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -166,14 +337,18 @@
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Printable characters (length === 1 and no modifier)
|
// Printable characters
|
||||||
if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey) {
|
if (e.key.length === 1 && !e.ctrlKey && !e.altKey && !e.metaKey) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
insertChar(e.key);
|
insertChar(e.key);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Everything else (Enter, Tab, etc.) is ignored.EEE
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
gust();
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
@@ -185,7 +360,7 @@
|
|||||||
|
|
||||||
<div
|
<div
|
||||||
id="terminal-input"
|
id="terminal-input"
|
||||||
class=" relative inline-block font-terminal whitespace-nowrap outline-none"
|
class="relative inline-block font-terminal whitespace-nowrap outline-none select-none"
|
||||||
bind:this={container}
|
bind:this={container}
|
||||||
tabindex="0"
|
tabindex="0"
|
||||||
role="textbox"
|
role="textbox"
|
||||||
@@ -193,22 +368,49 @@
|
|||||||
onblur={handleBlur}
|
onblur={handleBlur}
|
||||||
onfocus={handleFocus}
|
onfocus={handleFocus}
|
||||||
onkeydown={handleKeydown}
|
onkeydown={handleKeydown}
|
||||||
|
onpaste={handlePaste}
|
||||||
|
onmousedown={handleMouseDown}
|
||||||
style="--cursor-index: {cursorPos};"
|
style="--cursor-index: {cursorPos};"
|
||||||
>
|
>
|
||||||
<span class="prompt inline-block w-[1ch] text-center">$</span>
|
<span class="prompt inline-block w-[1ch] text-center">$</span>
|
||||||
<span class="inline" aria-hidden="true">
|
<span class="inline cursor-text" aria-hidden="true">
|
||||||
{#each text.split('') as char}
|
{#each value.split('') as char, i}
|
||||||
<span class="inline-block w-[1ch] text-center">{char}</span>
|
<span
|
||||||
|
class="char inline-block w-[1ch] text-center whitespace-pre"
|
||||||
|
class:selected={isSelected(i)}
|
||||||
|
data-char-index={i}>{char}</span
|
||||||
|
>
|
||||||
{/each}
|
{/each}
|
||||||
</span>
|
</span>
|
||||||
<div
|
<div
|
||||||
|
id="curs"
|
||||||
class="cursor absolute bottom-[0.2rem] h-px w-[1ch] bg-text-primary"
|
class="cursor absolute bottom-[0.2rem] h-px w-[1ch] bg-text-primary"
|
||||||
class:animate-cursor-blink={!blinkPaused}
|
class:animate-cursor-blink={!blinkPaused && !sel.active}
|
||||||
></div>
|
></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
.cursor {
|
.cursor {
|
||||||
left: calc(var(--cursor-index) * 1ch + 8.5px + 1ch);
|
left: calc(var(--cursor-index) * 1ch + 8.5px + 1ch);
|
||||||
|
transition: all 0.1s ease;
|
||||||
|
}
|
||||||
|
.char {
|
||||||
|
transition: all linear 0.1s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.char.selected {
|
||||||
|
transition: none;
|
||||||
|
background-color: var(--color-highlight);
|
||||||
|
border-radius: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.char.selected + .char.selected {
|
||||||
|
border-top-left-radius: 0;
|
||||||
|
border-bottom-left-radius: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.char.selected:has(+ .char.selected) {
|
||||||
|
border-top-right-radius: 0;
|
||||||
|
border-bottom-right-radius: 0;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { db } from '$lib/server/db';
|
/* import { db } from '$lib/server/db';
|
||||||
import { config } from '$lib/server/db/schema';
|
import { config } from '$lib/server/db/schema';
|
||||||
import { PASSWD } from '$lib/stores/bash/etc/userData';
|
import { PASSWD } from '$lib/stores/bash/etc/userData';
|
||||||
import { error } from '@sveltejs/kit';
|
import { error } from '@sveltejs/kit';
|
||||||
@@ -36,3 +36,4 @@ export const load: PageServerLoad = async () => {
|
|||||||
throw error(500, 'Database query failed');
|
throw error(500, 'Database query failed');
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
*/
|
||||||
|
|||||||
@@ -1,12 +1,19 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import Login from '../modules/Login.svelte';
|
|
||||||
import Maintenence from '../modules/Maintenence.svelte';
|
import Maintenence from '../modules/Maintenence.svelte';
|
||||||
import Settings from '../modules/Settings.svelte';
|
import Settings from '../modules/Settings.svelte';
|
||||||
import Terminal from '../modules/Terminal.svelte';
|
import Terminal from '../modules/Terminal.svelte';
|
||||||
|
|
||||||
|
import { loadBubblePacks, loadStates } from '$lib/shimagic';
|
||||||
|
import { CHATTER } from '$lib/shimagic/chatter';
|
||||||
|
import { NEEDS } from '$lib/shimagic/needs';
|
||||||
|
import Shimeji from '$lib/shimagic/Shimeji.svelte';
|
||||||
|
|
||||||
|
const states = loadStates();
|
||||||
|
const bubblePacks = loadBubblePacks({ fps: 8, duration: 2.5 });
|
||||||
|
|
||||||
let { form, data } = $props();
|
let { form, data } = $props();
|
||||||
|
|
||||||
const MAINTENANCE = $derived(Boolean(data.config[0]));
|
const MAINTENANCE = false;
|
||||||
let username = $state('');
|
let username = $state('');
|
||||||
|
|
||||||
function welcomeSequence() {
|
function welcomeSequence() {
|
||||||
@@ -26,7 +33,7 @@
|
|||||||
terminalComponent.init(username, password); */
|
terminalComponent.init(username, password); */
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(username);
|
let bound = $state<HTMLElement>();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if MAINTENANCE}
|
{#if MAINTENANCE}
|
||||||
@@ -34,17 +41,23 @@
|
|||||||
<Maintenence />
|
<Maintenence />
|
||||||
{:else}
|
{:else}
|
||||||
<Settings></Settings>
|
<Settings></Settings>
|
||||||
<div id="main" class="relative flex h-dvh w-full items-center justify-center p-24">
|
<!-- <div
|
||||||
|
bind:this={bound}
|
||||||
|
id="main"
|
||||||
|
class="relative flex h-screen w-full items-center justify-center p-24"
|
||||||
|
>
|
||||||
<div
|
<div
|
||||||
id="wrapper1"
|
id="wrapper1"
|
||||||
class=" absolute z-35 flex flex-col items-center {form?.success ? 'outro' : ''}"
|
class=" absolute z-35 flex flex-col items-center {form?.success ? 'outro' : ''}"
|
||||||
>
|
>
|
||||||
<Login init={initializer} {form} />
|
<Login init={initializer} {form} />
|
||||||
</div>
|
</div>
|
||||||
<div id="wrapper2" class=" absolute z-4 size-4/5 opacity-0 {form?.success ? 'intro' : ''}">
|
<div id="wrapper2" class=" {form?.success ? 'intro' : ''}">
|
||||||
<Terminal {username}></Terminal>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div> -->
|
||||||
|
<Terminal username="gornodox"></Terminal>
|
||||||
|
<Shimeji {states} {bubblePacks} needsConfig={NEEDS} chatter={CHATTER} scale={4} />
|
||||||
{/if}
|
{/if}
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
<script lang="ts">
|
|
||||||
import { addToast } from '$lib/stores/toasts';
|
|
||||||
import { FileSystem } from '$lib/termos/filesystem/filesystem';
|
|
||||||
import { onMount } from 'svelte';
|
|
||||||
import UsersTable from '../../modules/panel/users/UsersTable.svelte';
|
|
||||||
import Settings from '../../modules/Settings.svelte';
|
|
||||||
import type { ToastMessage } from '../admin/util';
|
|
||||||
|
|
||||||
function bye(tm: ToastMessage): void {
|
|
||||||
console.log('Funkcja wywolana');
|
|
||||||
}
|
|
||||||
|
|
||||||
onMount(async () => {
|
|
||||||
await FileSystem.init();
|
|
||||||
|
|
||||||
document.addEventListener('keydown', (e) => {
|
|
||||||
if (e.key === 'Enter') {
|
|
||||||
addToast('success', 'Hi~', '', 5000, undefined, undefined, true, false, bye, bye);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<Settings></Settings>
|
|
||||||
<div class="size-full p-16">
|
|
||||||
<UsersTable></UsersTable>
|
|
||||||
</div>
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:ital,wght@0,100..800;1,100..800&family=Space+Mono:ital,wght@0,400;0,700;1,400;1,700&display=swap');
|
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:ital,wght@0,100..800;1,100..800&family=Space+Mono:ital,wght@0,400;0,700;1,400;1,700&display=swap');
|
||||||
|
@import url('https://fonts.googleapis.com/css2?family=Micro+5&family=Press+Start+2P&display=swap');
|
||||||
@import 'tailwindcss';
|
@import 'tailwindcss';
|
||||||
@import './animations.css';
|
@import './animations.css';
|
||||||
@custom-variant light (&:where(.light, .light *));
|
@custom-variant light (&:where(.light, .light *));
|
||||||
@@ -290,6 +291,10 @@
|
|||||||
--lang-cs: oklch(0.55 0.27927 141.446);
|
--lang-cs: oklch(0.55 0.27927 141.446);
|
||||||
--lang-cpp: oklch(0.6 0.15576 6.88);
|
--lang-cpp: oklch(0.6 0.15576 6.88);
|
||||||
|
|
||||||
|
* {
|
||||||
|
transition: var(--transition-standard);
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
|
||||||
#underline-bg
|
#underline-bg
|
||||||
|
|||||||