Compare commits
3 Commits
Author | SHA1 | Date | |
---|---|---|---|
ac63fd8349 | |||
de55283839 | |||
9d503d53cc |
24
Dockerfile
24
Dockerfile
@ -1,24 +0,0 @@
|
|||||||
FROM node:23-alpine as skycraft-deps
|
|
||||||
|
|
||||||
WORKDIR /workspace/skycraft
|
|
||||||
ADD ./skycraft/package.json ./
|
|
||||||
ADD ./skycraft/yarn.lock ./
|
|
||||||
RUN yarn install
|
|
||||||
|
|
||||||
|
|
||||||
FROM skycraft-deps as skycraft-build
|
|
||||||
|
|
||||||
ADD . /workspace
|
|
||||||
RUN yarn build
|
|
||||||
|
|
||||||
|
|
||||||
FROM skycraft-deps as skycraft-dev
|
|
||||||
|
|
||||||
ENTRYPOINT ["yarn"]
|
|
||||||
CMD ["run", "serve"]
|
|
||||||
|
|
||||||
|
|
||||||
FROM scratch as skycraft-export
|
|
||||||
|
|
||||||
COPY --from=skycraft-build /workspace/skycraft/app.js /
|
|
||||||
COPY --from=skycraft-build /workspace/skycraft/static/* /
|
|
31
Makefile
31
Makefile
@ -1,31 +0,0 @@
|
|||||||
export DOCKER_BUILDKIT=1
|
|
||||||
|
|
||||||
skycraft-dev-image := skycraft-dev
|
|
||||||
|
|
||||||
.PHONY: skycraft
|
|
||||||
skycraft: ## build skycraft
|
|
||||||
docker build \
|
|
||||||
--output=out/skycraft \
|
|
||||||
--target=skycraft-export \
|
|
||||||
.
|
|
||||||
|
|
||||||
.PHONY: skycraft-dev-image
|
|
||||||
skycraft-dev-image:
|
|
||||||
docker build \
|
|
||||||
-t $(skycraft-dev-image) \
|
|
||||||
--target=skycraft-dev \
|
|
||||||
.
|
|
||||||
|
|
||||||
.PHONY: skycraft-dev
|
|
||||||
skycraft-dev: skycraft-dev-image
|
|
||||||
docker run -it --rm \
|
|
||||||
-v .:/workspace \
|
|
||||||
-v /workspace/skycraft/node_modules \
|
|
||||||
-p 8000:8000 \
|
|
||||||
$(skycraft-dev-image)
|
|
||||||
|
|
||||||
.PHONY: help
|
|
||||||
help: ## Show this help
|
|
||||||
@echo Noteworthy targets:
|
|
||||||
@egrep '^[a-zA-Z_-]+:.*?## .*$$' $(firstword $(MAKEFILE_LIST)) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}'
|
|
||||||
.DEFAULT_GOAL := help
|
|
@ -1,8 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "wmc-common",
|
|
||||||
"version": "1.0.0",
|
|
||||||
"license": "MIT",
|
|
||||||
"dependencies": {
|
|
||||||
"esbuild": "^0.14.2"
|
|
||||||
}
|
|
||||||
}
|
|
@ -86,42 +86,6 @@ export function orientationOnly(m) {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function fromBases(x, y, z) {
|
|
||||||
return [
|
|
||||||
x[0], x[1], x[2], 0,
|
|
||||||
y[0], y[1], y[2], 0,
|
|
||||||
z[0], z[1], z[2], 0,
|
|
||||||
0, 0, 0, 1,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function positionOnly(m) {
|
|
||||||
return [
|
|
||||||
1, 0, 0, 0,
|
|
||||||
0, 1, 0, 0,
|
|
||||||
0, 0, 1, 0,
|
|
||||||
m[12], m[13], m[14], m[15],
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
export function setOrientation(m, o) {
|
|
||||||
return [
|
|
||||||
o[0], o[1], o[2], m[3],
|
|
||||||
o[4], o[5], o[6], m[7],
|
|
||||||
o[8], o[9], o[10], m[11],
|
|
||||||
m[12], m[13], m[14], m[15],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function setPosition(m, x) {
|
|
||||||
return [
|
|
||||||
m[0], m[1], m[2], m[3],
|
|
||||||
m[4], m[5], m[6], m[7],
|
|
||||||
m[8], m[9], m[10], m[11],
|
|
||||||
x[0], x[1], x[2], 1,
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function inverse(m) {
|
export function inverse(m) {
|
||||||
const t = apply(m, [0, 0, 0, 1]);
|
const t = apply(m, [0, 0, 0, 1]);
|
||||||
const r = orientationOnly(m);
|
const r = orientationOnly(m);
|
@ -1,10 +1,10 @@
|
|||||||
import { makeFace } from 'wmc-common/geometry';
|
import { makeFace } from '../geometry';
|
||||||
import * as linalg from './linalg';
|
import * as linalg from './linalg';
|
||||||
import {memoize} from 'wmc-common/memoize';
|
import {memoize} from '../memoize';
|
||||||
|
|
||||||
type direction = ('-x' | '+x' | '-y' | '+y' | '-z' | '+z');
|
type direction = ('-x' | '+x' | '-y' | '+y' | '-z' | '+z');
|
||||||
|
|
||||||
export const BlockType = {
|
const BlockType = {
|
||||||
UNDEFINED: 0,
|
UNDEFINED: 0,
|
||||||
AIR: 1,
|
AIR: 1,
|
||||||
DIRT: 2,
|
DIRT: 2,
|
||||||
@ -18,6 +18,7 @@ export const BlockType = {
|
|||||||
|
|
||||||
const CHUNKSIZE = 32;
|
const CHUNKSIZE = 32;
|
||||||
|
|
||||||
|
|
||||||
/** seed: some kind of number uniquely defining the body
|
/** seed: some kind of number uniquely defining the body
|
||||||
* x, y, z: space coordinates in the body's frame
|
* x, y, z: space coordinates in the body's frame
|
||||||
*
|
*
|
||||||
@ -134,9 +135,11 @@ function faceTexture(type: number, dir: direction) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function* makeChunkFaces(chunk) {
|
function* makeChunkFaces(chunk, getChunk) {
|
||||||
const cs = CHUNKSIZE;
|
const cs = CHUNKSIZE;
|
||||||
|
|
||||||
|
console.log(`make chunk faces for ${chunk.seed} at ${chunk.position}`);
|
||||||
|
|
||||||
function faceCenter(pos: linalg.Vec3, dir: direction) {
|
function faceCenter(pos: linalg.Vec3, dir: direction) {
|
||||||
switch (dir) {
|
switch (dir) {
|
||||||
case '-x': return [pos[0] - 0.5, pos[1], pos[2]];
|
case '-x': return [pos[0] - 0.5, pos[1], pos[2]];
|
||||||
@ -303,115 +306,19 @@ function getBodyChunks(seed: number) {
|
|||||||
return chunks;
|
return chunks;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** fake chunk map re-using the memoize */
|
export function getBodyGeometry(chunks) {
|
||||||
class ChunkMap {
|
function lookup(seed: number, chunkX: number, chunkY: number, chunkZ: number) {
|
||||||
constructor(seed) {
|
for (const chunk of chunks) {
|
||||||
this.seed = seed;
|
const [cx, cy, cz] = chunk.layout;
|
||||||
|
if (chunkX == cx && chunkY == cy && chunkZ == cz) {
|
||||||
|
return chunk;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
get(i, j, k) {
|
const faces = chunks
|
||||||
return getChunk(this.seed, i, j, k);
|
|
||||||
}
|
|
||||||
|
|
||||||
has(i, j, k) {
|
|
||||||
return getChunk(this.seed, i, j, k) !== undefined;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getBodyGeometry(seed: number) {
|
|
||||||
const faces = getBodyChunks(seed)
|
|
||||||
.filter(chunk => !chunk.underground)
|
.filter(chunk => !chunk.underground)
|
||||||
.map(chunk => [...makeChunkFaces(chunk)]);
|
.map(chunk => [...makeChunkFaces(chunk, memoize(lookup))]);
|
||||||
|
|
||||||
return {
|
return faces.reduce((a, b) => a.concat(b));
|
||||||
faces: faces.reduce((a, b) => a.concat(b)),
|
}
|
||||||
chunkMap: new ChunkMap(seed),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export function blockLookup(chunkMap, x, y, z) {
|
|
||||||
const chunki = Math.floor((x + CHUNKSIZE / 2) / CHUNKSIZE);
|
|
||||||
const chunkj = Math.floor((y + CHUNKSIZE / 2) / CHUNKSIZE);
|
|
||||||
const chunkk = Math.floor((z + CHUNKSIZE / 2) / CHUNKSIZE);
|
|
||||||
|
|
||||||
const chunk = chunkMap.get(chunki, chunkj, chunkk);
|
|
||||||
if (chunk === undefined) {
|
|
||||||
return {
|
|
||||||
type: BlockType.UNDEFINED,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const i = Math.floor(x - chunk.position[0] + 0.5);
|
|
||||||
const j = Math.floor(y - chunk.position[1] + 0.5);
|
|
||||||
const k = Math.floor(z - chunk.position[2] + 0.5);
|
|
||||||
|
|
||||||
const blockIndex = CHUNKSIZE * (CHUNKSIZE * i + j) + k;
|
|
||||||
|
|
||||||
return {
|
|
||||||
type: chunk.blocks[blockIndex],
|
|
||||||
centerPosition: [
|
|
||||||
chunk.position[0] + i,
|
|
||||||
chunk.position[1] + j,
|
|
||||||
chunk.position[2] + k,
|
|
||||||
],
|
|
||||||
chunk,
|
|
||||||
blockIndex,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function movePoint(p, s, u) {
|
|
||||||
return linalg.add(p, linalg.scale(u, s));
|
|
||||||
}
|
|
||||||
|
|
||||||
function minIndex(arr) {
|
|
||||||
return arr.reduce((min, val, i) => val >= arr[min] ? min : i, -1);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Imported from wmc, looks like it calculates the distance to the next grid block */
|
|
||||||
function rayThroughGrid(origin, direction, maxDistance) {
|
|
||||||
const range = i => [...Array(i).keys()];
|
|
||||||
|
|
||||||
const nextGrid = range(3).map(i => direction[i] > 0 ?
|
|
||||||
Math.floor(origin[i] + 0.5) + 0.5 :
|
|
||||||
Math.floor(origin[i] + 0.5) - 0.5);
|
|
||||||
const distanceToGrid = range(3).map(i => (nextGrid[i] - origin[i]) / direction[i])
|
|
||||||
.map(v => v === 0.0 ? Number.POSITIVE_INFINITY : v);
|
|
||||||
const axis = minIndex(distanceToGrid);
|
|
||||||
const rayLength = distanceToGrid[axis];
|
|
||||||
|
|
||||||
if (rayLength > maxDistance) {
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
const position = movePoint(origin, distanceToGrid[axis], direction);
|
|
||||||
const normal = range(3).map(i => i === axis ? -Math.sign(direction[i]) : 0);
|
|
||||||
|
|
||||||
return {position, normal, distance: rayLength};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** needs a blockLookup function, finds the first non-air block along a ray */
|
|
||||||
export function castRay(chunkMap, origin, direction, maxDistance=CHUNKSIZE) {
|
|
||||||
let currentPoint = origin;
|
|
||||||
|
|
||||||
while (maxDistance > 0) {
|
|
||||||
const {position, normal, distance} = rayThroughGrid(currentPoint, direction, maxDistance);
|
|
||||||
|
|
||||||
if (position === undefined) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
maxDistance -= distance;
|
|
||||||
currentPoint = movePoint(position, 0.01, direction);
|
|
||||||
const blockCenter = movePoint(position, -0.5, normal);
|
|
||||||
const block = blockLookup(chunkMap, ...blockCenter);
|
|
||||||
|
|
||||||
if (block.type === BlockType.AIR) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
block,
|
|
||||||
normal,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
15
skycraft/client.ts
Normal file
15
skycraft/client.ts
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
const backend = 'http://localhost:8080/api/';
|
||||||
|
|
||||||
|
/** Get all chunks for the given body */
|
||||||
|
export async function getBody(seed: number) {
|
||||||
|
const resp = await fetch(backend + `body/${seed}`);
|
||||||
|
|
||||||
|
return await resp.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Get a complete solar system */
|
||||||
|
export async function getSystem(seed: number) {
|
||||||
|
const resp = await fetch(backend + `system/${seed}`);
|
||||||
|
|
||||||
|
return await resp.json();
|
||||||
|
}
|
@ -1,7 +1,7 @@
|
|||||||
import {makeBufferFromFaces } from 'wmc-common/geometry';
|
import {makeBufferFromFaces } from '../geometry';
|
||||||
import { loadTexture, makeProgram } from 'wmc-common/gl';
|
import { loadTexture, makeProgram } from '../gl';
|
||||||
import * as linalg from './linalg';
|
import * as linalg from './linalg';
|
||||||
import * as se3 from 'wmc-common/se3';
|
import * as se3 from '../se3';
|
||||||
import { makeOrbitObject } from './orbit';
|
import { makeOrbitObject } from './orbit';
|
||||||
|
|
||||||
const VSHADER = `
|
const VSHADER = `
|
||||||
@ -15,14 +15,12 @@ uniform mat4 uView;
|
|||||||
uniform vec3 uLightDirection;
|
uniform vec3 uLightDirection;
|
||||||
uniform float uAmbiantLight;
|
uniform float uAmbiantLight;
|
||||||
uniform vec3 uGlowColor;
|
uniform vec3 uGlowColor;
|
||||||
uniform vec3 uSpecularColor;
|
|
||||||
|
|
||||||
varying highp vec2 vTextureCoord;
|
varying highp vec2 vTextureCoord;
|
||||||
varying lowp vec3 vLighting;
|
varying lowp vec3 vLighting;
|
||||||
varying lowp vec3 vRay;
|
varying lowp vec3 vRay;
|
||||||
varying lowp vec3 vLightDir;
|
varying lowp vec3 vLightDir;
|
||||||
varying lowp vec3 vNormal;
|
varying lowp vec3 vNormal;
|
||||||
varying lowp vec3 vSpecularColor;
|
|
||||||
|
|
||||||
highp mat3 transpose(in highp mat3 inmat) {
|
highp mat3 transpose(in highp mat3 inmat) {
|
||||||
highp vec3 x = inmat[0];
|
highp vec3 x = inmat[0];
|
||||||
@ -52,7 +50,6 @@ void main() {
|
|||||||
vRay = -normalize((uModel * vec4(aPosition, 1.0)).xyz - camPos);
|
vRay = -normalize((uModel * vec4(aPosition, 1.0)).xyz - camPos);
|
||||||
vLightDir = -uLightDirection;
|
vLightDir = -uLightDirection;
|
||||||
vNormal = normal;
|
vNormal = normal;
|
||||||
vSpecularColor = uSpecularColor;
|
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
@ -64,7 +61,6 @@ varying lowp vec3 vLighting;
|
|||||||
varying lowp vec3 vRay;
|
varying lowp vec3 vRay;
|
||||||
varying lowp vec3 vLightDir;
|
varying lowp vec3 vLightDir;
|
||||||
varying lowp vec3 vNormal;
|
varying lowp vec3 vNormal;
|
||||||
varying lowp vec3 vSpecularColor;
|
|
||||||
|
|
||||||
void main() {
|
void main() {
|
||||||
highp vec4 color = texture2D(uSampler, vTextureCoord);
|
highp vec4 color = texture2D(uSampler, vTextureCoord);
|
||||||
@ -73,7 +69,7 @@ void main() {
|
|||||||
}
|
}
|
||||||
lowp vec3 specularDir = 2.0 * dot(vLightDir, vNormal) * vNormal - vLightDir;
|
lowp vec3 specularDir = 2.0 * dot(vLightDir, vNormal) * vNormal - vLightDir;
|
||||||
lowp float specularAmount = smoothstep(0.92, 1.0, dot(vRay, specularDir));
|
lowp float specularAmount = smoothstep(0.92, 1.0, dot(vRay, specularDir));
|
||||||
lowp vec3 specular = specularAmount * vSpecularColor;
|
lowp vec3 specular = 0.8 * specularAmount * vec3(1.0, 1.0, 0.8);
|
||||||
gl_FragColor = vec4(vLighting * color.rgb + specular, color.a);
|
gl_FragColor = vec4(vLighting * color.rgb + specular, color.a);
|
||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
@ -90,7 +86,6 @@ export async function initWorldGl(gl: WebGLRenderingContext) {
|
|||||||
const lightDirectionLoc = gl.getUniformLocation(program, 'uLightDirection');
|
const lightDirectionLoc = gl.getUniformLocation(program, 'uLightDirection');
|
||||||
const ambiantLoc = gl.getUniformLocation(program, 'uAmbiantLight');
|
const ambiantLoc = gl.getUniformLocation(program, 'uAmbiantLight');
|
||||||
const glowColorLoc = gl.getUniformLocation(program, 'uGlowColor');
|
const glowColorLoc = gl.getUniformLocation(program, 'uGlowColor');
|
||||||
const specularColorLoc = gl.getUniformLocation(program, 'uSpecularColor');
|
|
||||||
|
|
||||||
const positionLoc = gl.getAttribLocation(program, 'aPosition');
|
const positionLoc = gl.getAttribLocation(program, 'aPosition');
|
||||||
const normalLoc = gl.getAttribLocation(program, 'aNormal');
|
const normalLoc = gl.getAttribLocation(program, 'aNormal');
|
||||||
@ -122,18 +117,18 @@ export async function initWorldGl(gl: WebGLRenderingContext) {
|
|||||||
|
|
||||||
const drawObject = (objectParams) => {
|
const drawObject = (objectParams) => {
|
||||||
const {
|
const {
|
||||||
tf,
|
position,
|
||||||
|
orientation,
|
||||||
glBuffer,
|
glBuffer,
|
||||||
numVertices,
|
numVertices,
|
||||||
lightDirection,
|
lightDirection,
|
||||||
glowColor,
|
glowColor,
|
||||||
specularColor,
|
|
||||||
} = objectParams;
|
} = objectParams;
|
||||||
|
|
||||||
gl.uniformMatrix4fv(modelLoc, false, new Float32Array(tf));
|
gl.uniformMatrix4fv(modelLoc, false, new Float32Array(se3.product(
|
||||||
|
se3.translation(...position), orientation)));
|
||||||
gl.uniform3fv(lightDirectionLoc, lightDirection);
|
gl.uniform3fv(lightDirectionLoc, lightDirection);
|
||||||
gl.uniform3fv(glowColorLoc, glowColor);
|
gl.uniform3fv(glowColorLoc, glowColor);
|
||||||
gl.uniform3fv(specularColorLoc, specularColor);
|
|
||||||
|
|
||||||
gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer);
|
gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer);
|
||||||
|
|
||||||
@ -177,9 +172,9 @@ void main() {
|
|||||||
|
|
||||||
lowp float f = sqrt(x * x + y * y);
|
lowp float f = sqrt(x * x + y * y);
|
||||||
|
|
||||||
if (f > 1.00) {
|
if (f > 1.01) {
|
||||||
discard;
|
discard;
|
||||||
} else if (f < 0.98) {
|
} else if (f < 0.99) {
|
||||||
discard;
|
discard;
|
||||||
}
|
}
|
||||||
gl_FragColor = vec4(1, .5, 0, 0.5);
|
gl_FragColor = vec4(1, .5, 0, 0.5);
|
||||||
@ -217,12 +212,14 @@ export function getOrbitDrawContext(gl: WebGLRenderingContext) {
|
|||||||
|
|
||||||
const drawObject = (objectParams) => {
|
const drawObject = (objectParams) => {
|
||||||
const {
|
const {
|
||||||
tf,
|
position,
|
||||||
|
orientation,
|
||||||
value,
|
value,
|
||||||
glBuffer,
|
glBuffer,
|
||||||
} = objectParams;
|
} = objectParams;
|
||||||
|
|
||||||
gl.uniformMatrix4fv(modelLoc, false, new Float32Array(tf));
|
gl.uniformMatrix4fv(modelLoc, false, new Float32Array(se3.product(
|
||||||
|
se3.translation(...position), orientation)));
|
||||||
|
|
||||||
gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer);
|
gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer);
|
||||||
|
|
||||||
@ -240,42 +237,37 @@ export function getOrbitDrawContext(gl: WebGLRenderingContext) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function getShipTf(context) {
|
|
||||||
if (context.landed) {
|
|
||||||
const body = context.landedBody;
|
|
||||||
const bodyTf = se3.product(se3.translation(...body.position), body.orientation);
|
|
||||||
return se3.product(bodyTf, context.shipTf);
|
|
||||||
}
|
|
||||||
|
|
||||||
return context.player.tf;
|
|
||||||
}
|
|
||||||
|
|
||||||
function getObjects(context, body, parentPosition = undefined) {
|
function getObjects(context, body, parentPosition = undefined) {
|
||||||
const objects = [];
|
const objects = [];
|
||||||
const {gl, glContext, player} = context;
|
const {gl, glContext, player} = context;
|
||||||
const {position, orientation, glowColor, specularColor} = body;
|
const {position, orientation, glowColor} = body;
|
||||||
|
|
||||||
if (body.glBuffer === undefined) {
|
if (body.glBuffer === undefined) {
|
||||||
body.glBuffer = makeBufferFromFaces(gl, body.geometry.faces);
|
body.glBuffer = makeBufferFromFaces(gl, body.geometry);
|
||||||
}
|
}
|
||||||
|
|
||||||
objects.push({
|
objects.push({
|
||||||
geometry: body.glBuffer,
|
geometry: body.glBuffer,
|
||||||
tf: se3.product(se3.translation(...position), orientation),
|
orientation,
|
||||||
|
position,
|
||||||
glContext,
|
glContext,
|
||||||
glowColor,
|
glowColor,
|
||||||
specularColor,
|
|
||||||
});
|
});
|
||||||
if (parentPosition !== undefined) {
|
if (parentPosition !== undefined) {
|
||||||
const orbitObject = makeOrbitObject(gl, context.orbitGlContext, body.orbit, parentPosition);
|
const orbitObject = makeOrbitObject(gl, context.orbitGlContext, body.orbit, parentPosition);
|
||||||
//objects.push(orbitObject);
|
objects.push(orbitObject);
|
||||||
} else {
|
} else {
|
||||||
const shipTf = se3.product(getShipTf(context), se3.rotxyz(-Math.PI / 2, Math.PI / 2, Math.PI / 2));
|
const shipOrientation = [
|
||||||
|
se3.rotationOnly(player.tf),
|
||||||
|
//se3.rotationOnly(context.camera.tf),
|
||||||
|
se3.rotxyz(-Math.PI / 2, Math.PI / 2, Math.PI / 2),
|
||||||
|
].reduce(se3.product);
|
||||||
|
const shipPos = player.position;
|
||||||
objects.push({
|
objects.push({
|
||||||
geometry: makeBufferFromFaces(gl, context.spaceship),
|
geometry: makeBufferFromFaces(gl, context.spaceship),
|
||||||
tf: shipTf,
|
orientation: shipOrientation,
|
||||||
|
position: shipPos,
|
||||||
glContext,
|
glContext,
|
||||||
specularColor: [0.8, 0.8, 0.8],
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -296,7 +288,7 @@ export function draw(context) {
|
|||||||
const {gl, camera, player, universe, orbit, orbitGlContext, orbitBody} = context;
|
const {gl, camera, player, universe, orbit, orbitGlContext, orbitBody} = context;
|
||||||
const {skyColor, ambiantLight, projMatrix} = context;
|
const {skyColor, ambiantLight, projMatrix} = context;
|
||||||
const objects = getObjects(context, universe);
|
const objects = getObjects(context, universe);
|
||||||
if (orbit !== undefined && orbit.excentricity < 1 && !context.landing) {
|
if (orbit !== undefined && orbit.excentricity < 1) {
|
||||||
objects.push(makeOrbitObject(gl, orbitGlContext, orbit, orbitBody.position));
|
objects.push(makeOrbitObject(gl, orbitGlContext, orbit, orbitBody.position));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -312,23 +304,23 @@ export function draw(context) {
|
|||||||
|
|
||||||
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
|
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
|
||||||
|
|
||||||
const thirdPerson = context.landed ? se3.identity() : se3.translation(0, 1, 4);
|
let camtf;
|
||||||
|
if (camera.overhead) {
|
||||||
const playerView = [
|
camtf = [
|
||||||
player.tf, // player position & orientation
|
se3.translation(0, 500, 0),
|
||||||
camera.tf, // camera orientation relative to player
|
se3.rotx(-Math.PI / 2),
|
||||||
thirdPerson,
|
].reduce(se3.product);
|
||||||
];
|
} else {
|
||||||
if (context.landed) {
|
camtf = [
|
||||||
const body = context.landedBody;
|
player.tf, // player position & orientation
|
||||||
const bodyTf = se3.product(se3.translation(...body.position), body.orientation);
|
camera.tf, // camera orientation relative to player
|
||||||
playerView.splice(0, 0, bodyTf);
|
se3.translation(0, 1, 4), // step back from the player
|
||||||
|
].reduce(se3.product)
|
||||||
}
|
}
|
||||||
|
const viewMatrix = se3.inverse(camtf);
|
||||||
const viewMatrix = se3.inverse(playerView.reduce(se3.product));
|
|
||||||
let lastGlContext;
|
let lastGlContext;
|
||||||
|
|
||||||
for (const {tf, geometry, glContext, glowColor, specularColor} of objects) {
|
for (const {position, orientation, geometry, glContext, glowColor} of objects) {
|
||||||
if (glContext !== lastGlContext) {
|
if (glContext !== lastGlContext) {
|
||||||
glContext.setupScene({
|
glContext.setupScene({
|
||||||
projectionMatrix: projMatrix,
|
projectionMatrix: projMatrix,
|
||||||
@ -338,16 +330,15 @@ export function draw(context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
lastGlContext = glContext;
|
lastGlContext = glContext;
|
||||||
const position = se3.apply(tf, [0, 0, 0, 1]);
|
|
||||||
const lightDirection = sunDirection(position);
|
const lightDirection = sunDirection(position);
|
||||||
|
|
||||||
glContext.drawObject({
|
glContext.drawObject({
|
||||||
tf,
|
position,
|
||||||
|
orientation,
|
||||||
glBuffer: geometry.glBuffer,
|
glBuffer: geometry.glBuffer,
|
||||||
numVertices: geometry.numVertices,
|
numVertices: geometry.numVertices,
|
||||||
lightDirection,
|
lightDirection,
|
||||||
glowColor: glowColor || [0, 0, 0],
|
glowColor: glowColor || [0, 0, 0],
|
||||||
specularColor: specularColor || [0, 0, 0],
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,10 +1,11 @@
|
|||||||
import { makeFace } from 'wmc-common/geometry';
|
import { makeFace } from '../geometry';
|
||||||
|
|
||||||
|
import * as client from './client';
|
||||||
import * as linalg from './linalg';
|
import * as linalg from './linalg';
|
||||||
import { loadObjModel } from './obj';
|
import { loadObjModel } from './obj';
|
||||||
import * as se3 from 'wmc-common/se3';
|
import * as se3 from '../se3';
|
||||||
import { computeOrbit, findSoi, getCartesianState, updateBodyPhysics, isInSoi } from './orbit';
|
import { computeOrbit, findSoi, getCartesianState, updateBodyPhysics } from './orbit';
|
||||||
import { getBodyGeometry, castRay, blockLookup, BlockType } from './chunk';
|
import { getBodyGeometry } from './chunk';
|
||||||
import { draw, getOrbitDrawContext, initWorldGl } from './draw';
|
import { draw, getOrbitDrawContext, initWorldGl } from './draw';
|
||||||
import * as quat from './quat';
|
import * as quat from './quat';
|
||||||
|
|
||||||
@ -17,7 +18,24 @@ function closeToPlanet(context) {
|
|||||||
return linalg.norm(relativePos) < 20;
|
return linalg.norm(relativePos) < 20;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getSolarSystem(seed: number) {
|
async function getSolarSystem(seed: number) {
|
||||||
|
async function getGeometry(body) {
|
||||||
|
const chunks = await client.getBody(body.seed);
|
||||||
|
console.log(chunks);
|
||||||
|
body.geometry = getBodyGeometry(chunks);
|
||||||
|
console.log(body);
|
||||||
|
for (const child of body.children) {
|
||||||
|
await getGeometry(child);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const system = await client.getSystem(seed);
|
||||||
|
await getGeometry(system);
|
||||||
|
|
||||||
|
return system;
|
||||||
|
}
|
||||||
|
|
||||||
|
function _getSolarSystem(seed: number) {
|
||||||
/// XXX: only returns 1 body for now
|
/// XXX: only returns 1 body for now
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@ -157,14 +175,21 @@ function initUiListeners(canvas: HTMLCanvasElement, context) {
|
|||||||
delete context.orbit;
|
delete context.orbit;
|
||||||
return false;
|
return false;
|
||||||
case 'KeyL':
|
case 'KeyL':
|
||||||
context.landing = !context.landing;
|
if (closeToPlanet(context)) {
|
||||||
|
context.landing = True;
|
||||||
|
}
|
||||||
return false;
|
return false;
|
||||||
case 'KeyP':
|
|
||||||
context.pause = !context.pause;
|
case 'KeyO':
|
||||||
|
context.camera.overhead ^= 1;
|
||||||
return false;
|
return false;
|
||||||
case 'Space':
|
case 'Space':
|
||||||
if (!context.flying) {
|
if (!context.flying) {
|
||||||
jump(context);
|
if (context.jumpAmount > 0) {
|
||||||
|
const amount = context.jumpForce;
|
||||||
|
context.player.velocity[1] = amount;
|
||||||
|
context.jumpAmount -= 1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@ -173,20 +198,10 @@ function initUiListeners(canvas: HTMLCanvasElement, context) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
const moveListener = e => {
|
const moveListener = e => {
|
||||||
const cam = context.camera;
|
// context.camera.orientation[0] -= e.movementY / 500;
|
||||||
if (context.landed) {
|
// context.camera.orientation[1] -= e.movementX / 500;
|
||||||
cam.orientation[1] -= e.movementX / 500;
|
context.camera.tf =[
|
||||||
cam.orientation[0] -= e.movementY / 500;
|
context.camera.tf,
|
||||||
cam.tf = [
|
|
||||||
se3.roty(cam.orientation[1]),
|
|
||||||
se3.rotx(cam.orientation[0]),
|
|
||||||
].reduce(se3.product);
|
|
||||||
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
cam.tf =[
|
|
||||||
cam.tf,
|
|
||||||
se3.roty(-e.movementX / 500),
|
se3.roty(-e.movementX / 500),
|
||||||
se3.rotx(-e.movementY / 500),
|
se3.rotx(-e.movementY / 500),
|
||||||
].reduce(se3.product);
|
].reduce(se3.product);
|
||||||
@ -219,93 +234,28 @@ function initUiListeners(canvas: HTMLCanvasElement, context) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function jump(context) {
|
|
||||||
if (context.jumpAmount > 0) {
|
|
||||||
const amount = context.jumpForce;
|
|
||||||
context.jumpAmount -= 1;
|
|
||||||
|
|
||||||
const gravity = landedGravity(context);
|
|
||||||
const up = linalg.normalize(linalg.scale(gravity, -1));
|
|
||||||
context.player.velocity = linalg.scale(up, amount);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function moveShip(context, forward, right) {
|
|
||||||
if (context.keys.has('ShiftLeft')) {
|
|
||||||
forward *= 10;
|
|
||||||
right *= 10;
|
|
||||||
}
|
|
||||||
const tf = se3.product(
|
|
||||||
se3.orientationOnly(context.player.tf),
|
|
||||||
context.camera.tf,
|
|
||||||
);
|
|
||||||
const dir = [right, 0, -forward, 10];
|
|
||||||
if (context.flying) {
|
|
||||||
context.player.tf = [
|
|
||||||
context.player.tf,
|
|
||||||
se3.translation(...dir),
|
|
||||||
].reduce(se3.product);
|
|
||||||
} else {
|
|
||||||
const vel = context.player.velocity;
|
|
||||||
const dv = linalg.scale(se3.apply(tf, dir), 1/dir[3]);
|
|
||||||
context.player.velocity = linalg.add(vel, dv);
|
|
||||||
delete context.orbit;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function moveOnGround(context, forward, right) {
|
|
||||||
if (context.keys.has('ShiftLeft')) {
|
|
||||||
forward *= 2;
|
|
||||||
right *= 2;
|
|
||||||
}
|
|
||||||
const tf = se3.product(
|
|
||||||
se3.orientationOnly(context.player.tf),
|
|
||||||
context.camera.tf,
|
|
||||||
);
|
|
||||||
const dir = se3.apply(tf, [right, 0, -forward, 0]);
|
|
||||||
if (context.flying) {
|
|
||||||
context.player.tf = [
|
|
||||||
se3.translation(...dir),
|
|
||||||
context.player.tf,
|
|
||||||
].reduce(se3.product);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const dv = linalg.scale(dir, 10);
|
|
||||||
|
|
||||||
const maxSpeed = 8;
|
|
||||||
const airMovement = 0.08;
|
|
||||||
|
|
||||||
if (context.isOnGround) {
|
|
||||||
const up = upDirection(context);
|
|
||||||
const vertical = linalg.dot(dv, up);
|
|
||||||
const horizontal = linalg.diff(dv, linalg.scale(up, vertical));
|
|
||||||
context.player.velocity = horizontal;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// steering in the air
|
|
||||||
context.player.velocity = linalg.add(context.player.velocity, linalg.scale(dv, airMovement));
|
|
||||||
|
|
||||||
const curVel = linalg.norm(context.player.velocity);
|
|
||||||
|
|
||||||
if (curVel > maxSpeed) {
|
|
||||||
context.player.velocity = linalg.scale(context.player.velocity, maxSpeed / curVel);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
function handleInput(context) {
|
function handleInput(context) {
|
||||||
const move = (f, r) => (context.landed ? moveOnGround : moveShip)(context, f, r);
|
const move = (forward: number, right: number) => {
|
||||||
|
|
||||||
const roll = (amount: number) => {
|
|
||||||
if (context.keys.has('ShiftLeft')) {
|
if (context.keys.has('ShiftLeft')) {
|
||||||
amount *= 10;
|
forward *= 10;
|
||||||
|
right *= 10;
|
||||||
}
|
}
|
||||||
context.camera.tf =[
|
const tf = se3.product(
|
||||||
|
se3.orientationOnly(context.player.tf),
|
||||||
context.camera.tf,
|
context.camera.tf,
|
||||||
se3.rotz(amount),
|
);
|
||||||
].reduce(se3.product);
|
const dir = [right, 0, -forward, 10];
|
||||||
|
if (context.flying) {
|
||||||
|
context.player.tf = [
|
||||||
|
context.player.tf,
|
||||||
|
se3.translation(...dir),
|
||||||
|
].reduce(se3.product);
|
||||||
|
} else {
|
||||||
|
const vel = context.player.velocity;
|
||||||
|
const dv = linalg.scale(se3.apply(tf, dir), 1/dir[3]);
|
||||||
|
context.player.velocity = linalg.add(vel, dv);
|
||||||
|
delete context.orbit;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
context.keys.forEach(key => {
|
context.keys.forEach(key => {
|
||||||
@ -322,12 +272,6 @@ function handleInput(context) {
|
|||||||
case 'KeyD':
|
case 'KeyD':
|
||||||
move(0.0, 0.5);
|
move(0.0, 0.5);
|
||||||
return;
|
return;
|
||||||
case 'KeyQ':
|
|
||||||
roll(0.02);
|
|
||||||
return;
|
|
||||||
case 'KeyE':
|
|
||||||
roll(-0.02);
|
|
||||||
return;
|
|
||||||
case 'KeyR':
|
case 'KeyR':
|
||||||
context.timeOffset += 1;
|
context.timeOffset += 1;
|
||||||
return;
|
return;
|
||||||
@ -337,253 +281,15 @@ function handleInput(context) {
|
|||||||
|
|
||||||
function slerp(current: linalg.Mat4, target: linalg.Mat4, maxVelocity: number) : linalg.Mat4 {
|
function slerp(current: linalg.Mat4, target: linalg.Mat4, maxVelocity: number) : linalg.Mat4 {
|
||||||
const q0 = quat.mat2Quat(current);
|
const q0 = quat.mat2Quat(current);
|
||||||
let q1 = quat.mat2Quat(target);
|
const q1 = quat.mat2Quat(target);
|
||||||
|
|
||||||
const dq = quat.diff(q1, q0);
|
const dq = quat.diff(q1, q0);
|
||||||
const maxt = maxVelocity / quat.norm(dq);
|
const maxt = maxVelocity / quat.norm(dq);
|
||||||
|
|
||||||
//const q = quat.normalize(quat.add(q0, quat.scale(dq, Math.min(1, maxt))));
|
const q = quat.normalize(quat.add(q0, quat.scale(dq, Math.min(1, maxt))));
|
||||||
const t = maxVelocity;
|
|
||||||
if (quat.dot(q0, q1) < 0) {
|
|
||||||
q1 = quat.scale(q1, -1);
|
|
||||||
}
|
|
||||||
const q = quat.normalize(quat.add(quat.scale(q0, 1 - t), quat.scale(q1, t)));
|
|
||||||
return quat.quat2Mat(q);
|
return quat.quat2Mat(q);
|
||||||
}
|
}
|
||||||
|
|
||||||
function distanceToGround(body: Body, position: number[], direction: number[]) : number {
|
|
||||||
const inChunkOrientation = se3.inverse(body.orientation);
|
|
||||||
const toChunk = vec => se3.apply(inChunkOrientation, vec.concat([0]));
|
|
||||||
const directionInChunk = toChunk(direction);
|
|
||||||
const positionInChunk = toChunk(linalg.diff(position, body.position));
|
|
||||||
|
|
||||||
const hit = castRay(body.geometry.chunkMap, positionInChunk, directionInChunk);
|
|
||||||
|
|
||||||
if (hit === undefined || hit.block.type === BlockType.UNDEFINED || hit.block.type === undefined) {
|
|
||||||
const ray = linalg.diff(position, body.position);
|
|
||||||
return {
|
|
||||||
distance: linalg.norm(ray),
|
|
||||||
normal: linalg.normalize(ray),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const distance = linalg.norm(linalg.diff(positionInChunk, hit.block.centerPosition));
|
|
||||||
const normal = se3.apply(body.orientation, hit.normal.concat([0]));
|
|
||||||
return {distance, normal};
|
|
||||||
}
|
|
||||||
|
|
||||||
function finishLanding(context, body) {
|
|
||||||
const p = context.player;
|
|
||||||
context.landed = true;
|
|
||||||
context.landedBody = body;
|
|
||||||
|
|
||||||
p.tf = [
|
|
||||||
se3.inverse(body.orientation),
|
|
||||||
se3.inverse(se3.translation(...body.position)),
|
|
||||||
p.tf,
|
|
||||||
].reduce(se3.product);
|
|
||||||
|
|
||||||
context.shipTf = p.tf;
|
|
||||||
p.tf = se3.product(p.tf, se3.translation(1, 1, 0));
|
|
||||||
p.velocity = [0, 0, 0];
|
|
||||||
p.position = se3.apply(p.tf, [0, 0, 0, 1]);
|
|
||||||
}
|
|
||||||
|
|
||||||
function alignUp(playerTf, surfaceNormal) {
|
|
||||||
const zaxis = se3.apply(playerTf, [0, 0, 1, 0]);
|
|
||||||
const ny = surfaceNormal;
|
|
||||||
const nx = linalg.normalize(linalg.cross(ny, zaxis));
|
|
||||||
const nz = linalg.normalize(linalg.cross(nx, ny));
|
|
||||||
|
|
||||||
return se3.fromBases(nx, ny, nz);
|
|
||||||
}
|
|
||||||
|
|
||||||
function calculateLandingDv(verticalSpeed, altitude, dt) {
|
|
||||||
// pretty crude logic, could be improved
|
|
||||||
const maxThrust = 2;
|
|
||||||
const final = verticalSpeed**2 / (2*(altitude - 1.0));
|
|
||||||
|
|
||||||
if (verticalSpeed > 0 || final < maxThrust * 0.8) {
|
|
||||||
// can still accelerate forward
|
|
||||||
return -maxThrust * dt;
|
|
||||||
} else if (final < maxThrust) {
|
|
||||||
// coast
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
return final;
|
|
||||||
}
|
|
||||||
|
|
||||||
function autoLand(context, dt) {
|
|
||||||
const p = context.player;
|
|
||||||
// 0. check prereqs:
|
|
||||||
// - none
|
|
||||||
// 1. adjust tangential speed to match body rotational
|
|
||||||
// 2. cast ray towards center
|
|
||||||
// 3. while high, go towards center
|
|
||||||
// 4. when low, go towards ground
|
|
||||||
// 5. stop when on ground
|
|
||||||
const kShipRotateSpeed = 0.1;
|
|
||||||
|
|
||||||
const body = findSoi(context.universe, p.position);
|
|
||||||
const toBodyCenter = linalg.diff(body.position, p.position);
|
|
||||||
const {distance: altitude, normal: surfaceNormal} = distanceToGround(body, p.position, linalg.normalize(toBodyCenter));
|
|
||||||
|
|
||||||
const surfaceVelocity = linalg.add(body.velocity, linalg.cross(body.spin, linalg.scale(toBodyCenter, -1)));
|
|
||||||
const relativeVelocity = linalg.diff(p.velocity, surfaceVelocity);
|
|
||||||
const upward = linalg.dot(relativeVelocity, surfaceNormal);
|
|
||||||
const vertical = linalg.scale(surfaceNormal, upward);
|
|
||||||
const horizontal = linalg.diff(relativeVelocity, vertical);
|
|
||||||
const smallDv = linalg.scale(horizontal, -0.01);
|
|
||||||
p.velocity = linalg.add(p.velocity, smallDv);
|
|
||||||
|
|
||||||
// up is up
|
|
||||||
const currentOrientation = slerp(p.tf, alignUp(p.tf, surfaceNormal), kShipRotateSpeed);
|
|
||||||
p.tf = se3.setOrientation(p.tf, currentOrientation);
|
|
||||||
|
|
||||||
if (altitude < 1.5) {
|
|
||||||
if (upward < -2) {
|
|
||||||
// going too fast, bounce
|
|
||||||
p.velocity = linalg.add(p.velocity, linalg.scale(surfaceNormal, -2*upward));
|
|
||||||
context.landing = false;
|
|
||||||
} else if (upward < 0) {
|
|
||||||
finishLanding(context, body);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// accelerate towards the ground and then slow down to land
|
|
||||||
const dvup = calculateLandingDv(upward, altitude, dt);
|
|
||||||
p.velocity = linalg.add(p.velocity, linalg.scale(surfaceNormal, dvup));
|
|
||||||
}
|
|
||||||
|
|
||||||
function effectiveGravity(position: number[], rootBody: Body) : number[] {
|
|
||||||
let body = rootBody;
|
|
||||||
let acceleration = [0, 0, 0];
|
|
||||||
while (body !== undefined) {
|
|
||||||
const toBodyCenter = linalg.diff(body.position, position);
|
|
||||||
const d = linalg.norm(toBodyCenter);
|
|
||||||
const gravity = body.mass / d**3;
|
|
||||||
acceleration = linalg.add(acceleration, linalg.scale(toBodyCenter, gravity));
|
|
||||||
|
|
||||||
const parentMass = body.mass;
|
|
||||||
const children = body.children || [];
|
|
||||||
body = undefined;
|
|
||||||
for (const child of children) {
|
|
||||||
if (!isInSoi(child, parentMass, position)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
body = child;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return acceleration;
|
|
||||||
}
|
|
||||||
|
|
||||||
function upDirection(context) {
|
|
||||||
const gravity = landedGravity(context);
|
|
||||||
return linalg.normalize(linalg.scale(gravity, -1));
|
|
||||||
}
|
|
||||||
|
|
||||||
function landedGravity(context) {
|
|
||||||
// just clamp "down" to one of our six directions
|
|
||||||
const pos = context.player.position;
|
|
||||||
const altitude2 = pos[0]**2 + pos[1]**2 + pos[2]**2;
|
|
||||||
const g = context.landedBody.mass / altitude2;
|
|
||||||
if (pos[0] > 0 && Math.abs(pos[1]) < pos[0] && Math.abs(pos[2]) < pos[0]) {
|
|
||||||
return [-g, 0, 0];
|
|
||||||
}
|
|
||||||
if (pos[0] < 0 && Math.abs(pos[1]) < -pos[0] && Math.abs(pos[2]) < -pos[0]) {
|
|
||||||
return [+g, 0, 0];
|
|
||||||
}
|
|
||||||
if (pos[1] > 0 && Math.abs(pos[0]) < pos[1] && Math.abs(pos[2]) < pos[1]) {
|
|
||||||
return [0, -g, 0];
|
|
||||||
}
|
|
||||||
if (pos[1] < 0 && Math.abs(pos[0]) < -pos[1] && Math.abs(pos[2]) < -pos[1]) {
|
|
||||||
return [0, +g, 0];
|
|
||||||
}
|
|
||||||
if (pos[2] > 0 && Math.abs(pos[1]) < pos[2] && Math.abs(pos[1]) < pos[2]) {
|
|
||||||
return [0, 0, -g];
|
|
||||||
}
|
|
||||||
if (pos[2] < 0 && Math.abs(pos[1]) < -pos[2] && Math.abs(pos[1]) < -pos[2]) {
|
|
||||||
return [0, 0, +g];
|
|
||||||
}
|
|
||||||
// blarg
|
|
||||||
}
|
|
||||||
|
|
||||||
function checkCollision(curPos, newPos, chunkMap, orientation) {
|
|
||||||
const upDir = se3.apply(orientation, [0, 1, 0, 0]);
|
|
||||||
// I guess Gaspard is about 1.7 m tall?
|
|
||||||
// he also has a 60x60 cm axis-aligned square section '^_^
|
|
||||||
// box is centered around the camera
|
|
||||||
const gaspardBB = [
|
|
||||||
[-0.3, 0.2, -0.3],
|
|
||||||
[-0.3, 0.2, 0.3],
|
|
||||||
[0.3, 0.2, -0.3],
|
|
||||||
[0.3, 0.2, 0.3],
|
|
||||||
|
|
||||||
[-0.3, -1.5, -0.3],
|
|
||||||
[-0.3, -1.5, 0.3],
|
|
||||||
[0.3, -1.5, -0.3],
|
|
||||||
[0.3, -1.5, 0.3],
|
|
||||||
].map(v => se3.apply(orientation, v.concat([0])));
|
|
||||||
|
|
||||||
let dp = linalg.diff(newPos, curPos);
|
|
||||||
let isOnGround = false;
|
|
||||||
|
|
||||||
for (let i = 0; i < 3; i++) {
|
|
||||||
const newGaspard = v => v.map((x, j) => i === j ? x + newPos[j] : x + curPos[j]);
|
|
||||||
for (const point of gaspardBB.map(newGaspard)) {
|
|
||||||
const block = blockLookup(chunkMap, ...point);
|
|
||||||
if (block.type !== BlockType.AIR) {
|
|
||||||
const dir = [...Array(3).keys()].map(j => j === i ? 1 : 0);
|
|
||||||
if (Math.abs(linalg.dot(dir, upDir)) > 0.5) {
|
|
||||||
isOnGround = true;
|
|
||||||
}
|
|
||||||
dp[i] = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (let i = 0; i < 3; i++) {
|
|
||||||
const newGaspard = v => linalg.add(linalg.add(curPos, v), dp);
|
|
||||||
for (const point of gaspardBB.map(newGaspard)) {
|
|
||||||
const block = blockLookup(chunkMap, ...point);
|
|
||||||
if (block.type !== BlockType.AIR) {
|
|
||||||
dp[i] = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
newPos: linalg.add(curPos, dp),
|
|
||||||
isOnGround,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function updateLandedPhysics(context, dt) {
|
|
||||||
const gravity = landedGravity(context);
|
|
||||||
context.player.velocity = linalg.add(context.player.velocity, linalg.scale(gravity, dt));
|
|
||||||
|
|
||||||
const oldPos = context.player.position;
|
|
||||||
const taregtPos = linalg.add(context.player.position, linalg.scale(context.player.velocity, dt));
|
|
||||||
|
|
||||||
// from wmc
|
|
||||||
const {isOnGround, newPos} = checkCollision(oldPos, taregtPos, context.landedBody.geometry.chunkMap, se3.orientationOnly(context.player.tf));
|
|
||||||
context.player.position = newPos;
|
|
||||||
context.player.velocity = newPos.map((p, i) => (p - oldPos[i]) / dt);
|
|
||||||
if (isOnGround) {
|
|
||||||
context.jumpAmount = 2;
|
|
||||||
context.player.velocity = context.player.velocity.map(v => v * 0.7);
|
|
||||||
}
|
|
||||||
context.isOnGround = isOnGround;
|
|
||||||
context.player.tf = se3.setPosition(context.player.tf, newPos);
|
|
||||||
|
|
||||||
// up is up
|
|
||||||
const p = context.player;
|
|
||||||
const currentOrientation = slerp(p.tf, alignUp(p.tf, upDirection(context)), 0.1);
|
|
||||||
p.tf = se3.setOrientation(p.tf, currentOrientation);
|
|
||||||
}
|
|
||||||
|
|
||||||
function updatePhysics(time: number, context) {
|
function updatePhysics(time: number, context) {
|
||||||
const {player} = context;
|
const {player} = context;
|
||||||
const dt = time - (context.lastTime || 0);
|
const dt = time - (context.lastTime || 0);
|
||||||
@ -591,41 +297,37 @@ function updatePhysics(time: number, context) {
|
|||||||
|
|
||||||
player.position = se3.apply(player.tf, [0, 0, 0, 1]);
|
player.position = se3.apply(player.tf, [0, 0, 0, 1]);
|
||||||
|
|
||||||
if (!context.pause) {
|
updateBodyPhysics(time, context.universe);
|
||||||
updateBodyPhysics(time, context.universe);
|
|
||||||
}
|
|
||||||
|
|
||||||
const kShipRotateSpeed = 0.1;
|
const dr = slerp(se3.identity(), context.camera.tf, 0.007);
|
||||||
|
player.tf = se3.product(player.tf, dr);
|
||||||
|
context.camera.tf = se3.product(context.camera.tf, se3.inverse(dr));
|
||||||
|
|
||||||
if (context.landed) {
|
if (!context.flying) {
|
||||||
return updateLandedPhysics(context, dt);
|
if (context.orbit === undefined) {
|
||||||
}
|
const newPos = linalg.add(player.position, linalg.scale(player.velocity, dt));
|
||||||
|
const dx = linalg.diff(newPos, player.position);
|
||||||
|
player.tf = se3.product(se3.translation(...dx), player.tf);
|
||||||
|
|
||||||
if (context.landing) {
|
const body = findSoi(context.universe, context.player.position);
|
||||||
autoLand(context, dt);
|
context.orbit = computeOrbit(player, body, time);
|
||||||
} else {
|
console.log(`orbiting ${body.name}, excentricity: ${context.orbit.excentricity}`);
|
||||||
// allow adjusting camera
|
context.orbitBody = body;
|
||||||
const dr = slerp(se3.identity(), context.camera.tf, kShipRotateSpeed);
|
} else {
|
||||||
player.tf = se3.product(player.tf, dr);
|
const {position: orbitPos, velocity: orbitVel} = getCartesianState(
|
||||||
context.camera.tf = se3.product(context.camera.tf, se3.inverse(dr));
|
context.orbit, context.orbitBody.mass, time);
|
||||||
}
|
if (orbitPos === undefined) {
|
||||||
|
const newPos = linalg.add(player.position, linalg.scale(player.velocity, dt));
|
||||||
if (context.flying) {
|
const dx = linalg.diff(newPos, player.position);
|
||||||
// no physics, just magically moving around
|
player.tf = se3.product(se3.translation(...dx), player.tf);
|
||||||
return;
|
} else {
|
||||||
}
|
const position = linalg.add(orbitPos, context.orbitBody.position);
|
||||||
|
const velocity = linalg.add(orbitVel, context.orbitBody.velocity);
|
||||||
const gravity = effectiveGravity(player.position, context.universe);
|
player.velocity = velocity;
|
||||||
player.velocity = linalg.add(player.velocity, linalg.scale(gravity, dt));
|
const dx = linalg.diff(position, player.position);
|
||||||
|
player.tf = se3.product(se3.translation(...dx), player.tf);
|
||||||
const newPos = linalg.add(player.position, linalg.scale(player.velocity, dt));
|
}
|
||||||
player.tf = se3.setPosition(player.tf, newPos);
|
}
|
||||||
|
|
||||||
if (context.orbit === undefined) {
|
|
||||||
const body = findSoi(context.universe, context.player.position);
|
|
||||||
context.orbit = computeOrbit(player, body, time);
|
|
||||||
console.log(`orbiting ${body.name}, excentricity: ${context.orbit.excentricity}`);
|
|
||||||
context.orbitBody = body;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -633,6 +335,7 @@ function updateGeometry(context, timeout_ms = 10) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function tick(time: number, context) {
|
function tick(time: number, context) {
|
||||||
|
time = new Date().getTime();
|
||||||
handleInput(context);
|
handleInput(context);
|
||||||
const simTime = time * 0.001 + context.timeOffset;
|
const simTime = time * 0.001 + context.timeOffset;
|
||||||
updatePhysics(simTime, context);
|
updatePhysics(simTime, context);
|
||||||
@ -656,16 +359,14 @@ function tick(time: number, context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function makeCube(texture) {
|
function makeCube(texture) {
|
||||||
return {
|
return [
|
||||||
faces: [
|
makeFace('-x', texture, [-0.5, 0, 0]),
|
||||||
makeFace('-x', texture, [-0.5, 0, 0]),
|
makeFace('+x', texture, [+0.5, 0, 0]),
|
||||||
makeFace('+x', texture, [+0.5, 0, 0]),
|
makeFace('-y', texture, [0, -0.5, 0]),
|
||||||
makeFace('-y', texture, [0, -0.5, 0]),
|
makeFace('+y', texture, [0, +0.5, 0]),
|
||||||
makeFace('+y', texture, [0, +0.5, 0]),
|
makeFace('-z', texture, [0, 0, -0.5]),
|
||||||
makeFace('-z', texture, [0, 0, -0.5]),
|
makeFace('+z', texture, [0, 0, +0.5]),
|
||||||
makeFace('+z', texture, [0, 0, +0.5]),
|
];
|
||||||
]
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
@ -682,7 +383,7 @@ async function main() {
|
|||||||
// TODO
|
// TODO
|
||||||
// [ ] loading bar
|
// [ ] loading bar
|
||||||
// [x] spaceship
|
// [x] spaceship
|
||||||
// [x] landing
|
// [ ] landing
|
||||||
// [ ] huge planets
|
// [ ] huge planets
|
||||||
// [x] lighting
|
// [x] lighting
|
||||||
// [x] better lighting
|
// [x] better lighting
|
||||||
@ -712,7 +413,7 @@ async function main() {
|
|||||||
isOnGround: false,
|
isOnGround: false,
|
||||||
gravity: -17,
|
gravity: -17,
|
||||||
jumpForce: 6.5,
|
jumpForce: 6.5,
|
||||||
universe: getSolarSystem(0),
|
universe: await getSolarSystem(0),
|
||||||
timeOffset: 0,
|
timeOffset: 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -721,10 +422,11 @@ async function main() {
|
|||||||
initUiListeners(canvas, context);
|
initUiListeners(canvas, context);
|
||||||
|
|
||||||
const starshipGeom = await modelPromise;
|
const starshipGeom = await modelPromise;
|
||||||
|
console.log(`loaded ${starshipGeom.length} triangles`);
|
||||||
|
|
||||||
context.spaceship = starshipGeom;
|
context.spaceship = starshipGeom;
|
||||||
|
|
||||||
requestAnimationFrame(time => tick(time, context));
|
requestAnimationFrame(time => tick(time, context));
|
||||||
}
|
}
|
||||||
|
|
||||||
window.onload = main;
|
window.onload = main;
|
@ -38,8 +38,4 @@ export function scale(a: Vec3, s: number) : Vec3 {
|
|||||||
a[1] * s,
|
a[1] * s,
|
||||||
a[2] * s,
|
a[2] * s,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function normalize(a: Vec3) : Vec3 {
|
|
||||||
return scale(a, 1/norm(a));
|
|
||||||
}
|
|
495
skycraft/orbit.html
Normal file
495
skycraft/orbit.html
Normal file
@ -0,0 +1,495 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Kepler orbit simulation</title>
|
||||||
|
<style>
|
||||||
|
#canvas {
|
||||||
|
border: 1px solid black;
|
||||||
|
margin-right: 10px;
|
||||||
|
width: 500px;
|
||||||
|
height: 500px;
|
||||||
|
}
|
||||||
|
#info {
|
||||||
|
width: 300px;
|
||||||
|
border: 1px solid black;
|
||||||
|
padding: 6px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<table cellspacing="0" cellpadding="0">
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<td>
|
||||||
|
<canvas id="canvas"></canvas>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
Kepler orbit simulation<br><br>
|
||||||
|
<div id="info"></div>
|
||||||
|
<br><br>
|
||||||
|
- Press the space bar to start/stop the simulation<br>
|
||||||
|
- Drag the green circle/arrowhead to change the position/velocity<br>
|
||||||
|
- Scroll to zoom in/out<br>
|
||||||
|
- Press the arrow keys to adjust the velocity
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function Point(x, y) {
|
||||||
|
this.x = x;
|
||||||
|
this.y = y;
|
||||||
|
}
|
||||||
|
|
||||||
|
function State(e, p, u, thp, th0, ccw, E, t) {
|
||||||
|
this.e = e; // eccentricity
|
||||||
|
this.p = p; // semi-latus rectum
|
||||||
|
this.u = u; // G(m_1 + m_2)
|
||||||
|
this.thp = thp; // initial true anomaly
|
||||||
|
this.th0 = th0; //
|
||||||
|
this.ccw = ccw; // counter-clockwise orbit
|
||||||
|
this.t = t; // time since periapsis
|
||||||
|
this.E = E; // eccentric anomaly (redundant with t)
|
||||||
|
|
||||||
|
// redundant info (for performance)
|
||||||
|
this.r = new Point(0, 0); // position
|
||||||
|
this.v = new Point(0, 0); // velocity
|
||||||
|
this.T = 0; // period
|
||||||
|
}
|
||||||
|
|
||||||
|
function norm(v) { return Math.sqrt(v.x * v.x + v.y * v.y); }
|
||||||
|
|
||||||
|
function add(v, w) { return new Point(v.x + w.x, v.y + w.y); }
|
||||||
|
function minus(v, w) { return new Point(v.x - w.x, v.y - w.y); }
|
||||||
|
function mult(v, c) { return new Point(v.x * c, v.y * c); }
|
||||||
|
|
||||||
|
function dot(v, w) { return v.x * w.x + v.y * w.y; }
|
||||||
|
function vccw(v, w) { return v.x * w.y - v.y * w.x; }
|
||||||
|
|
||||||
|
function pow2(x) { return x*x; }
|
||||||
|
function cosh(x) { return (Math.exp(x) + Math.exp(-x)) / 2; }
|
||||||
|
function sinh(x) { return (Math.exp(x) - Math.exp(-x)) / 2; }
|
||||||
|
function tanh(x) { return (Math.exp(x) - Math.exp(-x)) / (Math.exp(x) + Math.exp(-x)); }
|
||||||
|
function atanh(x) { return 0.5 * Math.log((1 + x) / (1 - x)); }
|
||||||
|
|
||||||
|
var G = 6.67384e-11; // gravitational constant
|
||||||
|
var m1 = 5.97219e24; // mass of the center object
|
||||||
|
var m2 = 7.3477e22; // mass of the orbiting object
|
||||||
|
var u = G * (m1 + m2);
|
||||||
|
var st; // the state variable
|
||||||
|
|
||||||
|
(function(){
|
||||||
|
// initial states
|
||||||
|
var a = 384748000;
|
||||||
|
var e=0.0549006, p=a*(1-e*e), thp=0, th0=0, ccw=true;
|
||||||
|
var t=0;
|
||||||
|
var E=0;
|
||||||
|
st = new State(e, p, u, thp, th0, ccw, E, t);
|
||||||
|
})();
|
||||||
|
|
||||||
|
|
||||||
|
var canvas = document.getElementById("canvas");
|
||||||
|
var ctx = canvas.getContext("2d");
|
||||||
|
|
||||||
|
var dpr = window.devicePixelRatio || 1;
|
||||||
|
canvas.width = 500 * dpr;
|
||||||
|
canvas.height = 500 * dpr;
|
||||||
|
ctx.scale(dpr, dpr);
|
||||||
|
|
||||||
|
var vscale = 50000;
|
||||||
|
var drawScale = 1/2000000;
|
||||||
|
|
||||||
|
function toTheta(E, e) {
|
||||||
|
// eccentric anomaly -> true anomaly
|
||||||
|
if (e < 1)
|
||||||
|
return 2 * Math.atan( Math.sqrt((1+e) / (1-e)) * Math.tan(E/2) );
|
||||||
|
if (e > 1)
|
||||||
|
return 2 * Math.atan( Math.sqrt((1+e) / (e-1)) * tanh(E/2) );
|
||||||
|
return 2 * Math.atan(E);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toE(theta, e) {
|
||||||
|
// true anomaly -> eccentric anomaly
|
||||||
|
if (e < 1)
|
||||||
|
return Math.atan2( Math.sqrt(1-e*e) * Math.sin(theta) , e + Math.cos(theta));
|
||||||
|
if (e > 1)
|
||||||
|
return atanh( Math.sqrt(e*e-1) * Math.sin(theta) / ( e +Math.cos(theta)));
|
||||||
|
return Math.tan(theta / 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
function findT(E, e, u, p, ccw) {
|
||||||
|
// eccentric anomaly -> time since periapsis
|
||||||
|
if (!ccw)
|
||||||
|
E = -E;
|
||||||
|
var a = p / (1 - e*e);
|
||||||
|
if (e < 1)
|
||||||
|
return a * Math.sqrt(a / u) * (E - e * Math.sin(E));
|
||||||
|
if (e > 1)
|
||||||
|
return -a * Math.sqrt(-a / u) * (e * sinh(E) - E);
|
||||||
|
return Math.sqrt(p * p * p / (u * 8)) * (E + E*E*E/3);
|
||||||
|
}
|
||||||
|
|
||||||
|
function findE(t, e, u, p, E0, ccw) {
|
||||||
|
// time since periapsis -> eccentric anomaly
|
||||||
|
var E = E0;
|
||||||
|
var a = p / (1 - e*e);
|
||||||
|
if (e < 1)
|
||||||
|
M = Math.sqrt(u / (a*a*a)) * t;
|
||||||
|
else if (e > 1)
|
||||||
|
M = Math.sqrt(u / (-a*a*a)) * t;
|
||||||
|
else
|
||||||
|
M = Math.sqrt((u * 8) / (p * p * p)) * t;
|
||||||
|
|
||||||
|
if (!ccw)
|
||||||
|
M = -M;
|
||||||
|
|
||||||
|
// Newton's method
|
||||||
|
var E2;
|
||||||
|
for (var i = 1; i < 20; ++i) {
|
||||||
|
if (e < 1)
|
||||||
|
E2 = E - (E - e * Math.sin(E) - M) / (1 - e * Math.cos(E));
|
||||||
|
else if (e > 1)
|
||||||
|
E2 = E - (-E + e * sinh(E) - M) / (e * cosh(E) - 1);
|
||||||
|
else
|
||||||
|
E2 = E - (E + E*E*E/3 - M) / (1 + E*E);
|
||||||
|
if (Math.abs(E - E2) < 1e-10)
|
||||||
|
break;
|
||||||
|
E = E2;
|
||||||
|
}
|
||||||
|
return E;
|
||||||
|
}
|
||||||
|
|
||||||
|
function calculateState(r, v, u) {
|
||||||
|
// Find the state variables from initial position and velocity
|
||||||
|
|
||||||
|
var ccw = vccw(r, v);
|
||||||
|
|
||||||
|
// TODO: radial trajectory - this is a non-trivial special case.
|
||||||
|
if (ccw == 0) {
|
||||||
|
v.x += 0.1; // cheat
|
||||||
|
ccw = vccw(r, v);
|
||||||
|
}
|
||||||
|
|
||||||
|
var rs = norm(r);
|
||||||
|
//r1 = new Point(r.x / rs, r.y / rs);
|
||||||
|
//vr = dot(v, r1);
|
||||||
|
//vtt = new Point(v.x - r1.x * vr, v.y - r1.y * vr);
|
||||||
|
//r1 = new Point(r.x / rs, r.y / rs);
|
||||||
|
var vr = dot(v, r) / rs;
|
||||||
|
var k = dot(v, r) / dot(r, r);
|
||||||
|
var vrr = new Point(r.x * k, r.y * k);
|
||||||
|
var vtt = new Point(v.x - vrr.x, v.y - vrr.y);
|
||||||
|
|
||||||
|
var vt = norm(vtt);
|
||||||
|
|
||||||
|
var p = dot(r, r) * dot(vtt, vtt) / u;
|
||||||
|
var v0 = u / Math.sqrt(dot(r, r) * dot(vtt, vtt));
|
||||||
|
var v0inv = Math.sqrt(dot(r, r) * dot(vtt, vtt)) / u;
|
||||||
|
//v0 = u / Math.sqrt();
|
||||||
|
var e = Math.sqrt( pow2(vt*v0inv - 1) + pow2(vr*v0inv) );
|
||||||
|
//v02 = u / p;
|
||||||
|
//e = Math.sqrt( dot(vtt,vtt) - 2*vt*v0 + v02 + (dot(v, r) * dot(v, r) / dot(r, r) )) / v0;
|
||||||
|
|
||||||
|
//e2 = Math.sqrt(dot(vtt,vtt) - 2*vt*v0 + v02 + (dot(v, r) * dot(v, r) / dot(r, r) ));
|
||||||
|
//cos = (vt/v0-1) / e;
|
||||||
|
//sin = (vr / v0) / e;
|
||||||
|
|
||||||
|
//cos = (vt - v0) / e2;
|
||||||
|
//sin = vr / e2;
|
||||||
|
|
||||||
|
var thp = Math.atan2(vr, vt - v0);
|
||||||
|
if (ccw < 0)
|
||||||
|
thp = -thp;
|
||||||
|
|
||||||
|
var th0 = Math.atan2(r.y, r.x);
|
||||||
|
|
||||||
|
return new State(e, p, u, thp, th0, ccw >= 0, st.E, st.t);
|
||||||
|
}
|
||||||
|
|
||||||
|
function findRV(st) {
|
||||||
|
// Find the position and velocity of the current state
|
||||||
|
var e = st.e;
|
||||||
|
var p = st.p;
|
||||||
|
var u = st.u;
|
||||||
|
var thp = st.thp;
|
||||||
|
var th0 = st.th0;
|
||||||
|
var E = st.E;
|
||||||
|
var ccw = st.ccw;
|
||||||
|
|
||||||
|
var theta = toTheta(E, e);
|
||||||
|
var rv = p / (1+e*Math.cos(theta));
|
||||||
|
var r = new Point(rv*Math.cos((th0 - thp) + theta), rv*Math.sin((th0 - thp) + theta));
|
||||||
|
|
||||||
|
var v0 = Math.sqrt(u / p);
|
||||||
|
var vt = (e * Math.cos(theta) + 1) * v0;
|
||||||
|
var vr = e * Math.sin(theta) * v0;
|
||||||
|
var rs = norm(r);
|
||||||
|
var r1 = new Point(r.x / rs, r.y / rs);
|
||||||
|
var t1 = new Point(-r1.y, r1.x);
|
||||||
|
if (!ccw) {
|
||||||
|
vt = -vt;
|
||||||
|
vr = -vr;
|
||||||
|
}
|
||||||
|
|
||||||
|
var v = new Point(vr*r1.x + vt*t1.x, vr*r1.y + vt*t1.y);
|
||||||
|
|
||||||
|
// cache
|
||||||
|
st.r = r;
|
||||||
|
st.v = v;
|
||||||
|
|
||||||
|
return {r:r, v:v};
|
||||||
|
}
|
||||||
|
|
||||||
|
function recalculate(_st, dx, dy) {
|
||||||
|
// Adjust the velocity by (dx, dy)
|
||||||
|
var d = findRV(_st);
|
||||||
|
var r = d.r;
|
||||||
|
var v = d.v;
|
||||||
|
v = new Point(v.x + dx, v.y + dy);
|
||||||
|
|
||||||
|
st = calculateState(r, v, _st.u);
|
||||||
|
st.E = toE(st.thp, st.e);
|
||||||
|
st.t = findT(st.E, st.e, st.u, st.p, st.ccw);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function redraw(st) {
|
||||||
|
var e = st.e;
|
||||||
|
var p = st.p;
|
||||||
|
var u = st.u;
|
||||||
|
var thp = st.thp;
|
||||||
|
var th0 = st.th0;
|
||||||
|
|
||||||
|
ctx.clearRect(0, 0, 500, 500);
|
||||||
|
|
||||||
|
ctx.save();
|
||||||
|
ctx.translate(250, 250);
|
||||||
|
|
||||||
|
// center
|
||||||
|
ctx.fillStyle="#FF0000";
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(0, 0, 6, 0, 2*Math.PI);
|
||||||
|
ctx.fill();
|
||||||
|
|
||||||
|
// trace
|
||||||
|
ctx.strokeStyle ="#FF0000";
|
||||||
|
if (e == 0) { // circle
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(0, 0, p*drawScale, 0, 2*Math.PI);
|
||||||
|
ctx.stroke();
|
||||||
|
} /*else if (e < 1) { // ellipse
|
||||||
|
ctx.save();
|
||||||
|
var a = p / (1 - e*e);
|
||||||
|
ctx.rotate( th0 - thp );
|
||||||
|
ctx.translate(-e * a, 0);
|
||||||
|
ctx.scale(1, Math.sqrt(1 - e*e));
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(0, 0, a, 0, 2*Math.PI);
|
||||||
|
ctx.stroke();
|
||||||
|
ctx.restore();
|
||||||
|
} */ else {
|
||||||
|
var th;
|
||||||
|
var rv;
|
||||||
|
ctx.beginPath();
|
||||||
|
for (th=-Math.PI; th < Math.PI; th+=0.01) {
|
||||||
|
rv = p / (1+e*Math.cos(th));
|
||||||
|
if (rv <= 0)
|
||||||
|
continue;
|
||||||
|
ctx.lineTo( rv*Math.cos(th + (th0 - thp))*drawScale, rv*Math.sin(th + (th0 - thp))*drawScale );
|
||||||
|
}
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
var d = findRV(st);
|
||||||
|
var r = d.r;
|
||||||
|
var v = d.v;
|
||||||
|
|
||||||
|
// the orbiting object
|
||||||
|
ctx.fillStyle ="#008000";
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.arc(r.x * drawScale, r.y * drawScale, 5, 0, 2*Math.PI);
|
||||||
|
ctx.fill();
|
||||||
|
|
||||||
|
// the velocity line
|
||||||
|
ctx.strokeStyle ="#0000FF";
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.moveTo(r.x * drawScale, r.y * drawScale);
|
||||||
|
ctx.lineTo((r.x + v.x * vscale) * drawScale, (r.y + v.y * vscale) * drawScale);
|
||||||
|
ctx.stroke();
|
||||||
|
|
||||||
|
// arrowhead
|
||||||
|
ctx.save();
|
||||||
|
ctx.translate((r.x + v.x * vscale) * drawScale, (r.y + v.y * vscale) * drawScale);
|
||||||
|
ctx.rotate(-Math.atan2(v.x, v.y));
|
||||||
|
ctx.strokeStyle ="#0000FF";
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.moveTo(-8, -10);
|
||||||
|
ctx.lineTo(0, 0);
|
||||||
|
ctx.lineTo(8, -10);
|
||||||
|
ctx.stroke();
|
||||||
|
ctx.restore();
|
||||||
|
|
||||||
|
ctx.restore();
|
||||||
|
|
||||||
|
updateInfo();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
var moving = false;
|
||||||
|
var timer;
|
||||||
|
|
||||||
|
redraw(st);
|
||||||
|
|
||||||
|
|
||||||
|
var state = 0;
|
||||||
|
var r0, v0;
|
||||||
|
var saveMoving;
|
||||||
|
|
||||||
|
canvas.onmousemove = function(event) {
|
||||||
|
var x = event.offsetX == undefined ? event.layerX : event.offsetX;
|
||||||
|
var y = event.offsetY == undefined ? event.layerY : event.offsetY;
|
||||||
|
var p = mult(new Point(x - 250, y - 250), 1/drawScale);
|
||||||
|
var d = findRV(st);
|
||||||
|
var r = d.r;
|
||||||
|
var v = d.v;
|
||||||
|
|
||||||
|
if (state <= 2) {
|
||||||
|
if (norm(minus(p, r)) < 14 / drawScale) {
|
||||||
|
canvas.style.cursor = 'pointer';
|
||||||
|
state = 1;
|
||||||
|
} else if (norm( minus( add(r, mult(v, vscale)) , p ) ) < 14 / drawScale) {
|
||||||
|
canvas.style.cursor = 'pointer';
|
||||||
|
state = 2;
|
||||||
|
} else {
|
||||||
|
canvas.style.cursor = 'default';
|
||||||
|
state = 0;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if (state == 3) {
|
||||||
|
if (p.x == 0 && p.y == 0)
|
||||||
|
p.x = 0.1;
|
||||||
|
r = p;
|
||||||
|
v = v0;
|
||||||
|
} else if (state == 4) {
|
||||||
|
r = r0;
|
||||||
|
v = mult(minus(p, r), 1/vscale);
|
||||||
|
}
|
||||||
|
|
||||||
|
st = calculateState(r, v, st.u);
|
||||||
|
var thp = st.thp;
|
||||||
|
var th0 = st.th0;
|
||||||
|
|
||||||
|
st.E = toE(thp, st.e); // why only THP ?
|
||||||
|
st.t = findT(st.E, st.e, st.u, st.p, st.ccw);
|
||||||
|
redraw(st);
|
||||||
|
}
|
||||||
|
|
||||||
|
canvas.onmousedown = function(event) {
|
||||||
|
var d = findRV(st);
|
||||||
|
r0 = d.r;
|
||||||
|
v0 = d.v;
|
||||||
|
if (state == 1 || state == 2) {
|
||||||
|
state += 2;
|
||||||
|
saveMoving = moving;
|
||||||
|
stopMoving();
|
||||||
|
}
|
||||||
|
|
||||||
|
canvas.onmousemove(event);
|
||||||
|
event.preventDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
var mousewheel = function (e) {
|
||||||
|
var delta = e.wheelDelta ? e.wheelDelta : e.detail;
|
||||||
|
console.log(delta);
|
||||||
|
drawScale = drawScale + delta / 10000000000;
|
||||||
|
drawScale = Math.max(drawScale, 0.000000001);
|
||||||
|
redraw(st);
|
||||||
|
e.preventDefault();
|
||||||
|
};
|
||||||
|
|
||||||
|
canvas.addEventListener(canvas.hasOwnProperty("onmousewheel") ?
|
||||||
|
"mousewheel" : "DOMMouseScroll", mousewheel);
|
||||||
|
|
||||||
|
document.onmouseup = function(event) {
|
||||||
|
state = 0;
|
||||||
|
if (saveMoving)
|
||||||
|
startMoving();
|
||||||
|
canvas.style.cursor = 'default';
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateInfo() {
|
||||||
|
function curveType(e) {
|
||||||
|
if (e == 0) return "circle";
|
||||||
|
if (e < 1) return "ellipse";
|
||||||
|
if (e == 1) return "parabola";
|
||||||
|
return "hyperbola";
|
||||||
|
}
|
||||||
|
|
||||||
|
var a = st.p / (1 - st.e*st.e);
|
||||||
|
var T = 2 * Math.PI * a * Math.sqrt(a / st.u);
|
||||||
|
|
||||||
|
var div = document.getElementById("info");
|
||||||
|
s = "";
|
||||||
|
s += "curve = " + curveType(st.e) + "<br>";
|
||||||
|
s += "eccentricity = " + st.e.toFixed(2) + "<br>";
|
||||||
|
s += "altitude = " + Math.round(norm(st.r)/1000) + " km<br>";
|
||||||
|
s += "periapsis = " + Math.round((1-st.e)*a/1000) + " km<br>";
|
||||||
|
// is the apoapsis for parabola/hyperbola really infinity?
|
||||||
|
s += "apoapsis = " + ((st.e < 1) ? (Math.round((1+st.e)*a/1000) + " km") : "∞") + "<br>";
|
||||||
|
s += "velocity = " + Math.round(norm(st.v)/1000 * 10)/10 + " km/s<br>";
|
||||||
|
s += "eccentric anomaly = " + Math.round((((st.E / Math.PI) % 2) + 2) % 2 * 10) / 10 + "π<br>";
|
||||||
|
s += "period = " + ((st.e < 1) ? (Math.round(T / (24*60*60) * 10) / 10 + " days") : "∞") + "<br>";
|
||||||
|
div.innerHTML = s;
|
||||||
|
}
|
||||||
|
|
||||||
|
function animate() {
|
||||||
|
st.t += 24*60*60*0.1;
|
||||||
|
st.E = findE(st.t, st.e, st.u, st.p, st.E, st.ccw);
|
||||||
|
redraw(st);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopMoving() {
|
||||||
|
clearInterval(timer);
|
||||||
|
moving = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function startMoving() {
|
||||||
|
if (moving)
|
||||||
|
return;
|
||||||
|
timer = setInterval(animate, 30);
|
||||||
|
moving = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
document.onkeydown = function(event) {
|
||||||
|
var dx=0, dy=0;
|
||||||
|
if (event.keyCode == 38) { // up
|
||||||
|
dy = -1;
|
||||||
|
} else if (event.keyCode == 40) { // down
|
||||||
|
dy = 1;
|
||||||
|
} else if (event.keyCode == 37) { // left
|
||||||
|
dx = -1;
|
||||||
|
} else if (event.keyCode == 39) { // right
|
||||||
|
dx = 1;
|
||||||
|
} else if (event.keyCode == 32) {
|
||||||
|
if (moving) {
|
||||||
|
stopMoving();
|
||||||
|
} else {
|
||||||
|
startMoving();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (dx != 0 || dy != 0) {
|
||||||
|
recalculate(st, dx * 10, dy * 10);
|
||||||
|
redraw(st);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
@ -1,13 +1,13 @@
|
|||||||
import * as se3 from 'wmc-common/se3';
|
import * as se3 from '../se3';
|
||||||
import * as linalg from './linalg';
|
import * as linalg from './linalg';
|
||||||
import {Vec3} from './linalg';
|
import {Vec3} from './linalg';
|
||||||
|
|
||||||
interface Orbit {
|
interface Orbit {
|
||||||
excentricity: number,
|
excentricity: number,
|
||||||
semimajorAxis: number,
|
semimajor_axis: number,
|
||||||
inclination: number,
|
inclination: number,
|
||||||
ascendingNodeLongitude: number,
|
ascending_node_longitude: number,
|
||||||
periapsisArgument: number,
|
periapsis_argument: number,
|
||||||
t0: number,
|
t0: number,
|
||||||
|
|
||||||
lastE: number | undefined,
|
lastE: number | undefined,
|
||||||
@ -52,14 +52,6 @@ export function updateBodyPhysics(time: number, body: Body, parentBody : Body |
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isInSoi(body: Body, parentMass: number, position: number[]) : boolean {
|
|
||||||
const soi = body.orbit.semimajorAxis * Math.pow(body.mass / parentMass, 2/5);
|
|
||||||
const pos = position;
|
|
||||||
const bod = body.position;
|
|
||||||
const dr = [pos[0] - bod[0], pos[1] - bod[1], pos[2] - bod[2]];
|
|
||||||
return (dr[0]**2 + dr[1]**2 + dr[2]**2 < soi**2);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function findSoi(rootBody: Body, position: number[]) : Body {
|
export function findSoi(rootBody: Body, position: number[]) : Body {
|
||||||
const bodies = [rootBody];
|
const bodies = [rootBody];
|
||||||
let body : Body;
|
let body : Body;
|
||||||
@ -71,7 +63,11 @@ export function findSoi(rootBody: Body, position: number[]) : Body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (const child of body.children) {
|
for (const child of body.children) {
|
||||||
if (isInSoi(child, body.mass, position)) {
|
const soi = child.orbit.semimajor_axis * Math.pow(child.mass / body.mass, 2/5);
|
||||||
|
const pos = position;
|
||||||
|
const bod = child.position;
|
||||||
|
const dr = [pos[0] - bod[0], pos[1] - bod[1], pos[2] - bod[2]];
|
||||||
|
if (dr[0]**2 + dr[1]**2 + dr[2]**2 < soi**2) {
|
||||||
bodies.push(child);
|
bodies.push(child);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -132,10 +128,14 @@ export function computeOrbit(player: any, body: Body, time: number) {
|
|||||||
E = 2 * Math.atanh(Math.sqrt((e-1)/(e+1)) * Math.tan(nu/2));
|
E = 2 * Math.atanh(Math.sqrt((e-1)/(e+1)) * Math.tan(nu/2));
|
||||||
const n = Math.sqrt(-mu / (a**3));
|
const n = Math.sqrt(-mu / (a**3));
|
||||||
t0 = time - (e*Math.sinh(E) - E) / n;
|
t0 = time - (e*Math.sinh(E) - E) / n;
|
||||||
|
|
||||||
|
t0 %= 2 * Math.PI / n;
|
||||||
} else {
|
} else {
|
||||||
E = 2 * Math.atan(Math.sqrt((1-e)/(1+e)) * Math.tan(nu/2));
|
E = 2 * Math.atan(Math.sqrt((1-e)/(1+e)) * Math.tan(nu/2));
|
||||||
const n = Math.sqrt(mu / (a**3));
|
const n = Math.sqrt(mu / (a**3));
|
||||||
t0 = time - (1/n)*(E - e*Math.sin(E));
|
t0 = time - (1/n)*(E - e*Math.sin(E));
|
||||||
|
|
||||||
|
t0 %= 2 * Math.PI / n;
|
||||||
}
|
}
|
||||||
|
|
||||||
// column-major... see se3.js
|
// column-major... see se3.js
|
||||||
@ -148,10 +148,10 @@ export function computeOrbit(player: any, body: Body, time: number) {
|
|||||||
|
|
||||||
const orbit = {
|
const orbit = {
|
||||||
excentricity: e,
|
excentricity: e,
|
||||||
semimajorAxis: a,
|
semimajor_axis: a,
|
||||||
inclination: i,
|
inclination: i,
|
||||||
ascendingNodeLongitude: Om,
|
ascending_node_longitude: Om,
|
||||||
periapsisArgument: w,
|
periapsis_argument: w,
|
||||||
t0,
|
t0,
|
||||||
tf,
|
tf,
|
||||||
lastE: E,
|
lastE: E,
|
||||||
@ -171,17 +171,17 @@ export function computeOrbit(player: any, body: Body, time: number) {
|
|||||||
export function getCartesianState(orbit: Orbit, mu: number, time: number) {
|
export function getCartesianState(orbit: Orbit, mu: number, time: number) {
|
||||||
const {
|
const {
|
||||||
excentricity: e,
|
excentricity: e,
|
||||||
semimajorAxis: a,
|
semimajor_axis: a,
|
||||||
inclination: i,
|
inclination: i,
|
||||||
ascendingNodeLongitude: Om,
|
ascending_node_longitude: Om,
|
||||||
periapsisArgument: w,
|
periapsis_argument: w,
|
||||||
t0,
|
t0,
|
||||||
} = orbit;
|
} = orbit;
|
||||||
let n = Math.sqrt(mu/(a**3));
|
let n = Math.sqrt(mu/(a**3));
|
||||||
if (a < 0) {
|
if (a < 0) {
|
||||||
n = Math.sqrt(mu/-(a**3)); // mean motion
|
n = Math.sqrt(mu/-(a**3)); // mean motion
|
||||||
}
|
}
|
||||||
const M = n * (time - t0); // mean anomaly
|
const M = (n * (time - t0)) % (2 * Math.PI); // mean anomaly
|
||||||
|
|
||||||
// Newton's method
|
// Newton's method
|
||||||
var E2 = 0;
|
var E2 = 0;
|
||||||
@ -257,10 +257,10 @@ export function makeOrbitObject(gl: WebGLRenderingContext, glContext: any, orbit
|
|||||||
const buffer = gl.createBuffer();
|
const buffer = gl.createBuffer();
|
||||||
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
|
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
|
||||||
|
|
||||||
const a = orbit.semimajorAxis;
|
const a = orbit.semimajor_axis;
|
||||||
const b = a * Math.sqrt(1 - orbit.excentricity**2);
|
const b = a * Math.sqrt(1 - orbit.excentricity**2);
|
||||||
|
|
||||||
const x = - orbit.semimajorAxis * orbit.excentricity;
|
const x = - orbit.semimajor_axis * orbit.excentricity;
|
||||||
|
|
||||||
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
|
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
|
||||||
x-a, -b, 0, -1, -1,
|
x-a, -b, 0, -1, -1,
|
||||||
@ -277,7 +277,8 @@ export function makeOrbitObject(gl: WebGLRenderingContext, glContext: any, orbit
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
geometry,
|
geometry,
|
||||||
tf: se3.product(se3.translation(...position), orientation),
|
orientation,
|
||||||
|
position,
|
||||||
glContext,
|
glContext,
|
||||||
};
|
};
|
||||||
}
|
}
|
@ -4,12 +4,11 @@
|
|||||||
"main": "index.ts",
|
"main": "index.ts",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"esbuild": "^0.14.2",
|
"esbuild": "^0.14.2"
|
||||||
"wmc-common": "link:../common"
|
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"watch": "esbuild --outfile=static/app.js index.ts --bundle --sourcemap=inline --watch",
|
"watch": "esbuild --outfile=app.js index.ts --bundle --sourcemap=inline --watch",
|
||||||
"serve": "esbuild --outfile=static/app.js index.ts --bundle --sourcemap=inline --servedir=static",
|
"serve": "esbuild --outfile=app.js index.ts --bundle --sourcemap=inline --servedir=.",
|
||||||
"build": "esbuild --outfile=app.js index.ts --bundle --minify"
|
"build": "esbuild --outfile=app.js index.ts --bundle --minify"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import {Mat4} from './linalg';
|
import {Mat4} from './linalg';
|
||||||
import * as se3 from 'wmc-common/se3';
|
import * as se3 from '../se3';
|
||||||
|
|
||||||
export interface Quat {
|
export interface Quat {
|
||||||
x: number,
|
x: number,
|
||||||
@ -121,8 +121,4 @@ export function scale(q: Quat, a: number): Quat {
|
|||||||
z: a * q.z,
|
z: a * q.z,
|
||||||
w: a * q.w,
|
w: a * q.w,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function dot(q0: Quat, q1: Quat): number {
|
|
||||||
return q0.x*q1.x + q0.y*q1.y + q0.z*q1.z + q0.w*q1.w;
|
|
||||||
}
|
|
2
skycraft/server/.cargo/config.toml
Normal file
2
skycraft/server/.cargo/config.toml
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
[build]
|
||||||
|
rustflags = ["-C", "link-arg=-fuse-ld=lld"]
|
1
skycraft/server/.gitignore
vendored
Normal file
1
skycraft/server/.gitignore
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
/target
|
1864
skycraft/server/Cargo.lock
generated
Normal file
1864
skycraft/server/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
12
skycraft/server/Cargo.toml
Normal file
12
skycraft/server/Cargo.toml
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
[package]
|
||||||
|
name = "skycraft-server"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
tide = "0.14.0"
|
||||||
|
async-std = { version = "1.6.0", features = ["attributes"] }
|
||||||
|
serde = { version = "1.0", features = ["derive"] }
|
||||||
|
serde_json = "1.0"
|
14
skycraft/server/Dockerfile
Normal file
14
skycraft/server/Dockerfile
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
FROM rust:1.80.1 AS build
|
||||||
|
|
||||||
|
RUN apt-get update && apt-get install -y lld
|
||||||
|
|
||||||
|
WORKDIR /workspace
|
||||||
|
|
||||||
|
COPY src /workspace/src
|
||||||
|
COPY Cargo.toml /workspace/
|
||||||
|
COPY Cargo.lock /workspace/
|
||||||
|
|
||||||
|
RUN cargo build
|
||||||
|
|
||||||
|
|
||||||
|
FROM build AS dev
|
19
skycraft/server/Makefile
Normal file
19
skycraft/server/Makefile
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
dev-image:
|
||||||
|
docker build -t cargo-server-dev --target dev .
|
||||||
|
|
||||||
|
.PHONY: dev
|
||||||
|
dev: dev-image ## Start a dev container
|
||||||
|
docker run -it --rm \
|
||||||
|
-v $(CURDIR)/src:/workspace/src \
|
||||||
|
-v $(CURDIR)/Cargo.toml:/workspace/Cargo.toml \
|
||||||
|
-v $(CURDIR)/Cargo.lock:/workspace/Cargo.lock \
|
||||||
|
-p 127.0.0.1:8080:8080 \
|
||||||
|
cargo-server-dev \
|
||||||
|
bash
|
||||||
|
|
||||||
|
|
||||||
|
.PHONY: help
|
||||||
|
help: ## Show this help
|
||||||
|
@echo Noteworthy targets:
|
||||||
|
@egrep '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-20s\033[0m %s\n", $$1, $$2}'
|
||||||
|
.DEFAULT_GOAL := help
|
262
skycraft/server/src/main.rs
Normal file
262
skycraft/server/src/main.rs
Normal file
@ -0,0 +1,262 @@
|
|||||||
|
use tide::Request;
|
||||||
|
use tide::Response;
|
||||||
|
use tide::prelude::*;
|
||||||
|
//use serde_json::json;
|
||||||
|
use std::f64::consts::PI;
|
||||||
|
|
||||||
|
#[derive(Default, Serialize)]
|
||||||
|
struct SystemBody {
|
||||||
|
name: String,
|
||||||
|
mass: f32,
|
||||||
|
seed: u32,
|
||||||
|
spin: [f32; 3],
|
||||||
|
// geometry: ,
|
||||||
|
glow_color: [f32; 3],
|
||||||
|
orbit: KeplerOrbit,
|
||||||
|
children: Vec<SystemBody>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default, Serialize)]
|
||||||
|
struct KeplerOrbit {
|
||||||
|
excentricity: f32,
|
||||||
|
semimajor_axis: f32,
|
||||||
|
inclination: f32,
|
||||||
|
ascending_node_longitude: f32,
|
||||||
|
periapsis_argument: f32,
|
||||||
|
t0: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
const CHUNKSIZE: usize = 32;
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
struct Chunk {
|
||||||
|
position: [f32; 3],
|
||||||
|
layout: [i32; 3],
|
||||||
|
#[serde(serialize_with = "<[_]>::serialize")]
|
||||||
|
blocks: [u32; CHUNKSIZE.pow(3)],
|
||||||
|
seed: u32,
|
||||||
|
underground: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for Chunk {
|
||||||
|
fn eq(&self, other: &Chunk) -> bool {
|
||||||
|
self.seed == other.seed && self.position == other.position
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_std::main]
|
||||||
|
async fn main() -> tide::Result<()> {
|
||||||
|
let mut app = tide::new();
|
||||||
|
app.at("/api/system/:seed").get(get_system);
|
||||||
|
app.at("/api/body/:seed").get(get_body);
|
||||||
|
app.listen("0.0.0.0:8080").await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_sun_chunk(seed: u32, pos: [i32; 3]) -> Chunk {
|
||||||
|
let cs = CHUNKSIZE as i32;
|
||||||
|
Chunk {
|
||||||
|
position: pos.map(|x| ((x * cs - cs / 2) as f32)),
|
||||||
|
layout: pos,
|
||||||
|
blocks: [8; CHUNKSIZE.pow(3)],
|
||||||
|
seed: seed,
|
||||||
|
underground: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_dirt_chunk(seed: u32, pos: [i32; 3]) -> Chunk {
|
||||||
|
let cs = CHUNKSIZE as i32;
|
||||||
|
Chunk {
|
||||||
|
position: pos.map(|x| ((x * cs - cs / 2) as f32)),
|
||||||
|
layout: pos,
|
||||||
|
blocks: [2; CHUNKSIZE.pow(3)],
|
||||||
|
seed: seed,
|
||||||
|
underground: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_chunk(seed: u32, pos: [i32; 3]) -> Option<Chunk>{
|
||||||
|
match seed {
|
||||||
|
0 => match pos {
|
||||||
|
[0, 0, 0] => Some(get_sun_chunk(seed, pos)),
|
||||||
|
_ => None,
|
||||||
|
},
|
||||||
|
_ => match pos {
|
||||||
|
[0, 0, 0] => Some(get_dirt_chunk(seed, pos)),
|
||||||
|
_ => None,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_body_chunks(seed: u32) -> Vec<Chunk> {
|
||||||
|
let mut chunks = vec![];
|
||||||
|
let mut tocheck = vec![[0, 0, 0]];
|
||||||
|
|
||||||
|
while tocheck.len() > 0 {
|
||||||
|
let pos = tocheck.pop().unwrap();
|
||||||
|
let thischunk = get_chunk(seed, pos);
|
||||||
|
if thischunk.is_none() || chunks.contains(thischunk.as_ref().unwrap()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
chunks.push(thischunk.unwrap());
|
||||||
|
println!("Adding chunk for seed {seed} at position {:?}", pos);
|
||||||
|
|
||||||
|
let [ci, cj, ck] = pos;
|
||||||
|
tocheck.push([ci - 1, cj, ck]);
|
||||||
|
tocheck.push([ci + 1, cj, ck]);
|
||||||
|
tocheck.push([ci, cj - 1, ck]);
|
||||||
|
tocheck.push([ci, cj + 1, ck]);
|
||||||
|
tocheck.push([ci, cj, ck - 1]);
|
||||||
|
tocheck.push([ci, cj, ck + 1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
chunks
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get_body(req: Request<()>) -> tide::Result {
|
||||||
|
let seed: u32 = req.param("seed")?.parse()?;
|
||||||
|
let chunks = get_body_chunks(seed);
|
||||||
|
let response = Response::builder(200)
|
||||||
|
.body(serde_json::to_string(&chunks)?)
|
||||||
|
.content_type("application/json")
|
||||||
|
.header("access-control-allow-origin", "*")
|
||||||
|
.build();
|
||||||
|
Ok(response)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO
|
||||||
|
// ----
|
||||||
|
// [ ] serve chunks
|
||||||
|
// [ ] universe simulation?
|
||||||
|
// [ ] websocket with client updates
|
||||||
|
|
||||||
|
async fn get_system(_req: Request<()>) -> tide::Result {
|
||||||
|
// let seed: i32 = req.param("seed")?.parse()?;
|
||||||
|
let response = Response::builder(200)
|
||||||
|
.content_type("application/json")
|
||||||
|
.header("access-control-allow-origin", "*")
|
||||||
|
.body(serde_json::to_string(&SystemBody
|
||||||
|
{
|
||||||
|
name: "Tat".to_string(),
|
||||||
|
seed: 0,
|
||||||
|
|
||||||
|
mass: 1000.0,
|
||||||
|
spin: [0.0, 0.0, 0.2],
|
||||||
|
|
||||||
|
// geometry: getBodyGeometry(0),
|
||||||
|
glow_color: [0.5, 0.5, 0.46],
|
||||||
|
|
||||||
|
children: Vec::from([
|
||||||
|
SystemBody {
|
||||||
|
name: "Quicksilver".to_string(),
|
||||||
|
seed: 1336,
|
||||||
|
|
||||||
|
mass: 0.1,
|
||||||
|
spin: [0.0, 0.0, 0.05],
|
||||||
|
|
||||||
|
// geometry: makeCube([0, 4]),
|
||||||
|
|
||||||
|
orbit: KeplerOrbit {
|
||||||
|
excentricity: 0.0,
|
||||||
|
semimajor_axis: 200.0,
|
||||||
|
inclination: 0.8,
|
||||||
|
ascending_node_longitude: 0.0,
|
||||||
|
periapsis_argument: 0.0,
|
||||||
|
t0: 0.0,
|
||||||
|
},
|
||||||
|
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
SystemBody {
|
||||||
|
name: "Satourne".to_string(),
|
||||||
|
seed: 1338,
|
||||||
|
|
||||||
|
mass: 0.1,
|
||||||
|
spin: [0.0, 0.5, 0.0],
|
||||||
|
|
||||||
|
// geometry: makeCube([0, 5]),
|
||||||
|
|
||||||
|
orbit: KeplerOrbit {
|
||||||
|
excentricity: 0.0,
|
||||||
|
semimajor_axis: 900.0,
|
||||||
|
inclination: 0.0,
|
||||||
|
ascending_node_longitude: 0.0,
|
||||||
|
periapsis_argument: 0.0,
|
||||||
|
t0: 0.0,
|
||||||
|
},
|
||||||
|
|
||||||
|
children: Vec::from([
|
||||||
|
SystemBody {
|
||||||
|
name: "Kyoujin".to_string(),
|
||||||
|
seed: 13381,
|
||||||
|
|
||||||
|
mass: 0.01,
|
||||||
|
spin: [0.0, 0.0, 0.05],
|
||||||
|
|
||||||
|
// geometry: makeCube([0, 6]),
|
||||||
|
|
||||||
|
orbit: KeplerOrbit {
|
||||||
|
excentricity: 0.0,
|
||||||
|
semimajor_axis: 20.0,
|
||||||
|
inclination: (PI / 2.0) as f32,
|
||||||
|
ascending_node_longitude: 0.0,
|
||||||
|
periapsis_argument: 0.0,
|
||||||
|
t0: 0.0,
|
||||||
|
},
|
||||||
|
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
SystemBody {
|
||||||
|
name: "Tataooine".to_string(),
|
||||||
|
seed: 1337,
|
||||||
|
|
||||||
|
mass: 50.0,
|
||||||
|
spin: [0.0, 0.0, 0.05],
|
||||||
|
|
||||||
|
// geometry: getBodyGeometry(1337),
|
||||||
|
|
||||||
|
orbit: KeplerOrbit {
|
||||||
|
excentricity: 0.3,
|
||||||
|
semimajor_axis: 500.0,
|
||||||
|
inclination: 0.0,
|
||||||
|
ascending_node_longitude: 0.0,
|
||||||
|
periapsis_argument: 0.0,
|
||||||
|
t0: 0.0,
|
||||||
|
},
|
||||||
|
|
||||||
|
children: Vec::from([
|
||||||
|
SystemBody {
|
||||||
|
name: "Mun".to_string(),
|
||||||
|
seed: 13371,
|
||||||
|
|
||||||
|
mass: 0.01,
|
||||||
|
spin: [0.0, 0.0, 0.05],
|
||||||
|
|
||||||
|
// geometry: makeCube([0, 7]),
|
||||||
|
|
||||||
|
orbit: KeplerOrbit {
|
||||||
|
excentricity: 0.0,
|
||||||
|
semimajor_axis: 50.0,
|
||||||
|
inclination: (PI / 2.0) as f32,
|
||||||
|
ascending_node_longitude: 0.0,
|
||||||
|
periapsis_argument: 0.0,
|
||||||
|
t0: 0.0,
|
||||||
|
},
|
||||||
|
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
|
||||||
|
..Default::default()
|
||||||
|
})?)
|
||||||
|
.build();
|
||||||
|
Ok(response)
|
||||||
|
}
|
Binary file not shown.
Before Width: | Height: | Size: 40 KiB |
1
skycraft/texture.png
Symbolic link
1
skycraft/texture.png
Symbolic link
@ -0,0 +1 @@
|
|||||||
|
../texture.png
|
@ -44,7 +44,7 @@ esbuild-linux-32@0.14.54:
|
|||||||
|
|
||||||
esbuild-linux-64@0.14.54:
|
esbuild-linux-64@0.14.54:
|
||||||
version "0.14.54"
|
version "0.14.54"
|
||||||
resolved "https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.14.54.tgz"
|
resolved "https://registry.yarnpkg.com/esbuild-linux-64/-/esbuild-linux-64-0.14.54.tgz#de5fdba1c95666cf72369f52b40b03be71226652"
|
||||||
integrity sha512-EgjAgH5HwTbtNsTqQOXWApBaPVdDn7XcK+/PtJwZLT1UmpLoznPd8c5CxqsH2dQK3j05YsB3L17T8vE7cp4cCg==
|
integrity sha512-EgjAgH5HwTbtNsTqQOXWApBaPVdDn7XcK+/PtJwZLT1UmpLoznPd8c5CxqsH2dQK3j05YsB3L17T8vE7cp4cCg==
|
||||||
|
|
||||||
esbuild-linux-arm64@0.14.54:
|
esbuild-linux-arm64@0.14.54:
|
||||||
@ -109,7 +109,7 @@ esbuild-windows-arm64@0.14.54:
|
|||||||
|
|
||||||
esbuild@^0.14.2:
|
esbuild@^0.14.2:
|
||||||
version "0.14.54"
|
version "0.14.54"
|
||||||
resolved "https://registry.npmjs.org/esbuild/-/esbuild-0.14.54.tgz"
|
resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.14.54.tgz#8b44dcf2b0f1a66fc22459943dccf477535e9aa2"
|
||||||
integrity sha512-Cy9llcy8DvET5uznocPyqL3BFRrFXSVqbgpMJ9Wz8oVjZlh/zUSNbPRbov0VX7VxN2JH1Oa0uNxZ7eLRb62pJA==
|
integrity sha512-Cy9llcy8DvET5uznocPyqL3BFRrFXSVqbgpMJ9Wz8oVjZlh/zUSNbPRbov0VX7VxN2JH1Oa0uNxZ7eLRb62pJA==
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
"@esbuild/linux-loong64" "0.14.54"
|
"@esbuild/linux-loong64" "0.14.54"
|
||||||
@ -133,7 +133,3 @@ esbuild@^0.14.2:
|
|||||||
esbuild-windows-32 "0.14.54"
|
esbuild-windows-32 "0.14.54"
|
||||||
esbuild-windows-64 "0.14.54"
|
esbuild-windows-64 "0.14.54"
|
||||||
esbuild-windows-arm64 "0.14.54"
|
esbuild-windows-arm64 "0.14.54"
|
||||||
|
|
||||||
"wmc-common@link:../common":
|
|
||||||
version "0.0.0"
|
|
||||||
uid ""
|
|
||||||
|
Loading…
Reference in New Issue
Block a user