Compare commits

..

No commits in common. "9b03e6c2cbb326de89a625b6de363156a9596bde" and "f1c991bd3ef4c96e0a502abc6f1ae1950d0343c1" have entirely different histories.

12 changed files with 488 additions and 502 deletions

View File

@ -21,6 +21,5 @@
"titleBar.inactiveBackground": "#33005599", "titleBar.inactiveBackground": "#33005599",
"titleBar.inactiveForeground": "#e7e7e799" "titleBar.inactiveForeground": "#e7e7e799"
}, },
"peacock.remoteColor": "330055", "peacock.remoteColor": "330055"
"liveServer.settings.port": 5501
} }

407
bundle.js
View File

@ -6,9 +6,6 @@ const Constants = {
TWO_PI: Math.PI * 2 TWO_PI: Math.PI * 2
}; };
const map = (value, x1, y1, x2, y2)=>(value - x1) * (y2 - x2) / (y1 - x1) + x2; const map = (value, x1, y1, x2, y2)=>(value - x1) * (y2 - x2) / (y1 - x1) + x2;
const Constants1 = {
TWO_PI: Math.PI * 2
};
class Vector { class Vector {
x; x;
y; y;
@ -172,12 +169,10 @@ class Vector {
copy() { copy() {
return new Vector(this.x, this.y, this.z); return new Vector(this.x, this.y, this.z);
} }
drawDot() { drawDot(ctx) {
if (!doodler) return; ctx.beginPath();
doodler.dot(this, { ctx.arc(this.x, this.y, 2, 0, Constants.TWO_PI);
weight: 2, ctx.fill();
color: 'red'
});
} }
static fromAngle(angle, v) { static fromAngle(angle, v) {
if (v === undefined || v === null) { if (v === undefined || v === null) {
@ -191,7 +186,7 @@ class Vector {
return Vector.fromAngle(Math.random() * (Math.PI * 2), v); return Vector.fromAngle(Math.random() * (Math.PI * 2), v);
} }
static random3D(v) { static random3D(v) {
const angle = Math.random() * Constants1.TWO_PI; const angle = Math.random() * Constants.TWO_PI;
const vz = Math.random() * 2 - 1; const vz = Math.random() * 2 - 1;
const mult = Math.sqrt(1 - vz * vz); const mult = Math.sqrt(1 - vz * vz);
const vx = mult * Math.cos(angle); const vx = mult * Math.cos(angle);
@ -237,230 +232,6 @@ class Vector {
return Vector.dot(Vector.sub(a, b), Vector.sub(a, b)); return Vector.dot(Vector.sub(a, b), Vector.sub(a, b));
} }
} }
const init = (opt)=>{
if (window.doodler) throw 'Doodler has already been initialized in this window';
window.doodler = new Doodler(opt);
window.doodler.init();
};
class Doodler {
ctx;
_canvas;
layers = [];
bg;
framerate;
get width() {
return this.ctx.canvas.width;
}
get height() {
return this.ctx.canvas.height;
}
draggables = [];
constructor({ width , height , canvas , bg , framerate }){
if (!canvas) {
canvas = document.createElement('canvas');
document.body.append(canvas);
}
this.bg = bg || 'white';
this.framerate = framerate || 60;
canvas.width = width;
canvas.height = height;
this._canvas = canvas;
const ctx = canvas.getContext('2d');
console.log(ctx);
if (!ctx) throw 'Unable to initialize Doodler: Canvas context not found';
this.ctx = ctx;
}
init() {
this._canvas.addEventListener('mousedown', (e)=>this.onClick(e));
this._canvas.addEventListener('mouseup', (e)=>this.offClick(e));
this._canvas.addEventListener('mousemove', (e)=>{
const rect = this._canvas.getBoundingClientRect();
this.mouseX = e.clientX - rect.left;
this.mouseY = e.clientY - rect.top;
for (const d of this.draggables.filter((d)=>d.beingDragged)){
d.point.add(e.movementX, e.movementY);
}
});
this.startDrawLoop();
}
timer;
startDrawLoop() {
this.timer = setInterval(()=>this.draw(), 1000 / this.framerate);
}
draw() {
this.ctx.fillStyle = this.bg;
this.ctx.fillRect(0, 0, this.width, this.height);
for (const [i, l] of (this.layers || []).entries()){
l(this.ctx, i);
}
this.drawUI();
}
createLayer(layer) {
this.layers.push(layer);
}
deleteLayer(layer) {
this.layers = this.layers.filter((l)=>l !== layer);
}
moveLayer(layer, index) {
let temp = this.layers.filter((l)=>l !== layer);
temp = [
...temp.slice(0, index),
layer,
...temp.slice(index)
];
this.layers = temp;
}
line(start, end, style) {
this.setStyle(style);
this.ctx.beginPath();
this.ctx.moveTo(start.x, start.y);
this.ctx.lineTo(end.x, end.y);
this.ctx.stroke();
}
dot(at, style) {
this.setStyle({
...style,
weight: 1
});
this.ctx.beginPath();
this.ctx.arc(at.x, at.y, style?.weight || 1, 0, Constants1.TWO_PI);
this.ctx.fill();
}
drawCircle(at, radius, style) {
this.setStyle(style);
this.ctx.beginPath();
this.ctx.arc(at.x, at.y, radius, 0, Constants1.TWO_PI);
this.ctx.stroke();
}
fillCircle(at, radius, style) {
this.setStyle(style);
this.ctx.beginPath();
this.ctx.arc(at.x, at.y, radius, 0, Constants1.TWO_PI);
this.ctx.fill();
}
drawRect(at, width, height, style) {
this.setStyle(style);
this.ctx.strokeRect(at.x, at.y, width, height);
}
fillRect(at, width, height, style) {
this.setStyle(style);
this.ctx.fillRect(at.x, at.y, width, height);
}
drawSquare(at, size, style) {
this.drawRect(at, size, size, style);
}
fillSquare(at, size, style) {
this.fillRect(at, size, size, style);
}
drawCenteredRect(at, width, height, style) {
this.ctx.save();
this.ctx.translate(-width / 2, -height / 2);
this.drawRect(at, width, height, style);
this.ctx.restore();
}
fillCenteredRect(at, width, height, style) {
this.ctx.save();
this.ctx.translate(-width / 2, -height / 2);
this.fillRect(at, width, height, style);
this.ctx.restore();
}
drawCenteredSquare(at, size, style) {
this.drawCenteredRect(at, size, size, style);
}
fillCenteredSquare(at, size, style) {
this.fillCenteredRect(at, size, size, style);
}
drawBezier(a, b, c, d, style) {
this.setStyle(style);
this.ctx.beginPath();
this.ctx.moveTo(a.x, a.y);
this.ctx.bezierCurveTo(b.x, b.y, c.x, c.y, d.x, d.y);
this.ctx.stroke();
}
drawRotated(origin, angle, cb) {
this.ctx.save();
this.ctx.translate(origin.x, origin.y);
this.ctx.rotate(angle);
this.ctx.translate(-origin.x, -origin.y);
cb();
this.ctx.restore();
}
setStyle(style) {
const ctx = this.ctx;
ctx.fillStyle = style?.color || style?.fillColor || 'black';
ctx.strokeStyle = style?.color || style?.strokeColor || 'black';
ctx.lineWidth = style?.weight || 1;
}
mouseX = 0;
mouseY = 0;
registerDraggable(point, radius, style) {
if (this.draggables.find((d)=>d.point === point)) return;
const id = this.addUIElement('circle', point, radius, {
fillColor: '#5533ff50',
strokeColor: '#5533ff50'
});
this.draggables.push({
point,
radius,
style,
id
});
}
unregisterDraggable(point) {
for (const d of this.draggables){
if (d.point === point) {
this.removeUIElement(d.id);
}
}
this.draggables = this.draggables.filter((d)=>d.point !== point);
}
onClick(e) {
for (const d of this.draggables){
if (d.point.dist(new Vector(this.mouseX, this.mouseY)) <= d.radius) {
d.beingDragged = true;
} else d.beingDragged = false;
}
}
offClick(e) {
for (const d of this.draggables){
d.beingDragged = false;
}
}
uiElements = new Map();
uiDrawing = {
rectangle: (...args)=>{
!args[3].noFill && this.fillRect(args[0], args[1], args[2], args[3]);
!args[3].noStroke && this.drawRect(args[0], args[1], args[2], args[3]);
},
square: (...args)=>{
!args[2].noFill && this.fillSquare(args[0], args[1], args[2]);
!args[2].noStroke && this.drawSquare(args[0], args[1], args[2]);
},
circle: (...args)=>{
!args[2].noFill && this.fillCircle(args[0], args[1], args[2]);
!args[2].noStroke && this.drawCircle(args[0], args[1], args[2]);
}
};
drawUI() {
for (const [shape, ...args] of this.uiElements.values()){
this.uiDrawing[shape].apply(null, args);
}
}
addUIElement(shape, ...args) {
const id = crypto.randomUUID();
for (const arg of args){
delete arg.color;
}
this.uiElements.set(id, [
shape,
...args
]);
return id;
}
removeUIElement(id) {
this.uiElements.delete(id);
}
}
class ComplexPath { class ComplexPath {
points = []; points = [];
radius = 50; radius = 50;
@ -495,19 +266,23 @@ class ComplexPath {
class PathSegment { class PathSegment {
points; points;
ctx; ctx;
length;
constructor(points){ constructor(points){
this.points = points; this.points = points;
this.length = this.calculateApproxLength(100);
} }
setContext(ctx) { setContext(ctx) {
this.ctx = ctx; this.ctx = ctx;
} }
draw() { draw() {
const [a, b, c, d] = this.points; if (!this.ctx) return;
doodler.drawBezier(a, b, c, d, { const ctx = this.ctx;
strokeColor: '#ffffff50' ctx.save();
}); ctx.beginPath();
ctx.moveTo(this.points[0].x, this.points[0].y);
ctx.bezierCurveTo(this.points[1].x, this.points[1].y, this.points[2].x, this.points[2].y, this.points[3].x, this.points[3].y);
ctx.strokeStyle = '#ffffff50';
ctx.lineWidth = 2;
ctx.stroke();
ctx.restore();
} }
getPointAtT(t) { getPointAtT(t) {
const [a, b, c, d] = this.points; const [a, b, c, d] = this.points;
@ -588,46 +363,6 @@ class PathSegment {
if (distance < r) return t; if (distance < r) return t;
return false; return false;
} }
calculateApproxLength(resolution = 25) {
const stepSize = 1 / resolution;
const points = [];
for(let i = 0; i <= resolution; i++){
const current = stepSize * i;
points.push(this.getPointAtT(current));
}
return points.reduce((acc, cur)=>{
const prev = acc.prev;
acc.prev = cur;
if (!prev) return acc;
acc.length += cur.dist(prev);
return acc;
}, {
prev: undefined,
length: 0
}).length;
}
calculateEvenlySpacedPoints(spacing, resolution = 1) {
const points = [];
points.push(this.points[0]);
let prev = points[0];
let distSinceLastEvenPoint = 0;
let t = 0;
const div = Math.ceil(this.length * resolution * 10);
while(t < 1){
t += 1 / div;
const point = this.getPointAtT(t);
distSinceLastEvenPoint += prev.dist(point);
if (distSinceLastEvenPoint >= spacing) {
const overshoot = distSinceLastEvenPoint - spacing;
const evenPoint = Vector.add(point, Vector.sub(point, prev).normalize().mult(overshoot));
distSinceLastEvenPoint = overshoot;
points.push(evenPoint);
prev = evenPoint;
}
prev = point;
}
return points;
}
} }
class Mover { class Mover {
position; position;
@ -688,11 +423,6 @@ class Mover {
if (this.position.y < 0) this.position.y = this.ctx.canvas.height; if (this.position.y < 0) this.position.y = this.ctx.canvas.height;
} }
draw() { draw() {
doodler.drawRotated(this.position, this.velocity.heading() || 0, ()=>{
doodler.fillCenteredRect(this.position, this.boundingBox.size.x, this.boundingBox.size.y, {
fillColor: 'white'
});
});
if (!this.ctx) return; if (!this.ctx) return;
this.ctx.fillStyle = 'white'; this.ctx.fillStyle = 'white';
this.ctx.save(); this.ctx.save();
@ -871,7 +601,6 @@ class TrainCar extends Train {
super.move(); super.move();
} else { } else {
this.draw(); this.draw();
this.follower?.draw();
} }
} }
} }
@ -921,12 +650,15 @@ class Track extends PathSegment {
]; ];
} }
getNearestPoint(p) { getNearestPoint(p) {
let [closest, closestDistance] = this.getClosestPoint(p); let [closest, closestDistance, closestT] = this.getClosestPoint(p);
let mostValid = this;
if (this.next !== this) { if (this.next !== this) {
const [point, distance, t] = this.next.getClosestPoint(p); const [point, distance, t] = this.next.getClosestPoint(p);
if (distance < closestDistance) { if (distance < closestDistance) {
closest = point; closest = point;
closestDistance = distance; closestDistance = distance;
mostValid = this.next;
t;
} }
} }
if (this.prev !== this) { if (this.prev !== this) {
@ -934,6 +666,8 @@ class Track extends PathSegment {
if (distance1 < closestDistance) { if (distance1 < closestDistance) {
closest = point1; closest = point1;
closestDistance = distance1; closestDistance = distance1;
mostValid = this.next;
t1;
} }
} }
return closest; return closest;
@ -944,18 +678,17 @@ class Track extends PathSegment {
} }
draw() { draw() {
super.draw(); super.draw();
if (this.editable) for (const e of this.points){ if (this.ctx && this.editable) for (const e of this.points){
e.drawDot(); this.ctx.fillStyle = 'blue';
e.drawDot(this.ctx);
} }
} }
} }
class Spline { class Spline {
segments = []; segments = [];
ctx; ctx;
evenPoints;
constructor(segs){ constructor(segs){
this.segments = segs; this.segments = segs;
this.evenPoints = this.calculateEvenlySpacedPoints(3);
} }
setContext(ctx) { setContext(ctx) {
this.ctx = ctx; this.ctx = ctx;
@ -968,19 +701,6 @@ class Spline {
segment.draw(); segment.draw();
} }
} }
calculateEvenlySpacedPoints(spacing, resolution = 1) {
return this.segments.flatMap((s)=>s.calculateEvenlySpacedPoints(spacing, resolution));
}
followEvenPoints(t) {
const i = Math.floor(t);
const a = this.evenPoints[i];
const b = this.evenPoints[(i + 1) % this.evenPoints.length];
try {
return Vector.lerp(a, b, t % 1);
} catch {
console.log(t, i, a, b);
}
}
} }
const generateSquareTrack = ()=>{ const generateSquareTrack = ()=>{
const first = new Track([ const first = new Track([
@ -1056,40 +776,71 @@ const generateSquareTrack = ()=>{
eighth eighth
]); ]);
}; };
init({ const drawLine = (ctx, x1, y1, x2, y2)=>{
width: 400, ctx.beginPath();
height: 400, ctx.moveTo(x1, y1);
bg: '#333' ctx.lineTo(x2, y2);
}); ctx.stroke();
};
const hello = ()=>{
console.log('HELLO WORLD');
};
hello();
const canvas = document.createElement('canvas');
canvas.height = 400;
canvas.width = 400;
document.body.append(canvas);
const ctx = canvas.getContext('2d');
const clear = ()=>{
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, canvas.width, canvas.height);
};
setInterval(()=>{
draw();
}, 1000 / 60);
const path = generateSquareTrack(); const path = generateSquareTrack();
path.setContext(ctx);
let t = 0; let t = 0;
let currentSeg = 0;
const trains = Array(1).fill(null).map((_, i)=>new Train(path.segments[i % path.segments.length], 5)); const trains = Array(1).fill(null).map((_, i)=>new Train(path.segments[i % path.segments.length], 5));
doodler.createLayer(()=>{ for (const train of trains){
train.setContext(ctx);
}
function draw() {
clear();
path.draw(); path.draw();
for (const p of path.evenPoints){
p.drawDot();
}
const point = path.followEvenPoints(t);
point && doodler.drawCircle(point, 5, {
strokeColor: 'green'
});
t = (t + 1 / 3) % path.evenPoints.length;
});
document.addEventListener('keyup', (e)=>{
if (e.key === 'd') {}
if (e.key === 'ArrowUp') {}
if (e.key === 'ArrowDown') {
for (const train of trains){ for (const train of trains){
train.speed -= .1; train.move();
}
ctx.strokeStyle = 'red';
ctx.lineWidth = 4;
const seg = path.segments[currentSeg];
const start = seg.getPointAtT(t);
const tan = seg.tangent(t).normalize().mult(25);
drawLine(ctx, start.x, start.y, start.x + tan.x, start.y + tan.y);
t += .01;
if (t > 1) {
t -= 1;
currentSeg = (currentSeg + 1) % path.segments.length;
}
}
document.addEventListener('keyup', (e)=>{
if (e.key === 'd') {
console.log(trains);
}
if (e.key === 'ArrowUp') {
for (const train of trains){
train.speed += .1;
}
}
if (e.key === 'ArrowDown') {
for (const train1 of trains){
train1.speed -= .1;
} }
} }
if (e.key === 'e') { if (e.key === 'e') {
for (const t of path.segments){ for (const t of path.segments){
t.editable = !t.editable; t.editable = !t.editable;
for (const p of t.points){
if (t.editable) doodler.registerDraggable(p, 10);
else doodler.unregisterDraggable(p);
}
} }
} }
}); });

View File

@ -12,6 +12,6 @@
}, },
"imports": { "imports": {
"drawing": "./drawing/index.ts", "drawing": "./drawing/index.ts",
"doodler": "https://git.cyborggrizzly.com/emma/doodler/raw/tag/0.0.3a/mod.ts" "doodler": "https://git.cyborggrizzly.com/emma/doodler/raw/branch/main/mod.ts"
} }
} }

