Skip to content

Commit

Permalink
Demo: Standardize boost, whitespace fixes, lint
Browse files Browse the repository at this point in the history
  • Loading branch information
PhoenixIllusion committed May 25, 2024
1 parent 1567d6e commit 6f0a042
Show file tree
Hide file tree
Showing 11 changed files with 69 additions and 68 deletions.
8 changes: 4 additions & 4 deletions basic-examples/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,15 @@ export class App {

async init() {
const curURL = new URL(window.location.href);
if(!this.memoryAvailableEle && curURL.searchParams.get('mem')) {
if (!this.memoryAvailableEle && curURL.searchParams.get('mem')) {
await loadJolt({});
this.memoryAvailableEle = setupMemoryAvailable(Jolt);
}
// initialize babylon scene and engine
const engine = this.engine = new Engine(this.canvas, true);
const scene = this.scene = new Scene(engine);
this.ui = AdvancedDynamicTexture.CreateFullscreenUI('gui');

scene.enablePhysics(new Vector3(0, -9.8, 0), await JoltJSPlugin.loadPlugin())

if (!(this.config && this.config.getCamera)) {
Expand All @@ -94,13 +94,13 @@ export class App {
light.intensity = 0.7;

const maybeCallback = this.createScene(scene);
const callback = maybeCallback instanceof Promise ? await maybeCallback: maybeCallback;
const callback = maybeCallback instanceof Promise ? await maybeCallback : maybeCallback;

let last = performance.now();
// run the main render loop
engine.runRenderLoop(() => {
const scene = this.scene;
if(scene) {
if (scene) {
if (callback) {
const now = performance.now();
callback(now, now - last);
Expand Down
12 changes: 6 additions & 6 deletions basic-examples/src/scene/vehicle_motorcycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,6 @@ export default async (scene: Scene): Promise<SceneCallback> => {
const material = new StandardMaterial('tile');
material.diffuseTexture = tiledTexture;

await loadTrack(scene);

const physicSetting: PhysicsImpostorParameters = { mass: 300, restitution: 0, friction: 0, centerOffMass: new Vector3(0, -.3, 0), disableBidirectionalTransformation: true };
const car = createBox(new Vector3(0, 2, 0), Quaternion.FromEulerAngles(0, Math.PI, 0), new Vector3(0.1, .3, 0.4), physicSetting, '#FF0000');
car.box.material!.wireframe = true;
Expand All @@ -38,6 +36,8 @@ export default async (scene: Scene): Promise<SceneCallback> => {
const vehicleInput = new DefaultMotorcycleInput(car.physics.physicsBody);
const controller = new MotorcycleController(car.physics, wheeledConfig, vehicleInput);


await loadTrack(scene);
const carWheels: Mesh[] = []
wheeledConfig.wheels.forEach((o, i) => {
const mesh = MeshBuilder.CreateCylinder('cylinder', { diameter: o.radius * 2, height: o.width, tessellation: 16 });
Expand All @@ -53,17 +53,17 @@ export default async (scene: Scene): Promise<SceneCallback> => {
setupTachometer(controller, scene);
camera.getRoot().parent = followPoint;

let stdTorque = controller.engine.maxTorque;
let stdInertia = controller.engine.inertia;

const rotateVector = new Vector3();
return (_time: number, _delta: number) => {
vehicleInput.input.forward = input.direction.z;
vehicleInput.input.right = input.direction.x;
vehicleInput.input.handBrake = input.handbrake;

const newTorque = input.boost ? 1.1*stdTorque : stdTorque;
if(controller.engine.maxTorque != newTorque) {
controller.engine.maxTorque = newTorque;
const newInertia = input.boost ? 0.25 * stdInertia : stdInertia;
if (controller.engine.inertia != newInertia) {
controller.engine.inertia = newInertia;
}

followPoint.position.copyFrom(car.box.position);
Expand Down
10 changes: 5 additions & 5 deletions basic-examples/src/scene/vehicle_tracked.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MeshBuilder, SceneCallback, createBox, createFloor } from '../util/example';
import { MeshBuilder, SceneCallback, createBox } from '../util/example';
import { DefaultTrackedInput, TrackededVehicleController, Vehicle, createBasicTracked } from '@phoenixillusion/babylonjs-jolt-plugin/vehicle';
import { SceneConfig } from '../app';
import { Camera } from '@babylonjs/core/Cameras/camera';
Expand Down Expand Up @@ -52,17 +52,17 @@ export default async (scene: Scene): Promise<SceneCallback> => {
setupTachometer(controller, scene);
camera.getRoot().parent = followPoint;

let stdTorque = controller.engine.maxTorque;
let stdInertia = controller.engine.inertia;

const rotateVector = new Vector3();
return (_time: number, _delta: number) => {
vehicleInput.input.forward = input.direction.z;
vehicleInput.input.right = input.direction.x;
vehicleInput.input.handBrake = input.handbrake;

const newTorque = input.boost ? 1.1*stdTorque : stdTorque;
if(controller.engine.maxTorque != newTorque) {
controller.engine.maxTorque = newTorque;
const newInertia = input.boost ? 0.25 * stdInertia : stdInertia;
if (controller.engine.inertia != newInertia) {
controller.engine.inertia = newInertia;
}

followPoint.position.copyFrom(car.box.position);
Expand Down
4 changes: 2 additions & 2 deletions basic-examples/src/scene/vehicle_wheeled.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MeshBuilder, SceneCallback, createBox, createFloor } from '../util/example';
import { MeshBuilder, SceneCallback, createBox } from '../util/example';
import { DefaultWheeledVehicleInput, WheeledVehicleController, Vehicle, createBasicCar } from '@phoenixillusion/babylonjs-jolt-plugin/vehicle';
import { SceneConfig } from '../app';
import { FollowCamera } from '@babylonjs/core/Cameras/followCamera';
Expand Down Expand Up @@ -66,7 +66,7 @@ export default async (scene: Scene): Promise<SceneCallback> => {
vehicleInput.input.handBrake = input.handbrake;

const newInertia = input.boost ? 0.25 * stdInertia : stdInertia;
if(controller.engine.inertia != newInertia) {
if (controller.engine.inertia != newInertia) {
controller.engine.inertia = newInertia;
}

Expand Down
5 changes: 3 additions & 2 deletions basic-examples/src/util/camera.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Matrix, Vector3 } from "@babylonjs/core/Maths/math.vector";
import { TransformNode } from "@babylonjs/core/Meshes/transformNode";
import { CameraCombinedInput } from "./controller";
import { Scene } from "@babylonjs/core/scene";
import { BaseKeyCodes } from "./controller/keyboard";

export class CameraSetup {

Expand Down Expand Up @@ -33,7 +34,7 @@ export class CameraSetup {
this.camera = new FreeCamera("cam", new Vector3(0, 0, -50), scene);
this.camera.fov = 0.47350045992678597;
this.camera.parent = yTilt;
}
}

public setDistance(dist: number) {
this.camera.position.z = this._targetDistance = -dist;
Expand Down Expand Up @@ -64,7 +65,7 @@ export class CameraSetup {
return this.camera.getViewMatrix();
}

public setController(input: CameraCombinedInput<FreeCamera>) {
public setController<T extends BaseKeyCodes>(input: CameraCombinedInput<FreeCamera, T>) {
this.camera.inputs.clear();
this.camera.attachControl();
this.camera.inputs.add(input);
Expand Down
14 changes: 7 additions & 7 deletions basic-examples/src/util/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { BaseCameraPointersInput } from "@babylonjs/core/Cameras/Inputs/BaseCame
import { Camera } from "@babylonjs/core/Cameras/camera";
import { App } from "../app";

type OnInputCheck<T,K extends BaseKeyCodes> = (camera: T, joystickState: Vector2, keyboardState: KeyCodeState<K>) => void;
type OnInputCheck<T, K extends BaseKeyCodes> = (camera: T, joystickState: Vector2, keyboardState: KeyCodeState<K>) => void;

export class CameraCombinedInput<T extends Camera, K extends BaseKeyCodes> extends BaseCameraPointersInput {
SWIPE_SENSIBILITY = 1.5;
Expand All @@ -28,7 +28,7 @@ export class CameraCombinedInput<T extends Camera, K extends BaseKeyCodes> exten

getSimpleName = () => "joystick"

constructor(private _onInputCheck: OnInputCheck<T,K>, private cameraSetup: CameraSetup, keycodes: K) {
constructor(private _onInputCheck: OnInputCheck<T, K>, private cameraSetup: CameraSetup, keycodes: K) {
super();
this.joystick = new JoystickControl(App.instance.ui!);
this.keyboard = new KeyboardControl(keycodes);
Expand Down Expand Up @@ -61,11 +61,11 @@ export class CameraCombinedInput<T extends Camera, K extends BaseKeyCodes> exten
}

checkInputs() {
let engine = EngineStore.LastCreatedEngine!;
if (this.keyboard.state.ROTATE_LEFT) this.cameraSetup.rotate(-this.SWIPE_SENSIBILITY * engine.getDeltaTime() / 500);
if (this.keyboard.state.ROTATE_RIGHT) this.cameraSetup.rotate(this.SWIPE_SENSIBILITY * engine.getDeltaTime() / 500);
if (this.keyboard.state.ROTATE_UP) this.cameraSetup.changeTiltY(-this.SWIPE_SENSIBILITY * engine.getDeltaTime() / 500);
if (this.keyboard.state.ROTATE_DOWN) this.cameraSetup.changeTiltY(this.SWIPE_SENSIBILITY * engine.getDeltaTime() / 500);
let engine = EngineStore.LastCreatedEngine!;
if (this.keyboard.state.ROTATE_LEFT) this.cameraSetup.rotate(-this.SWIPE_SENSIBILITY * engine.getDeltaTime() / 500);
if (this.keyboard.state.ROTATE_RIGHT) this.cameraSetup.rotate(this.SWIPE_SENSIBILITY * engine.getDeltaTime() / 500);
if (this.keyboard.state.ROTATE_UP) this.cameraSetup.changeTiltY(-this.SWIPE_SENSIBILITY * engine.getDeltaTime() / 500);
if (this.keyboard.state.ROTATE_DOWN) this.cameraSetup.changeTiltY(this.SWIPE_SENSIBILITY * engine.getDeltaTime() / 500);
this._onInputCheck(this.camera, this.joystick.joystickDelta, this.keyboard.state)
}

Expand Down
8 changes: 4 additions & 4 deletions basic-examples/src/util/controller/keyboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ export class BaseKeyCodes {
ROTATE_DOWN: KeyboardEventTypes[] = ['KeyC'];
}

export type KeyCodeState<T extends BaseKeyCodes> = {[key in keyof T]: boolean};
export type KeyCodeState<T extends BaseKeyCodes> = { [key in keyof T]: boolean };

export class KeyState<T extends BaseKeyCodes> {
state: KeyCodeState<T>;
constructor(keycodes: T) {
const state: {[k: string]: boolean} = {};
const state: { [k: string]: boolean } = {};
Object.keys(keycodes).forEach(key => {
state[key] = false;
});
Expand Down Expand Up @@ -59,8 +59,8 @@ export class KeyboardControl<T extends BaseKeyCodes> {
if (!evt.metaKey) {
if (info.type === KeyboardEventTypes.KEYDOWN || info.type === KeyboardEventTypes.KEYUP) {
const set_state = info.type === KeyboardEventTypes.KEYDOWN ? true : false;
Object.entries(this.keys).forEach(([k,v])=> {
if(v.indexOf(key)>=0) {
Object.entries(this.keys).forEach(([k, v]) => {
if (v.indexOf(key) >= 0) {
this.state[k as keyof T] = set_state;
}
})
Expand Down
2 changes: 1 addition & 1 deletion basic-examples/src/util/custom-ele-util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ export interface IDynamicProp {
update(): void;
}
export class DynamicProp<T extends HTMLElement> implements IDynamicProp {
constructor(public ele: T, private onUpdate: (ele: T)=> void) {}
constructor(public ele: T, private onUpdate: (ele: T) => void) { }
update() {
this.onUpdate(this.ele);
}
Expand Down
4 changes: 2 additions & 2 deletions basic-examples/src/util/memory-available.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ export class MemoryAvailableElement extends HTMLElement {
time = NOW;
const freeMem = this.jolt.JoltInterface.prototype.sGetFreeMemory();
const totalMem = this.jolt.JoltInterface.prototype.sGetTotalMemory();
const percentUsed = (100 * (totalMem-freeMem - this.base) / totalMem).toFixed(2) + '%';
const percentUsed = (100 * (totalMem - freeMem - this.base) / totalMem).toFixed(2) + '%';
barInner.style.width = percentUsed;
barInner.innerText = percentUsed;
memoryText.innerText = `${totalMem-freeMem - this.base} (+ ${this.base}) / ${totalMem}`;
memoryText.innerText = `${totalMem - freeMem - this.base} (+ ${this.base}) / ${totalMem}`;
}
}));
const dispose = document.createElement('button');
Expand Down
52 changes: 26 additions & 26 deletions basic-examples/src/util/tachometer.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { IBaseVehicleController } from "@phoenixillusion/babylonjs-jolt-plugin/vehicle";
import { DynamicProp, IDynamicProp } from "./custom-ele-util";

function deg(d: number) { return d/360 * 2 * Math.PI }
function deg(d: number) { return d / 360 * 2 * Math.PI }
export class TachometerElement extends HTMLElement {
public controller?: IBaseVehicleController

Expand All @@ -17,8 +17,8 @@ export class TachometerElement extends HTMLElement {

const shadow = this.attachShadow({ mode: "open" });
const style = document.createElement('style');
style.innerHTML =
`:host {
style.innerHTML =
`:host {
position: relative;
padding: 10px 0;
width: 200px;
Expand Down Expand Up @@ -72,7 +72,7 @@ export class TachometerElement extends HTMLElement {
:host .gears .active ,:host .modes .active {
color: red;
}
`;
`;
shadow.appendChild(style);
const tachometerBase = document.createElement('div');
tachometerBase.className = "base";
Expand All @@ -99,18 +99,18 @@ export class TachometerElement extends HTMLElement {
maxRPMDrawn = 10;

private getRadialPoint(angle: number, dist: number) {
const x = 100 + Math.cos(deg(angle))*dist;
const y = 100 + Math.sin(deg(angle))*dist;
return [x,y];
const x = 100 + Math.cos(deg(angle)) * dist;
const y = 100 + Math.sin(deg(angle)) * dist;
return [x, y];
}

private calculateRPMAngle(rpm: number): number {
const maxRPMDrawn = this.maxRPMDrawn
const startAngle = this.startAngle;
const endAngle = this.endAngle;

const percent = rpm/maxRPMDrawn;
return startAngle + (endAngle-startAngle) * percent;
const percent = rpm / maxRPMDrawn;
return startAngle + (endAngle - startAngle) * percent;
}

private renderBackground() {
Expand All @@ -125,9 +125,9 @@ export class TachometerElement extends HTMLElement {
ctx.arc(100, 100, 90, deg(startAngle), deg(endAngle));
ctx.stroke();

const maxRPMDrawn = this.maxRPMDrawn = Math.ceil(controller.engine.maxRPM/1000) * 1000;
const numHatch = maxRPMDrawn/1000 * 2;
const hatchAngle = (endAngle-startAngle)/numHatch;
const maxRPMDrawn = this.maxRPMDrawn = Math.ceil(controller.engine.maxRPM / 1000) * 1000;
const numHatch = maxRPMDrawn / 1000 * 2;
const hatchAngle = (endAngle - startAngle) / numHatch;

//redline
const redlineStart = this.calculateRPMAngle(controller.transmission.shiftUpRPM);
Expand All @@ -141,20 +141,20 @@ export class TachometerElement extends HTMLElement {
ctx.strokeStyle = 'white';
ctx.textBaseline = "middle";
ctx.font = "14px Arial"
for(let i=0; i <=numHatch; i++) {
for (let i = 0; i <= numHatch; i++) {
const angle = startAngle + hatchAngle * i;
let hatchStart = 80;
let lineWidth = 2;
if(i % 2 == 0) {
if (i % 2 == 0) {
hatchStart = 72;
lineWidth = 3;
const [xT,yT] = this.getRadialPoint(angle, 60);
const [xT, yT] = this.getRadialPoint(angle, 60);
ctx.lineWidth = 1.5;
const text = ""+i/2;
ctx.strokeText(text, xT - ctx.measureText(text).width/2, yT);
const text = "" + i / 2;
ctx.strokeText(text, xT - ctx.measureText(text).width / 2, yT);
}
const [xS,yS] = this.getRadialPoint(angle, hatchStart)
const [xE,yE] = this.getRadialPoint(angle, 90+lineWidth/2)
const [xS, yS] = this.getRadialPoint(angle, hatchStart)
const [xE, yE] = this.getRadialPoint(angle, 90 + lineWidth / 2)

ctx.lineWidth = lineWidth;
ctx.beginPath();
Expand All @@ -179,10 +179,10 @@ export class TachometerElement extends HTMLElement {
const speedMPH = document.createElement('div');
speedMPH.className = 'value'
speed.appendChild(speedMPH);
this.dynamicItems.push(new DynamicProp(speedMPH,
this.dynamicItems.push(new DynamicProp(speedMPH,
(x) => {
x.innerText = `${this.toMPH(this.controller!.getLinearVelocity().length())}`
}))
}))
const label = document.createElement('div');
label.innerText = 'mph'
label.className = 'label'
Expand Down Expand Up @@ -210,9 +210,9 @@ export class TachometerElement extends HTMLElement {
const gears = document.createElement('div');
gears.className = 'gears';

const gearNames = ['R','N'];
const gearNames = ['R', 'N'];
this.controller!.transmission.gearRatios.forEach((_o, i) => {
gearNames.push(''+(1+i));
gearNames.push('' + (1 + i));
});
const allGears: HTMLDivElement[] = [];
gearNames.forEach(name => {
Expand All @@ -225,7 +225,7 @@ export class TachometerElement extends HTMLElement {
this.dynamicItems.push(new DynamicProp(gears, () => {
const currentGear = this.controller!.transmission.gear;
allGears.forEach((gear, i) => {
gear.classList.toggle('active', (i-1) === currentGear);
gear.classList.toggle('active', (i - 1) === currentGear);
})
}));
return gears;
Expand All @@ -237,8 +237,8 @@ export class TachometerElement extends HTMLElement {

ctx.beginPath();
const angle = this.calculateRPMAngle(this.controller!.engine.rpm);
const [xS,yS] = this.getRadialPoint(angle, 6)
const [xE,yE] = this.getRadialPoint(angle, 50)
const [xS, yS] = this.getRadialPoint(angle, 6)
const [xE, yE] = this.getRadialPoint(angle, 50)

ctx.strokeStyle = 'red';
ctx.lineWidth = 3;
Expand Down
Loading

0 comments on commit 6f0a042

Please sign in to comment.