physics use private class fields

This commit is contained in:
“chrisshank” 2024-12-19 00:43:29 -08:00
parent d0567e6d2c
commit cca4e6969b
1 changed files with 60 additions and 60 deletions

View File

@ -9,55 +9,55 @@ await init();
export class FolkPhysics extends FolkBaseSet { export class FolkPhysics extends FolkBaseSet {
static override tagName = 'folk-physics'; static override tagName = 'folk-physics';
private static PHYSICS_SCALE = 0.1; static #PHYSICS_SCALE = 0.1;
private world?: RAPIER.World; #world?: RAPIER.World;
private bodies: Map<FolkShape, RAPIER.RigidBody> = new Map(); #bodies: Map<FolkShape, RAPIER.RigidBody> = new Map();
private elementToRect: Map<FolkShape, DOMRectTransform> = new Map(); #elementToRect: Map<FolkShape, DOMRectTransform> = new Map();
private animationFrameId?: number; #animationFrameId?: number;
private lastTimestamp?: number; #lastTimestamp?: number;
private integrator = TransformIntegrator.register('physics'); #integrator = TransformIntegrator.register('physics');
connectedCallback() { connectedCallback() {
super.connectedCallback(); super.connectedCallback();
this.world = new RAPIER.World({ this.#world = new RAPIER.World({
x: 0.0, x: 0.0,
y: 5, y: 5,
}); });
this.createContainer(); this.#createContainer();
this.startSimulation(); this.#startSimulation();
} }
disconnectedCallback() { disconnectedCallback() {
super.disconnectedCallback(); super.disconnectedCallback();
if (this.animationFrameId) { if (this.#animationFrameId) {
cancelAnimationFrame(this.animationFrameId); cancelAnimationFrame(this.#animationFrameId);
} }
// Cleanup physics resources // Cleanup physics resources
this.bodies.clear(); this.#bodies.clear();
this.elementToRect.clear(); this.#elementToRect.clear();
this.world?.free(); this.#world?.free();
} }
override update(changedProperties: PropertyValues<this>) { override update(changedProperties: PropertyValues<this>) {
super.update(changedProperties); super.update(changedProperties);
if (!this.world || this.sourcesMap.size !== this.sourceElements.size) return; if (!this.#world || this.sourcesMap.size !== this.sourceElements.size) return;
this.updatePhysicsBodies(); this.#updatePhysicsBodies();
} }
private updatePhysicsBodies() { #updatePhysicsBodies() {
// Remove bodies for elements that no longer exist // Remove bodies for elements that no longer exist
for (const [element, body] of this.bodies) { for (const [element, body] of this.#bodies) {
if (!this.sourceElements.has(element)) { if (!this.sourceElements.has(element)) {
this.world!.removeRigidBody(body); this.#world!.removeRigidBody(body);
this.bodies.delete(element); this.#bodies.delete(element);
} }
} }
@ -67,39 +67,39 @@ export class FolkPhysics extends FolkBaseSet {
const rect = this.sourcesMap.get(element); const rect = this.sourcesMap.get(element);
if (!(rect instanceof DOMRectTransform)) continue; if (!(rect instanceof DOMRectTransform)) continue;
if (!this.bodies.has(element)) { if (!this.#bodies.has(element)) {
// Create new rigid body matching the element's position // Create new rigid body matching the element's position
const bodyDesc = RAPIER.RigidBodyDesc.dynamic() const bodyDesc = RAPIER.RigidBodyDesc.dynamic()
.setTranslation( .setTranslation(
(rect.x + rect.width / 2) * FolkPhysics.PHYSICS_SCALE, (rect.x + rect.width / 2) * FolkPhysics.#PHYSICS_SCALE,
(rect.y + rect.height / 2) * FolkPhysics.PHYSICS_SCALE, (rect.y + rect.height / 2) * FolkPhysics.#PHYSICS_SCALE,
) )
.setRotation(rect.rotation); .setRotation(rect.rotation);
const body = this.world!.createRigidBody(bodyDesc); const body = this.#world!.createRigidBody(bodyDesc);
// Scale down the collider size // Scale down the collider size
const colliderDesc = RAPIER.ColliderDesc.cuboid( const colliderDesc = RAPIER.ColliderDesc.cuboid(
(rect.width / 2) * FolkPhysics.PHYSICS_SCALE, (rect.width / 2) * FolkPhysics.#PHYSICS_SCALE,
(rect.height / 2) * FolkPhysics.PHYSICS_SCALE, (rect.height / 2) * FolkPhysics.#PHYSICS_SCALE,
).setTranslation(0, 0); ).setTranslation(0, 0);
this.world!.createCollider(colliderDesc, body); this.#world!.createCollider(colliderDesc, body);
this.bodies.set(element, body); this.#bodies.set(element, body);
// Set element's rotation origin to top-left // Set element's rotation origin to top-left
rect.transformOrigin = { x: 0, y: 0 }; rect.transformOrigin = { x: 0, y: 0 };
} }
// Update existing body // Update existing body
const body = this.bodies.get(element)!; const body = this.#bodies.get(element)!;
if (element === document.activeElement) { if (element === document.activeElement) {
body.setBodyType(RAPIER.RigidBodyType.KinematicPositionBased, true); body.setBodyType(RAPIER.RigidBodyType.KinematicPositionBased, true);
body.setTranslation( body.setTranslation(
{ {
x: (rect.x + rect.width / 2) * FolkPhysics.PHYSICS_SCALE, x: (rect.x + rect.width / 2) * FolkPhysics.#PHYSICS_SCALE,
y: (rect.y + rect.height / 2) * FolkPhysics.PHYSICS_SCALE, y: (rect.y + rect.height / 2) * FolkPhysics.#PHYSICS_SCALE,
}, },
true, true,
); );
@ -108,33 +108,33 @@ export class FolkPhysics extends FolkBaseSet {
// Update collider size when switching back to dynamic // Update collider size when switching back to dynamic
const collider = body.collider(0); const collider = body.collider(0);
if (collider) { if (collider) {
this.world!.removeCollider(collider, true); this.#world!.removeCollider(collider, true);
const newColliderDesc = RAPIER.ColliderDesc.cuboid( const newColliderDesc = RAPIER.ColliderDesc.cuboid(
(rect.width / 2) * FolkPhysics.PHYSICS_SCALE, (rect.width / 2) * FolkPhysics.#PHYSICS_SCALE,
(rect.height / 2) * FolkPhysics.PHYSICS_SCALE, (rect.height / 2) * FolkPhysics.#PHYSICS_SCALE,
).setTranslation(0, 0); ).setTranslation(0, 0);
this.world!.createCollider(newColliderDesc, body); this.#world!.createCollider(newColliderDesc, body);
} }
body.setBodyType(RAPIER.RigidBodyType.Dynamic, true); body.setBodyType(RAPIER.RigidBodyType.Dynamic, true);
} }
} }
} }
private startSimulation() { #startSimulation() {
const step = async (timestamp: number) => { const step = async (timestamp: number) => {
if (!this.lastTimestamp) { if (!this.#lastTimestamp) {
this.lastTimestamp = timestamp; this.#lastTimestamp = timestamp;
} }
if (this.world) { if (this.#world) {
this.world.step(); this.#world.step();
// Yield physics effects // Yield physics effects
for (const [shape, body] of this.bodies) { for (const [shape, body] of this.#bodies) {
const position = body.translation(); const position = body.translation();
this.integrator.yield(shape, { this.#integrator.yield(shape, {
x: position.x / FolkPhysics.PHYSICS_SCALE - shape.width / 2, x: position.x / FolkPhysics.#PHYSICS_SCALE - shape.width / 2,
y: position.y / FolkPhysics.PHYSICS_SCALE - shape.height / 2, y: position.y / FolkPhysics.#PHYSICS_SCALE - shape.height / 2,
rotation: body.rotation(), rotation: body.rotation(),
width: shape.width, width: shape.width,
height: shape.height, height: shape.height,
@ -142,14 +142,14 @@ export class FolkPhysics extends FolkBaseSet {
} }
// Get integrated results and update physics state // Get integrated results and update physics state
const results = await this.integrator.integrate(); const results = await this.#integrator.integrate();
for (const [shape, result] of results) { for (const [shape, result] of results) {
const body = this.bodies.get(shape); const body = this.#bodies.get(shape);
if (body) { if (body) {
body.setTranslation( body.setTranslation(
{ {
x: (result.x + result.width / 2) * FolkPhysics.PHYSICS_SCALE, x: (result.x + result.width / 2) * FolkPhysics.#PHYSICS_SCALE,
y: (result.y + result.height / 2) * FolkPhysics.PHYSICS_SCALE, y: (result.y + result.height / 2) * FolkPhysics.#PHYSICS_SCALE,
}, },
true, true,
); );
@ -158,33 +158,33 @@ export class FolkPhysics extends FolkBaseSet {
} }
} }
this.animationFrameId = requestAnimationFrame(step); this.#animationFrameId = requestAnimationFrame(step);
}; };
this.animationFrameId = requestAnimationFrame(step); this.#animationFrameId = requestAnimationFrame(step);
} }
private createContainer() { #createContainer() {
if (!this.world) return; if (!this.#world) return;
// Create a single rigid body for the container // Create a single rigid body for the container
const containerDesc = RAPIER.RigidBodyDesc.fixed(); const containerDesc = RAPIER.RigidBodyDesc.fixed();
const container = this.world.createRigidBody(containerDesc); const container = this.#world.createRigidBody(containerDesc);
// Scale down the container walls // Scale down the container walls
const vertices = [ const vertices = [
// Floor: left to right // Floor: left to right
{ x: -100, y: this.clientHeight * FolkPhysics.PHYSICS_SCALE }, { x: -100, y: this.clientHeight * FolkPhysics.#PHYSICS_SCALE },
{ x: 100, y: this.clientHeight * FolkPhysics.PHYSICS_SCALE }, { x: 100, y: this.clientHeight * FolkPhysics.#PHYSICS_SCALE },
// Right wall: bottom to top // Right wall: bottom to top
{ x: this.clientWidth * FolkPhysics.PHYSICS_SCALE, y: this.clientHeight * FolkPhysics.PHYSICS_SCALE }, { x: this.clientWidth * FolkPhysics.#PHYSICS_SCALE, y: this.clientHeight * FolkPhysics.#PHYSICS_SCALE },
{ x: this.clientWidth * FolkPhysics.PHYSICS_SCALE, y: -100 }, { x: this.clientWidth * FolkPhysics.#PHYSICS_SCALE, y: -100 },
// Ceiling: right to left // Ceiling: right to left
{ x: 100, y: 0 }, { x: 100, y: 0 },
{ x: -100, y: 0 }, { x: -100, y: 0 },
// Left wall: top to bottom // Left wall: top to bottom
{ x: 0, y: -100 }, { x: 0, y: -100 },
{ x: 0, y: this.clientHeight * FolkPhysics.PHYSICS_SCALE }, { x: 0, y: this.clientHeight * FolkPhysics.#PHYSICS_SCALE },
]; ];
const indices = [ const indices = [
@ -201,6 +201,6 @@ export class FolkPhysics extends FolkBaseSet {
const vertexArray = new Float32Array(vertices.flatMap((v) => [v.x, v.y])); const vertexArray = new Float32Array(vertices.flatMap((v) => [v.x, v.y]));
const indexArray = new Uint32Array(indices); const indexArray = new Uint32Array(indices);
this.world.createCollider(RAPIER.ColliderDesc.polyline(vertexArray, indexArray), container); this.#world.createCollider(RAPIER.ColliderDesc.polyline(vertexArray, indexArray), container);
} }
} }