View File

@ -1,5 +1,5 @@
import { Constants } from "../math/constants.ts"; import { Constants } from "../math/constants.ts";
import { Vector } from "doodler"; import { Vector } from "../math/vector.ts";
const circle = (ctx: CanvasRenderingContext2D, center: Vector, radius: number) => { const circle = (ctx: CanvasRenderingContext2D, center: Vector, radius: number) => {
ctx.beginPath(); ctx.beginPath();

138
main.ts
View File

@ -1,26 +1,48 @@
import { lerp } from "./math/lerp.ts"; import { lerp } from "./math/lerp.ts";
import { ComplexPath, PathSegment } from "./math/path.ts"; import { ComplexPath, PathSegment } from "./math/path.ts";
import { Vector } from "./math/vector.ts";
import { Mover } from "./physics/mover.ts"; import { Mover } from "./physics/mover.ts";
import { Train } from "./train.ts"; import { Train } from "./train.ts";
import { fillCircle, drawCircle } from 'drawing'; import { fillCircle, drawCircle } from 'drawing';
import { generateSquareTrack } from "./track.ts"; import { generateSquareTrack } from "./track.ts";
import { drawLine } from "./drawing/line.ts"; import { drawLine } from "./drawing/line.ts";
import { initializeDoodler, Vector } from 'doodler'; import { hello } from 'doodler';
hello();
const canvas = document.createElement('canvas');
canvas.height = 400;
canvas.width = 400;
document.body.append(canvas);
const ctx = canvas.getContext('2d')!;
// for (const mover of trains) { // for (const mover of trains) {
// mover.setContext(ctx); // mover.setContext(ctx);
// mover.velocity.add(Vector.random2D()) // mover.velocity.add(Vector.random2D())
// } // }
initializeDoodler({ const clear = () => {
width: 400, ctx.fillStyle = 'black';
height: 400, ctx.fillRect(0, 0, canvas.width, canvas.height)
bg: '#333' }
});
const fps = 60;
setInterval(() => {
// for (const train of trains) {
// train.move();
// }
draw();
}, 1000 / fps);
// const path = new PathSegment([new Vector(20, 20), new Vector(200, 100), new Vector(200, 300), new Vector(20, 380)]);
const path = generateSquareTrack(); const path = generateSquareTrack();
path.setContext(ctx);
// const train = new Train(path.segments[0], 4);
// train.setContext(ctx);
// train.velocity.x = -1;
// train.velocity.y = 1;
const controls = { const controls = {
ArrowUp: false, ArrowUp: false,
@ -31,51 +53,97 @@ const controls = {
let t = 0; let t = 0;
let currentSeg = 0; let currentSeg = 0;
const speed = 1;
const trainCount = 1; const trainCount = 1;
const trains = Array(trainCount).fill(null).map((_, i) => new Train(path.segments[i % path.segments.length], 5)); const trains = Array(trainCount).fill(null).map((_, i) => new Train(path.segments[i % path.segments.length], 5));
for (const train of trains) {
train.setContext(ctx);
// train.maxSpeed = Math.random() * 5 + 1
}
doodler.createLayer(() => { function draw() {
clear();
path.draw(); path.draw();
// for (const train of trains) { // for (const control in controls) {
// train.move(); // if (controls.hasOwnProperty(control)) {
// const isActive = controls[control as keyof typeof controls];
// if (isActive) {
// const force = getSteeringForce(train, control);
// train.applyForce(force);
// }
// } // }
// ctx.strokeStyle = 'red'; // if (Object.values(controls).every(c => !c)) {
// ctx.lineWidth = 4; // train.acceleration.set(0, 0)
// const seg = path.segments[currentSeg]; // }
// const start = seg.getPointAtT(t); // }
// const tan = seg.tangent(t).normalize().mult(25);
// const tan = seg.tangent(t);
for (const p of path.evenPoints) { // train.follow(path)
p.drawDot(); for (const train of trains) {
train.move();
} }
// doodler.line(start, new Vector(start.x + tan.x, start.y + tan.y), {color: 'blue'}); // ctx.strokeStyle = 'orange';
// doodler.fillCircle(start, 5, {fillColor: 'blue'})
const point = path.followEvenPoints(t); ctx.strokeStyle = 'red';
point && ctx.lineWidth = 4;
doodler.drawCircle(point, 5, {strokeColor: 'green'}) const seg = path.segments[currentSeg];
const start = seg.getPointAtT(t);
const tan = seg.tangent(t).normalize().mult(25);
drawLine(ctx, start.x, start.y, start.x + tan.x, start.y + tan.y);
t = (t + (1 / 3)) % path.evenPoints.length; t += .01;
if (t > 1) {
t -= 1;
currentSeg = (currentSeg + 1) % path.segments.length;
}
}
// path.segments.forEach(s => s.calculateApproxLength(10000)) // let wKeydown =false
})
// document.addEventListener('keydown', e => {
// if (e.key === 'w' && !wKeydown) {
// wKeydown = true;
// for (const train of trains) {
// train.acceleration.add(.1, 0);
// }
// }
// });
// document.addEventListener('keyup', e => {
// if (e.key === 'w') {
// wKeydown = false;
// for (const train of trains) {
// train.acceleration.sub(.1, 0);
// }
// }
// });
// let sKeydown = false;
// document.addEventListener('keydown', e => {
// if (e.key === 's' && !sKeydown) {
// sKeydown = true;
// for (const train of trains) {
// train.acceleration.sub(.1, 0);
// }
// }
// });
// document.addEventListener('keyup', e => {
// if (e.key === 's') {
// sKeydown = false;
// for (const train of trains) {
// train.acceleration.add(.1, 0);
// }
// }
// });
document.addEventListener('keyup', e => { document.addEventListener('keyup', e => {
if (e.key === 'd') { if (e.key === 'd') {
// console.log(trains) console.log(trains)
// console.log(path.segments.reduce((a,b) => a + b.calculateApproxLength(1000), 0))
// console.log(path.evenPoints);
} }
if (e.key === 'ArrowUp') { if (e.key === 'ArrowUp') {
// for (const train of trains) { for (const train of trains) {
// train.speed += .1; train.speed += .1;
// } }
} }
if (e.key === 'ArrowDown') { if (e.key === 'ArrowDown') {
for (const train of trains) { for (const train of trains) {
@ -86,12 +154,6 @@ document.addEventListener('keyup', e => {
if (e.key === 'e') { if (e.key === 'e') {
for (const t of path.segments) { for (const t of path.segments) {
t.editable = !t.editable; t.editable = !t.editable;
for (const p of t.points) {
if (t.editable)
doodler.registerDraggable(p, 10)
else
doodler.unregisterDraggable(p)
}
} }
} }
}) })

View File

@ -1,4 +1,4 @@
import { Vector } from "doodler"; import { Vector } from "./vector.ts";
export const lerp = (a: number, b: number, t: number) => { export const lerp = (a: number, b: number, t: number) => {
return (a*t) + (b*(1-t)); return (a*t) + (b*(1-t));

View File

@ -1,4 +1,4 @@
import { Vector } from "doodler"; import { Vector } from "./vector.ts";
export class ComplexPath { export class ComplexPath {
@ -42,11 +42,8 @@ export class PathSegment {
points: [Vector, Vector, Vector, Vector] points: [Vector, Vector, Vector, Vector]
ctx?: CanvasRenderingContext2D; ctx?: CanvasRenderingContext2D;
length: number;
constructor(points: [Vector, Vector, Vector, Vector]) { constructor(points: [Vector, Vector, Vector, Vector]) {
this.points = points; this.points = points;
this.length = this.calculateApproxLength(100);
} }
setContext(ctx: CanvasRenderingContext2D) { setContext(ctx: CanvasRenderingContext2D) {
@ -54,30 +51,26 @@ export class PathSegment {
} }
draw() { draw() {
const [a, b, c, d] = this.points; if (!this.ctx) return;
doodler.drawBezier(a, b, c, d, { const ctx = this.ctx;
strokeColor: '#ffffff50'
})
// if (!this.ctx) return;
// const ctx = this.ctx;
// ctx.save(); ctx.save();
// ctx.beginPath(); ctx.beginPath();
// ctx.moveTo(this.points[0].x, this.points[0].y); ctx.moveTo(this.points[0].x, this.points[0].y);
// ctx.bezierCurveTo( ctx.bezierCurveTo(
// this.points[1].x, this.points[1].x,
// this.points[1].y, this.points[1].y,
// this.points[2].x, this.points[2].x,
// this.points[2].y, this.points[2].y,
// this.points[3].x, this.points[3].x,
// this.points[3].y, this.points[3].y,
// ); );
// ctx.strokeStyle = '#ffffff50'; ctx.strokeStyle = '#ffffff50';
// ctx.lineWidth = 2; ctx.lineWidth = 2;
// ctx.stroke(); ctx.stroke();
// ctx.restore(); ctx.restore();
} }
getPointAtT(t: number) { getPointAtT(t: number) {
@ -120,7 +113,7 @@ export class PathSegment {
const point = this.getPointAtT(i * resolution); const point = this.getPointAtT(i * resolution);
const distance = v.dist(point); const distance = v.dist(point);
if (distance < r) { if (distance < r) {
points.push([i * resolution, this]); points.push([i * resolution,this]);
} }
} }
return points return points
@ -176,50 +169,4 @@ export class PathSegment {
return false; return false;
} }
calculateApproxLength(resolution = 25) {
const stepSize = 1 / resolution;
const points: Vector[] = []
for (let i = 0; i <= resolution; i++) {
const current = stepSize * i;
points.push(this.getPointAtT(current))
}
return points.reduce((acc: { prev?: Vector, length: number }, cur) => {
const prev = acc.prev;
acc.prev = cur;
if (!prev) return acc;
acc.length += cur.dist(prev);
return acc;
}, { prev: undefined, length: 0 }).length
}
calculateEvenlySpacedPoints(spacing: number, resolution = 1) {
const points: Vector[] = []
points.push(this.points[0]);
let prev = points[0];
let distSinceLastEvenPoint = 0
let t = 0;
const div = Math.ceil(this.length * resolution * 10);
while (t < 1) {
t += 1 / div;
const point = this.getPointAtT(t);
distSinceLastEvenPoint += prev.dist(point);
if (distSinceLastEvenPoint >= spacing) {
const overshoot = distSinceLastEvenPoint - spacing;
const evenPoint = Vector.add(point, Vector.sub(point, prev).normalize().mult(overshoot))
distSinceLastEvenPoint = overshoot;
points.push(evenPoint);
prev = evenPoint;
}
prev = point;
}
return points;
}
} }

273
math/vector.ts Normal file
View File

@ -0,0 +1,273 @@
import { Constants } from "./constants.ts";
export class Vector {
x: number;
y: number;
z: number;
constructor(x = 0, y = 0, z = 0) {
this.x = x;
this.y = y;
this.z = z;
}
set(x: number, y: number, z?: number): void;
set(v: Vector): void;
set(v: [number, number, number]): void;
set(v: Vector | [number, number, number] | number, y?: number, z?: number) {
if (arguments.length === 1 && typeof v !== "number") {
this.set((v as Vector).x || (v as Array<number>)[0] || 0,
(v as Vector).y || (v as Array<number>)[1] || 0,
(v as Vector).z || (v as Array<number>)[2] || 0);
} else {
this.x = v as number;
this.y = y || 0;
this.z = z || 0;
}
}
get() {
return new Vector(this.x, this.y, this.z);
}
mag() {
const x = this.x,
y = this.y,
z = this.z;
return Math.sqrt(x * x + y * y + z * z);
}
magSq() {
const x = this.x,
y = this.y,
z = this.z;
return (x * x + y * y + z * z);
}
setMag(len: number): void;
setMag(v: Vector, len: number): Vector
setMag(v_or_len: Vector | number, len?: number) {
if (len === undefined) {
len = v_or_len as number;
this.normalize();
this.mult(len);
} else {
const v = v_or_len as Vector;
v.normalize();
v.mult(len);
return v;
}
}
add(x: number, y: number, z: number): void;
add(x: number, y: number): void;
add(v: Vector): void;
add(v: Vector | number, y?: number, z?: number) {
if (arguments.length === 1 && typeof v !== 'number') {
this.x += v.x;
this.y += v.y;
this.z += v.z;
} else if (arguments.length === 2) {
// 2D Vector
this.x += v as number;
this.y += y ?? 0;
} else {
this.x += v as number;
this.y += y ?? 0;
this.z += z ?? 0;
}
}
sub(x: number, y: number, z: number): void;
sub(x: number, y: number): void;
sub(v: Vector): void;
sub(v: Vector | number, y?: number, z?: number) {
if (arguments.length === 1 && typeof v !== 'number') {
this.x -= v.x;
this.y -= v.y;
this.z -= v.z;
} else if (arguments.length === 2) {
// 2D Vector
this.x -= v as number;
this.y -= y ?? 0;
} else {
this.x -= v as number;
this.y -= y ?? 0;
this.z -= z ?? 0;
}
}
mult(v: number | Vector) {
if (typeof v === 'number') {
this.x *= v;
this.y *= v;
this.z *= v;
} else {
this.x *= v.x;
this.y *= v.y;
this.z *= v.z;
}
return this;
}
div(v: number | Vector) {
if (typeof v === 'number') {
this.x /= v;
this.y /= v;
this.z /= v;
} else {
this.x /= v.x;
this.y /= v.y;
this.z /= v.z;
}
}
rotate(angle: number) {
const prev_x = this.x;
const c = Math.cos(angle);
const s = Math.sin(angle);
this.x = c * this.x - s * this.y;
this.y = s * prev_x + c * this.y;
}
dist(v: Vector) {
const dx = this.x - v.x,
dy = this.y - v.y,
dz = this.z - v.z;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
dot(x: number, y: number, z: number): number;
dot(v: Vector): number;
dot(v: Vector | number, y?: number, z?: number) {
if (arguments.length === 1 && typeof v !== 'number') {
return (this.x * v.x + this.y * v.y + this.z * v.z);
}
return (this.x * (v as number) + this.y * y! + this.z * z!);
}
cross(v: Vector) {
const x = this.x,
y = this.y,
z = this.z;
return new Vector(y * v.z - v.y * z,
z * v.x - v.z * x,
x * v.y - v.x * y);
}
lerp(x: number, y: number, z: number): void;
lerp(v: Vector, amt: number): void;
lerp(v_or_x: Vector | number, amt_or_y: number, z?: number, amt?: number) {
const lerp_val = (start: number, stop: number, amt: number) => {
return start + (stop - start) * amt;
};
let x, y: number;
if (arguments.length === 2 && typeof v_or_x !== 'number') {
// given vector and amt
amt = amt_or_y;
x = v_or_x.x;
y = v_or_x.y;
z = v_or_x.z;
} else {
// given x, y, z and amt
x = v_or_x as number;
y = amt_or_y;
}
this.x = lerp_val(this.x, x, amt!);
this.y = lerp_val(this.y, y, amt!);
this.z = lerp_val(this.z, z!, amt!);
}
normalize() {
const m = this.mag();
if (m > 0) {
this.div(m);
}
return this;
}
limit(high: number) {
if (this.mag() > high) {
this.normalize();
this.mult(high);
}
}
heading() {
return (-Math.atan2(-this.y, this.x));
}
heading2D() {
return this.heading();
}
toString() {
return "[" + this.x + ", " + this.y + ", " + this.z + "]";
}
array() {
return [this.x, this.y, this.z];
}
copy() {
return new Vector(this.x, this.y, this.z);
}
drawDot(ctx: CanvasRenderingContext2D) {
// ctx.fillStyle = 'red'
ctx.beginPath();
ctx.arc(this.x, this.y, 2, 0, Constants.TWO_PI);
ctx.fill();
}
static fromAngle(angle: number, v?: Vector) {
if (v === undefined || v === null) {
v = new Vector();
}
v.x = Math.cos(angle);
v.y = Math.sin(angle);
return v;
}
static random2D(v?: Vector) {
return Vector.fromAngle(Math.random() * (Math.PI * 2), v);
}
static random3D(v: Vector) {
const angle = Math.random() * Constants.TWO_PI;
const vz = Math.random() * 2 - 1;
const mult = Math.sqrt(1 - vz * vz);
const vx = mult * Math.cos(angle);
const vy = mult * Math.sin(angle);
if (v === undefined || v === null) {
v = new Vector(vx, vy, vz);
} else {
v.set(vx, vy, vz);
}
return v;
}
static dist(v1: Vector, v2: Vector) {
return v1.dist(v2);
}
static dot(v1: Vector, v2: Vector) {
return v1.dot(v2);
}
static cross(v1: Vector, v2: Vector) {
return v1.cross(v2);
}
static add(v1: Vector, v2: Vector) {
return new Vector(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z);
}
static sub(v1: Vector, v2: Vector) {
return new Vector(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z);
}
static angleBetween(v1: Vector, v2: Vector) {
return Math.acos(v1.dot(v2) / Math.sqrt(v1.magSq() * v2.magSq()));
}
static lerp(v1: Vector, v2: Vector, amt: number) {
// non-static lerp mutates object, but this version returns a new vector
const retval = new Vector(v1.x, v1.y, v1.z);
retval.lerp(v2, amt);
return retval;
}
static vectorProjection(v1: Vector, v2: Vector) {
v2 = v2.copy();
v2.normalize();
const sp = v1.dot(v2);
v2.mult(sp);
return v2;
}
static hypot2(a: Vector, b: Vector) {
return Vector.dot(Vector.sub(a,b), Vector.sub(a,b))
}
}

View File

@ -1,7 +1,7 @@
import { Constants } from "../math/constants.ts"; import { Constants } from "../math/constants.ts";
import { map } from "../math/lerp.ts"; import { map } from "../math/lerp.ts";
import { ComplexPath, PathSegment } from "../math/path.ts"; import { ComplexPath, PathSegment } from "../math/path.ts";
import { Vector } from "doodler"; import { Vector } from "../math/vector.ts";
import { Mover } from "./mover.ts"; import { Mover } from "./mover.ts";
export class export class

View File

@ -1,4 +1,4 @@
import { Vector } from "doodler"; import { Vector } from "../math/vector.ts";
export class Mover { export class Mover {
position: Vector; position: Vector;
@ -81,9 +81,6 @@ export class Mover {
} }
draw() { draw() {
doodler.drawRotated(this.position, this.velocity.heading() || 0, () => {
doodler.fillCenteredRect(this.position, this.boundingBox.size.x, this.boundingBox.size.y, {fillColor: 'white'})
});
if (!this.ctx) return; if (!this.ctx) return;
this.ctx.fillStyle = 'white' this.ctx.fillStyle = 'white'

View File

@ -1,5 +1,5 @@
import { PathSegment } from "./math/path.ts"; import { PathSegment } from "./math/path.ts";
import { Vector } from "doodler"; import { Vector } from "./math/vector.ts";
import { Train } from "./train.ts"; import { Train } from "./train.ts";
export class Track extends PathSegment { export class Track extends PathSegment {
@ -57,13 +57,17 @@ export class Track extends PathSegment {
} }
getNearestPoint(p: Vector) { getNearestPoint(p: Vector) {
let [closest, closestDistance] = this.getClosestPoint(p); let [closest, closestDistance, closestT] = this.getClosestPoint(p);
// deno-lint-ignore no-this-alias
let mostValid: Track = this;
if (this.next !== this) { if (this.next !== this) {
const [point, distance, t] = this.next.getClosestPoint(p); const [point, distance, t] = this.next.getClosestPoint(p);
if (distance < closestDistance) { if (distance < closestDistance) {
closest = point; closest = point;
closestDistance = distance; closestDistance = distance;
mostValid = this.next;
closestT = t;
} }
} }
if (this.prev !== this) { if (this.prev !== this) {
@ -71,6 +75,8 @@ export class Track extends PathSegment {
if (distance < closestDistance) { if (distance < closestDistance) {
closest = point; closest = point;
closestDistance = distance; closestDistance = distance;
mostValid = this.next;
closestT = t;
} }
} }
@ -85,9 +91,10 @@ export class Track extends PathSegment {
draw(): void { draw(): void {
super.draw(); super.draw();
if (this.editable) if (this.ctx && this.editable)
for (const e of this.points) { for (const e of this.points) {
e.drawDot(); this.ctx.fillStyle = 'blue';
e.drawDot(this.ctx);
} }
} }
} }
@ -95,11 +102,8 @@ export class Track extends PathSegment {
export class Spline<T extends PathSegment = PathSegment> { export class Spline<T extends PathSegment = PathSegment> {
segments: T[] = []; segments: T[] = [];
ctx?: CanvasRenderingContext2D; ctx?: CanvasRenderingContext2D;
evenPoints: Vector[];
constructor(segs: T[]) { constructor(segs: T[]) {
this.segments = segs; this.segments = segs;
this.evenPoints = this.calculateEvenlySpacedPoints(3);
} }
setContext(ctx: CanvasRenderingContext2D) { setContext(ctx: CanvasRenderingContext2D) {
@ -114,52 +118,6 @@ export class Spline<T extends PathSegment = PathSegment> {
segment.draw(); segment.draw();
} }
} }
calculateEvenlySpacedPoints(spacing: number, resolution = 1) {
return this.segments.flatMap(s => s.calculateEvenlySpacedPoints(spacing, resolution));
// const points: Vector[] = []
// points.push(this.segments[0].points[0]);
// let prev = points[0];
// let distSinceLastEvenPoint = 0
// for (const seg of this.segments) {
// let t = 0;
// const div = Math.ceil(seg.length * resolution * 10);
// while (t < 1) {
// t += 1 / div;
// const point = seg.getPointAtT(t);
// distSinceLastEvenPoint += prev.dist(point);
// if (distSinceLastEvenPoint >= spacing) {
// const overshoot = distSinceLastEvenPoint - spacing;
// const evenPoint = Vector.add(point, Vector.sub(point, prev).normalize().mult(overshoot))
// distSinceLastEvenPoint = overshoot;
// points.push(evenPoint);
// prev = evenPoint;
// }
// prev = point
// }
// }
// return points;
}
followEvenPoints(t: number) {
const i = Math.floor(t);
const a = this.evenPoints[i]
const b = this.evenPoints[(i + 1) % this.evenPoints.length]
try {
return Vector.lerp(a, b, t % 1);
} catch {
console.log(t, i, a, b);
}
}
} }
export const generateSquareTrack = () => { export const generateSquareTrack = () => {

View File

@ -1,6 +1,6 @@
import { drawLine } from "./drawing/line.ts"; import { drawLine } from "./drawing/line.ts";
import { ComplexPath, PathSegment } from "./math/path.ts"; import { ComplexPath, PathSegment } from "./math/path.ts";
import { Vector } from "doodler"; import { Vector } from "./math/vector.ts";
import { Follower } from "./physics/follower.ts"; import { Follower } from "./physics/follower.ts";
import { Mover } from "./physics/mover.ts"; import { Mover } from "./physics/mover.ts";
import { Track } from "./track.ts"; import { Track } from "./track.ts";
@ -178,7 +178,6 @@ class TrainCar extends Train {
super.move(); super.move();
} else { } else {
this.draw() this.draw()
this.follower?.draw();
} }
} }
// this.draw() // this.draw()