gravity/tool/objects.js
2026-01-05 01:30:32 -06:00

87 lines
2.3 KiB
JavaScript

import {hide, show} from '../helper.js';
import {Tool} from '../tool.js';
export class ObjectsTool extends Tool {
objects = [];
setContainer(container) {
super.setContainer(container);
// Display a list of the currently selected objects,
// or all objects if none are currently selected.
if (this.sim.select.selectedGroup.length) {
this.objects = this.sim.select.selectedGroup;
} else {
this.objects = this.sim.system.filter(obj => obj.alive);
}
this.populate();
this.sim.select.onSelect(({selectedGroup}) => {
this.objects = selectedGroup;
this.depopulate();
this.populate();
});
this.sim.system.onCreate(obj => {
if (!this.sim.select.selectedGroup.length) {
this.objects.push(obj);
this.populate();
}
});
this.sim.system.onMerge(({merged}) => {
if (!merged.objectsToolEl) return;
hide({
items: this.objects,
item: merged,
parentEl: this.div,
itemEl: merged.objectsToolEl,
});
});
}
frame() {
this.populate();
}
depopulate() {
while (this.div.firstChild) {
this.div.removeChild(this.div.firstChild);
}
}
populate() {
for (const obj of this.objects) {
const objectEl = obj.objectsToolEl ?? document.createElement('div');
obj.objectsToolEl = objectEl;
const {r, g, b} = obj.color;
// Distance from center of screen
// const distance = magnitude(sub(obj.position, add(this.sim.display.viewOrigin, {
// x: this.sim.display.width / 2,
// y: this.sim.display.height / 2,
// })));
objectEl.innerHTML =
`<span style="background-color: rgb(${r},${g},${b});">&nbsp;&nbsp;</span>` +
`E<sub>k</sub>: ${obj.kineticEnergy.toExponential(1)}` +
`<br>&nbsp;&nbsp;W<sub>p</sub>: ${obj.workDoneByPointer.toExponential(1)}` +
`<br>&nbsp;&nbsp;W<sub>f</sub>: ${obj.workDoneByForces.toExponential(1)}`;
// `${obj.mass.toPrecision(3)} ` +
// `${distance.toPrecision(3)}`;
// `${magnitude(obj.velocity).toExponential(0)} ` +
// `${-degrees(direction(obj.velocity)).toFixed(0)}°`;
if (!obj.hidden) {
show({
items: this.objects,
item: obj,
parentEl: this.div,
itemEl: objectEl,
});
}
}
}
}