[WIP] skycraft server

This commit is contained in:
Paul Mathieu 2024-08-15 14:54:33 +02:00
parent 9bb162e7d5
commit 9d503d53cc
11 changed files with 2724 additions and 26 deletions

View File

@ -135,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]];
@ -304,10 +306,19 @@ function getBodyChunks(seed: number) {
return chunks; return chunks;
} }
export function getBodyGeometry(seed: number) { export function getBodyGeometry(chunks) {
const faces = getBodyChunks(seed) function lookup(seed: number, chunkX: number, chunkY: number, chunkZ: number) {
for (const chunk of chunks) {
const [cx, cy, cz] = chunk.layout;
if (chunkX == cx && chunkY == cy && chunkZ == cz) {
return chunk;
}
}
}
const faces = chunks
.filter(chunk => !chunk.underground) .filter(chunk => !chunk.underground)
.map(chunk => [...makeChunkFaces(chunk)]); .map(chunk => [...makeChunkFaces(chunk, memoize(lookup))]);
return faces.reduce((a, b) => a.concat(b)); return faces.reduce((a, b) => a.concat(b));
} }

15
skycraft/client.ts Normal file
View 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();
}

View File

@ -172,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);
@ -304,11 +304,20 @@ 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 viewMatrix = se3.inverse([ let camtf;
player.tf, // player position & orientation if (camera.overhead) {
camera.tf, // camera orientation relative to player camtf = [
se3.translation(0, 1, 4), // step back from the player se3.translation(0, 500, 0),
].reduce(se3.product)); se3.rotx(-Math.PI / 2),
].reduce(se3.product);
} else {
camtf = [
player.tf, // player position & orientation
camera.tf, // camera orientation relative to player
se3.translation(0, 1, 4), // step back from the player
].reduce(se3.product)
}
const viewMatrix = se3.inverse(camtf);
let lastGlContext; let lastGlContext;
for (const {position, orientation, geometry, glContext, glowColor} of objects) { for (const {position, orientation, geometry, glContext, glowColor} of objects) {

View File

@ -1,5 +1,6 @@
import { makeFace } from '../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 '../se3'; import * as se3 from '../se3';
@ -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 {
@ -161,6 +179,10 @@ function initUiListeners(canvas: HTMLCanvasElement, context) {
context.landing = True; context.landing = True;
} }
return false; return false;
case 'KeyO':
context.camera.overhead ^= 1;
return false;
case 'Space': case 'Space':
if (!context.flying) { if (!context.flying) {
if (context.jumpAmount > 0) { if (context.jumpAmount > 0) {
@ -313,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);
@ -390,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,
}; };

495
skycraft/orbit.html Normal file
View 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") : "&infin;") + "<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 + "&pi;<br>";
s += "period = " + ((st.e < 1) ? (Math.round(T / (24*60*60) * 10) / 10 + " days") : "&infin;") + "<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>

View File

@ -4,10 +4,10 @@ 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,
@ -63,7 +63,7 @@ export function findSoi(rootBody: Body, position: number[]) : Body {
} }
for (const child of body.children) { for (const child of body.children) {
const soi = child.orbit.semimajorAxis * Math.pow(child.mass / body.mass, 2/5); const soi = child.orbit.semimajor_axis * Math.pow(child.mass / body.mass, 2/5);
const pos = position; const pos = position;
const bod = child.position; const bod = child.position;
const dr = [pos[0] - bod[0], pos[1] - bod[1], pos[2] - bod[2]]; const dr = [pos[0] - bod[0], pos[1] - bod[1], pos[2] - bod[2]];
@ -128,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
@ -144,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,
@ -167,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;
@ -253,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,

View File

@ -0,0 +1,2 @@
[build]
rustflags = ["-C", "link-arg=-fuse-ld=lld"]

1
skycraft/server/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

1864
skycraft/server/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View 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"

262
skycraft/server/src/main.rs Normal file
View 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("127.0.0.1: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)
}