Shimeji with physics added !!!!!

This commit is contained in:
2026-03-22 08:14:31 +01:00
parent c3f1af6818
commit 2fa12e22d5
9 changed files with 724 additions and 28 deletions
+5
View File
@@ -4,6 +4,7 @@ export type User = {
readonly uid: number; // Normal user 1000+ System user 1-999 root - 0 //TODO: Make a formated type
readonly gid: number; // Primary group | 'Users' 1000 - Others - 1000+ root - 0 //TODO: Make a formated type
home: string; //TODO: Make a formated type
accesible: boolean;
history: string[];
cwd?: number; //TODO: Make a formated type
pwd?: number; //TODO: Make a formated type
@@ -16,6 +17,7 @@ export const PASSWD: User[] = [
uid: 0,
gid: 0,
home: '/',
accesible: false,
history: []
},
{
@@ -24,6 +26,7 @@ export const PASSWD: User[] = [
uid: 1000,
gid: 1000,
home: '/home/admin',
accesible: true,
history: []
},
{
@@ -32,6 +35,7 @@ export const PASSWD: User[] = [
uid: 1001,
gid: 1000,
home: '/home/user',
accesible: true,
history: []
},
{
@@ -40,6 +44,7 @@ export const PASSWD: User[] = [
uid: 1002,
gid: 1000,
home: '/home/gornodox',
accesible: true,
history: []
}
];
+273
View File
@@ -0,0 +1,273 @@
export class Shimeji {
private element: HTMLElement;
private x: number;
private y: number;
private velocityX: number = 0;
private velocityY: number = 0;
// Mouse tracking
private mouseX: number = 0;
private mouseY: number = 0;
private mouseAccelX: number = 0;
private mouseAccelY: number = 0;
private isBeingDragged: boolean = false;
private rafId: number | null = null;
private prevDeltaTime: number = 0;
// Physics parameters
private readonly RESTITUTION: number = 0.6; // 1 perfect bounciness 0 no bounce
private readonly STIFFNESS: number = 100; // Spring constant
private readonly DAMPING: number = 1; // Air resistance 1 - no resistance 0.1 high air density
private readonly MASS: number = 10.0; // Mass
// Gravity (pixels per frame squared)
private gravity: number = 10;
// Boundaries
private bounds: { minX: number; minY: number; maxX: number; maxY: number };
// Optional forces
private wind: number = 0;
private friction: number = 0.8;
constructor(element: HTMLElement) {
this.element = element;
// Initialize bounds (will update on resize)
this.bounds = {
minX: 0,
minY: 0,
maxX: window.innerWidth,
maxY: window.innerHeight
};
// Start with element at center
this.x = window.innerWidth / 2;
this.y = window.innerHeight / 2;
this.updateBounds();
window.addEventListener('resize', () => this.updateBounds());
console.log(this.element.getBoundingClientRect());
this.setupDragEvents();
}
private updateBounds(): void {
this.bounds = {
minX: 0,
minY: 0,
maxX: window.innerWidth,
maxY: window.innerHeight
};
}
start(): void {
if (this.rafId !== null) return;
const firstFrame = (delta: number) => {
this.prevDeltaTime = delta;
this.rafId = requestAnimationFrame(animate);
}
const animate = (delta: number) => {
const dt: number = Math.min(delta - this.prevDeltaTime, 0.05);
this.prevDeltaTime = delta;
this.updatePhysics(dt);
this.applyBoundaries();
this.render();
this.rafId = requestAnimationFrame(animate);
};
this.rafId = requestAnimationFrame(firstFrame);
}
stop(): void {
if (this.rafId !== null) {
cancelAnimationFrame(this.rafId);
this.rafId = null;
}
}
private setupDragEvents(): void {
this.element.addEventListener('mousedown', (e) => {
e.preventDefault();
this.isBeingDragged = true;
this.element.style.cursor = 'grabbing';
const parent = this.element.parentElement;
if(parent) parent.style.cursor = 'grabbing';
const rect = this.element.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
const pivotX = (x / rect.width) * 100;
const pivotY = (y / rect.height) * 100;
this.element.style.transformOrigin = `${pivotX}% ${pivotY}%`;
});
document.addEventListener('mousemove', (e) => {
this.mouseX = e.pageX;
this.mouseY = e.pageY;
this.mouseAccelX = e.movementX * 0.1;
this.mouseAccelY = e.movementY * 0.1;
});
document.addEventListener('mouseup', (e) => {
if(this.isBeingDragged) {
this.isBeingDragged = false;
this.element.style.cursor = 'grab';
const parent = this.element.parentElement;
if(parent) parent.style.cursor = 'auto';
}
});
this.element.addEventListener('dragstart', (e) => {
e.preventDefault();
});
}
private updatePhysics(dt: number): void {
if (this.isBeingDragged) {
console.log(this.element.style.transformOrigin);
// Spring force toward mouse
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 = Math.abs(forceX / this.MASS) < 0.0001 ? 0 : (forceX / this.MASS);
const accelerationY = Math.abs(forceY / this.MASS) < 0.0001 ? 0 : (forceY / this.MASS);
console.log(accelerationX, accelerationY);
// Update velocity with acceleration
this.velocityX += accelerationX * dt;
this.velocityY += accelerationY * dt;
this.velocityX *= 0.8;
this.velocityY *= 0.8;
}
// Apply gravity (always present)
this.velocityY += this.gravity;
this.velocityX *= this.DAMPING;
this.velocityY *= this.DAMPING;
// Apply additional friction when on ground (touching bottom)
if (this.y + this.getElementHeight() >= this.bounds.maxY) {
this.velocityX *= this.friction;
}
// Update position with velocity
this.x = this.x + this.velocityX * dt;
this.y = this.y + this.velocityY * dt;
}
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 (account for element width with center positioning)
const leftBound = elementWidth / 2;
const rightBound = this.bounds.maxX - elementWidth / 2;
if (this.x < leftBound) {
this.x = leftBound;
this.velocityX = -(this.RESTITUTION) * this.velocityX;
} else if (this.x > rightBound) {
this.x = rightBound;
this.velocityX = -(this.RESTITUTION) * this.velocityX;
}
// Y-axis boundaries
const topBound = elementHeight / 2;
const bottomBound = this.bounds.maxY - elementHeight / 2;
if (this.y < topBound) {
this.y = topBound;
this.velocityY = -(this.RESTITUTION) * this.velocityY;
} else if (this.y > bottomBound) {
this.y = bottomBound;
this.velocityY = -(this.RESTITUTION) * this.velocityY;
if (Math.abs(this.velocityY) < 0.3) {
this.velocityY = 0;
}
}
}
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;
}
// 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;
}
getState() {
return {
x: this.x,
y: this.y,
velocityX: this.velocityX,
velocityY: this.velocityY,
mouseX: this.mouseX,
mouseY: this.mouseY
};
}
moveTo(pos: number) {
}
}
+371
View File
@@ -0,0 +1,371 @@
// Shimeji.ts
export class Shimeji {
private element: HTMLElement;
// Position and velocity
private x: number = 0;
private y: number = 0;
private velocityX: number = 0;
private velocityY: number = 0;
// Mouse tracking
private mouseX: number = 0;
private mouseY: number = 0;
private mouseAccelX: number = 0;
private mouseAccelY: number = 0;
// Throw detection - track mouse movement history
private mouseHistory: Array<{x: number, y: number, time: number}> = [];
private readonly HISTORY_LENGTH: number = 5;
private isBeingDragged: boolean = false;
private rafId: number | null = null;
// Physics parameters
private readonly STIFFNESS: number = 0.85;
private readonly DAMPING: number = 0.6;
private readonly MASS: number = 1.0;
// Gravity (pixels per frame squared)
private gravity: number = 10;
// Bounce coefficients (energy retention - lower = less bounce)
private readonly WALL_BOUNCE: number = 0.5; // Walls lose 50% energy
private readonly FLOOR_BOUNCE: number = 0.6; // Floor loses 40% energy (realistic)
private readonly CEILING_BOUNCE: number = 0.4; // Ceiling loses 60% energy
// Minimum velocity to continue bouncing
private readonly MIN_BOUNCE_VELOCITY: number = 2;
// Boundaries
private bounds: { minX: number; minY: number; maxX: number; maxY: number };
// Optional forces
private wind: number = 0;
private friction: number = 0.98;
// Track if on ground for additional effects
private wasOnGround: boolean = false;
private bounceCount: number = 0;
constructor(element: HTMLElement) {
this.element = element;
// Initialize bounds (will update on resize)
this.bounds = {
minX: 0,
minY: 0,
maxX: window.innerWidth,
maxY: window.innerHeight
};
// Start with element at center
this.x = window.innerWidth / 2;
this.y = window.innerHeight / 2;
this.updateBounds();
window.addEventListener('resize', () => this.updateBounds());
this.setupDragEvents();
}
private updateBounds(): void {
this.bounds = {
minX: 0,
minY: 0,
maxX: window.innerWidth,
maxY: window.innerHeight
};
}
start(): void {
if (this.rafId !== null) return;
const animate = () => {
this.updatePhysics();
this.applyBoundaries();
this.render();
this.rafId = requestAnimationFrame(animate);
};
this.rafId = requestAnimationFrame(animate);
}
stop(): void {
if (this.rafId !== null) {
cancelAnimationFrame(this.rafId);
this.rafId = null;
}
}
private setupDragEvents(): void {
this.element.addEventListener('mousedown', (e) => {
e.preventDefault();
this.isBeingDragged = true;
this.element.style.cursor = 'grabbing';
// Clear mouse history on new drag
this.mouseHistory = [];
});
// Track mouse movement globally for better throw detection
document.addEventListener('mousemove', (e) => {
if (this.isBeingDragged) {
this.mouseX = e.pageX;
this.mouseY = e.pageY;
this.mouseAccelX = e.movementX;
this.mouseAccelY = e.movementY;
// Store mouse position history for throw calculation
this.mouseHistory.push({
x: e.pageX,
y: e.pageY,
time: Date.now()
});
// Keep only recent history
if (this.mouseHistory.length > this.HISTORY_LENGTH) {
this.mouseHistory.shift();
}
}
});
this.element.addEventListener('mouseup', (e) => {
if(this.isBeingDragged) {
this.isBeingDragged = false;
this.element.style.cursor = 'grab';
// Calculate throw velocity based on mouse movement speed
this.applyThrowVelocity();
// Reset mouse history
this.mouseHistory = [];
}
});
this.element.addEventListener('dragstart', (e) => {
e.preventDefault();
});
}
private applyThrowVelocity(): void {
if (this.mouseHistory.length < 2) return;
// Get oldest and newest mouse positions
const oldest = this.mouseHistory[0];
const newest = this.mouseHistory[this.mouseHistory.length - 1];
// Calculate time delta in seconds
const timeDelta = (newest.time - oldest.time) / 1000;
if (timeDelta === 0) return;
// Calculate velocity in pixels per second
let throwVelX = (newest.x - oldest.x) / timeDelta;
let throwVelY = (newest.y - oldest.y) / timeDelta;
// Cap maximum throw velocity to prevent ridiculous speeds
const MAX_THROW_SPEED = 50;
throwVelX = Math.min(Math.max(throwVelX, -MAX_THROW_SPEED), MAX_THROW_SPEED);
throwVelY = Math.min(Math.max(throwVelY, -MAX_THROW_SPEED), MAX_THROW_SPEED);
// Apply throw velocity (divide by ~60 to convert from per-second to per-frame)
this.velocityX += throwVelX / 60;
this.velocityY += throwVelY / 60;
// Add a little extra oomph based on acceleration
if (Math.abs(this.mouseAccelX) > 5) {
this.velocityX += this.mouseAccelX / 30;
}
if (Math.abs(this.mouseAccelY) > 5) {
this.velocityY += this.mouseAccelY / 30;
}
}
private updatePhysics(): void {
// Apply spring force toward mouse when dragging
if (this.isBeingDragged) {
const dx = this.mouseX - this.x;
const dy = this.mouseY - this.y;
const forceX = dx * this.STIFFNESS;
const forceY = dy * this.STIFFNESS;
// Apply force to acceleration (F = ma)
const accelerationX = (forceX + this.mouseAccelX) / this.MASS;
const accelerationY = (forceY + this.mouseAccelY) / this.MASS;
// Update velocity with acceleration
this.velocityX += accelerationX;
this.velocityY += accelerationY;
}
// Apply gravity (always present, but stronger when not dragging)
if(!this.isBeingDragged) {
this.velocityY += this.gravity;
} else {
// Slight gravity even when dragging for realism
this.velocityY += this.gravity * 0.3;
}
// Apply wind (optional horizontal force)
if(this.y > 10) this.velocityX += this.wind;
// Apply damping (air resistance)
this.velocityX *= this.DAMPING;
this.velocityY *= this.DAMPING;
// Update position with velocity
this.x += this.velocityX;
this.y += this.velocityY;
}
private getElementHeight(): number {
return this.element.offsetHeight;
}
private getElementWidth(): number {
return this.element.offsetWidth;
}
private applyBoundaries(): void {
const elementWidth = this.getElementWidth();
const elementHeight = this.getElementHeight();
// X-axis boundaries with realistic bounce
const leftBound = elementWidth / 2;
const rightBound = this.bounds.maxX - elementWidth / 2;
if (this.x < leftBound) {
this.x = leftBound;
// Bounce with energy loss
this.velocityX = -Math.abs(this.velocityX) * this.WALL_BOUNCE;
// Stop if bounce is too small
if (Math.abs(this.velocityX) < this.MIN_BOUNCE_VELOCITY) {
this.velocityX = 0;
}
} else if (this.x > rightBound) {
this.x = rightBound;
this.velocityX = -Math.abs(this.velocityX) * this.WALL_BOUNCE;
if (Math.abs(this.velocityX) < this.MIN_BOUNCE_VELOCITY) {
this.velocityX = 0;
}
}
// Y-axis boundaries with realistic bounce
const topBound = elementHeight / 2;
const bottomBound = this.bounds.maxY - elementHeight / 2;
// Ceiling collision
if (this.y < topBound) {
this.y = topBound;
this.velocityY = -this.velocityY * this.CEILING_BOUNCE;
// Stop tiny bouncing on ceiling
if (Math.abs(this.velocityY) < this.MIN_BOUNCE_VELOCITY) {
this.velocityY = 0;
}
}
// Floor collision
else if (this.y > bottomBound) {
this.y = bottomBound;
const impactSpeed = Math.abs(this.velocityY);
// Only bounce if impact speed is significant
if (impactSpeed > this.MIN_BOUNCE_VELOCITY) {
// Apply floor bounce with energy loss
this.velocityY = -this.velocityY * this.FLOOR_BOUNCE;
// Bounce gets smaller each time naturally due to energy loss
this.bounceCount++;
// Apply ground friction on bounce
this.velocityX *= this.groundFriction;
// Optional: Visual feedback for bounce
// console.log(`Bounce ${this.bounceCount}: impact speed ${impactSpeed.toFixed(2)}, new velocity ${this.velocityY.toFixed(2)}`);
} else {
// Stop bouncing when energy is too low
this.velocityY = 0;
this.wasOnGround = true;
}
} else {
this.wasOnGround = false;
// Reset bounce count when in air
if (!this.isBeingDragged && this.velocityY !== 0) {
this.bounceCount = 0;
}
}
}
private get groundFriction(): number {
// More friction when moving fast
const speed = Math.abs(this.velocityX);
if (speed > 10) return this.friction * 0.9;
if (speed > 5) return this.friction * 0.95;
return this.friction;
}
private render(): void {
this.element.style.transform = `translate(${this.x}px, ${this.y}px) translateY(-50%)`;
}
// Public methods to control physics
setGravity(value: number): void {
this.gravity = value;
}
setWind(value: number): void {
this.wind = value;
}
setPhysics(stiffness: number, damping: number, mass: number = 1.0): void {
(this as any).STIFFNESS = stiffness;
(this as any).DAMPING = damping;
(this as any).MASS = mass;
}
setFriction(value: number): void {
this.friction = value;
}
// Configure bounce properties
setBounceProperties(wall: number, floor: number, ceiling: number = 0.4): void {
(this as any).WALL_BOUNCE = Math.min(Math.max(wall, 0), 1);
(this as any).FLOOR_BOUNCE = Math.min(Math.max(floor, 0), 1);
(this as any).CEILING_BOUNCE = Math.min(Math.max(ceiling, 0), 1);
}
// Add impulse (like a jump)
addImpulse(x: number, y: number): void {
this.velocityX += x;
this.velocityY += y;
}
// Reset position
resetPosition(x?: number, y?: number): void {
this.x = x ?? this.bounds.maxX / 2;
this.y = y ?? this.bounds.maxY / 2;
this.velocityX = 0;
this.velocityY = 0;
this.isBeingDragged = false;
this.bounceCount = 0;
}
getState() {
return {
x: this.x,
y: this.y,
velocityX: this.velocityX,
velocityY: this.velocityY,
mouseX: this.mouseX,
mouseY: this.mouseY,
isBeingDragged: this.isBeingDragged,
isOnGround: this.wasOnGround,
bounceCount: this.bounceCount
};
}
}
+11 -20
View File
@@ -4,43 +4,34 @@
import { ArrowRight, ChevronLeft, ChevronRight, CircleAlert, Lock } from "@lucide/svelte";
import type { effect } from "zod/v3";
let formElem: HTMLElement;
let {init, form}: { init: (formData: FormData) => void, form: any} = $props();
const USERS = PASSWD.filter((user) => user.accesible == true);
const basePath: string = '/src/lib/assets/login/';
let userIndex: number = $state(3);
$inspect(userIndex);
let username: string = $state('gornodox');
let userImage: string = $derived(`${basePath}${username}.png`);
function changeUser(direction: 0 | 1) {
if(direction === 0) {
userIndex--;
document.getElementById('username')?.classList.add('switchR');
}
else {
userIndex++;
document.getElementById('username')?.classList.add('switchL');
}
if(userIndex >= PASSWD.length) userIndex = 0;
if(userIndex < 0) userIndex = PASSWD.length - 1;
if(direction === 0) userIndex--;
else userIndex++;
if(userIndex >= USERS.length) userIndex = 0;
if(userIndex < 0) userIndex = USERS.length - 1;
const user = PASSWD[userIndex];
const user = USERS[userIndex];
username = user.username;
}
</script>
<div id="wrapper" class=" flex flex-col items-center" class:outro={form?.success}>
<img class="rounded-full mb-4 border-primary-dark border-2" src={userImage} alt="" width="80" height="80" />
<img class="rounded-full mb-4 border-primary-dark border-2" src={`${basePath}${username}.png`} onerror={(event) => {(event.currentTarget as HTMLImageElement).src = `${basePath}default.png`; return false;}} alt="user avatar" width="80" height="80" />
<div id="name" class=" relative flex flex-row items-center text-text-muted-dark justify-center gap-4 w-1/2">
<button onclick={() => changeUser(0)}
class=" active:-translate-x-0.5 hover:text-primary-hover-dark"><ChevronLeft size={16} strokeWidth={2} /></button>
<strong id="username" class=" mx-auto" onanimationend={(event) => {event.currentTarget.innerText = username; event.currentTarget.classList.remove('switchR', 'switchL');}}>gornodox</strong>
<strong bind:this={elem} class=" mx-auto">{username}</strong>
<button onclick={() => changeUser(1)}
class=" active:translate-x-0.5 hover:text-primary-hover-dark"><ChevronRight size={16} strokeWidth={2} /></button>
</div>
@@ -70,11 +61,11 @@
}
.switchL {
animation: fadeSlideLeft 1s forwards cubic-bezier(.4,.7,0,.99);
animation: fadeSlideLeft .75s forwards cubic-bezier(.4,.7,0,.99);
}
.switchR {
animation: fadeSlideRight 1s forwards cubic-bezier(.4,.7,0,.99);
animation: fadeSlideRight .75s forwards cubic-bezier(.4,.7,0,.99);
}
+53
View File
@@ -0,0 +1,53 @@
<script lang="ts">
import { Shimeji } from "$lib/stores/shimeji";
import { onMount } from "svelte";
const drag: number = 3;
const speed: number = 2;
let shimeji: Shimeji;
let sprite: HTMLElement;
let pos: number = $state(0);
let vel: number = $state(0);
let targetPos: number = $state(0);
let rafId: number;
function genRandomPos(min: number, max: number): number{
const out = Math.random() * (max - min) + min;
return out;
}
onMount(() => {
shimeji = new Shimeji(sprite);
shimeji.start();
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));
}
});
return () => {
shimeji.stop();
};
})
</script>
<div class=" absolute z-100 size-full overflow-clip ">
<div bind:this={sprite} class=" cursor-grab transform-flat -translate-x-1/2 origin-bottom absolute bg-amber-400 size-20"></div>
</div>
<style>
</style>
+2 -2
View File
@@ -11,9 +11,9 @@
const printOutput = (e: HTMLElement, d: PrintData): void => print(e, d);
export async function init(password: string) {
export async function init(username: string, password: string) {
try {
terminal = await initTerminal({ username: 'gornodox', password}, callbackInit, 'en_US');
terminal = await initTerminal({username, password}, callbackInit, 'en_US');
updateTerminal();
} catch (error) {
console.error('terminal init failed', error);
+5 -2
View File
@@ -23,10 +23,13 @@
}
function initializer(formData: FormData) {
console.log(formData);
if(form?.error) return;
const password = formData.get("password")?.toString();
if(!password) throw new Error("password is null or undefined");
terminalComponent.init(password)
const username = formData.get("username")?.toString();
if(!password || !username) throw new Error("password or username is null or undefined");
terminalComponent.init(username, password)
}
</script>
+2 -2
View File
@@ -1,9 +1,9 @@
<script lang="ts">
import Login from "../../modules/Login.svelte";
import Shimeji from "../../modules/Shimeji.svelte";
</script>
<Login />
<Shimeji />
+1 -1
View File
@@ -4,7 +4,7 @@
@custom-variant light (&:where(.light, .light *));
* {
transition: all 0.2s ease-in allow-discrete;
/* transition: all 0.2s ease-in allow-discrete; */
}
@utility scroll-hidden {