Commit d6ce1354 authored by Roque's avatar Roque

[WEB-WORKER] [WIP] Drone simulator

parent 46586276
/// <reference path="./GameManager.ts" />
var DroneAPI = /** @class */ (function () {
//*************************************************** CONSTRUCTOR **************************************************
function DroneAPI(gameManager, team) {
this._gameManager = gameManager;
this._team = team;
}
Object.defineProperty(DroneAPI.prototype, "team", {
//*************************************************** ACCESSOR *****************************************************
get: function () {
if (this._team == "L")
return this._gameManager.teamLeft;
else if (this._team == "R")
return this._gameManager.teamRight;
},
enumerable: true,
configurable: true
});
//*************************************************** FUNCTIONS ****************************************************
//#region ------------------ Internal
DroneAPI.prototype.internal_sendMsg = function (msg, to) {
var _this = this;
_this._gameManager.delay(function () {
if (to < 0) {
// Send to all drones
_this.team.forEach(function (drone) {
if (drone.infosMesh) {
try {
drone.onGetMsg(msg);
}
catch (error) {
console.warn('Drone crashed on sendMsg due to error:', error);
drone._internal_crash();
}
}
});
}
else {
// Send to specific drone
if (drone.infosMesh) {
try {
_this.team[to].onGetMsg(msg);
}
catch (error) {
console.warn('Drone crashed on sendMsg due to error:', error);
_this.team[to]._internal_crash();
}
}
}
}, GAMEPARAMETERS.latency.communication);
};
//#endregion
//#region ------------------ Accessible from AI
DroneAPI.prototype.log = function (msg) {
console.log("API say : " + msg);
};
DroneAPI.prototype.getGameParameter = function (name) {
if (["gameTime", "mapSize", "teamSize", "derive", "meteo", "initialHumanAreaPosition"].includes(name))
return this._gameManager.gameParameter[name];
};
DroneAPI.prototype._isWithinDroneView = function (drone_position, element_position) {
// Check if element is under the drone cone-view
var angle = GAMEPARAMETERS.drone.viewAngle ? GAMEPARAMETERS.drone.viewAngle : 60,
radius = drone_position.z * Math.tan(angle/2 * Math.PI/180),
distance = (drone_position.x - element_position.x) * (drone_position.x - element_position.x) +
(drone_position.y - element_position.y) * (drone_position.y - element_position.y);
if (distance < (radius*radius))
return true;
return false;
};
DroneAPI.prototype._getProbabilityOfDetection = function (drone_position) {
var h = drone_position.z,
km = GAMEPARAMETERS.meteo;
prob = 20 * (1 + (110-h)/25) * km;
return prob;
};
DroneAPI.prototype.isHumanPositionSpottedCalculation = function (drone) {
var context = this,
result = false,
drone_position = drone.infosMesh.position;
//swap axes back
drone_position = {
x: drone_position.x,
y: drone_position.z,
z: drone_position.y
};
context._gameManager.teamRight.forEach(function (human) {
if (human.infosMesh && context._isWithinDroneView(drone_position, human.position)) {
var prob = context._getProbabilityOfDetection(drone_position),
random = Math.floor(Math.random()*101);
if (random < prob)
result = true;
}
});
return result;
};
DroneAPI.prototype.isHumanPositionSpotted = function (drone) {
var context = this,
human_detected;
if (drone.__is_calculating_human_position !== true) {
drone.__is_calculating_human_position = true;
//human detection is done with the info captured by the drone
//at the moment this method is called
human_detected = context.isHumanPositionSpottedCalculation(drone);
context._gameManager.delay(function () {
drone.__is_calculating_human_position = false;
try {
drone.onCapture(human_detected);
} catch (error) {
console.warn('Drone crashed on capture due to error:', error);
drone._internal_crash();
}
}, 2000);
}
};
DroneAPI.prototype.getDirectionFromCoordinates = function (x, y, z, drone_position) {
if(isNaN(x) || isNaN(y) || isNaN(z)){
throw new Error('Target coordinates must be numbers');
}
x -= drone_position.x;
y -= drone_position.y;
z -= drone_position.z;
if (this._team == "R")
y = -y;
return {
x: x,
y: y,
z: z
};
};
DroneAPI.prototype.setAltitude = function (altitude) {
//TODO
return;
};
DroneAPI.prototype.getInitialAltitude = function () {
return 0;
};
DroneAPI.prototype.getAltitudeAbs = function () {
return 0;
};
DroneAPI.prototype.getMinHeight = function () {
return 9;
};
DroneAPI.prototype.getMaxHeight = function () {
return 220;
};
DroneAPI.prototype.getDroneAI = function () {
return null;
};
DroneAPI.prototype.getMaxSpeed = function () {
return GAMEPARAMETERS.drone.maxSpeed;
};
return DroneAPI;
}());
/// <reference path="./GameManager.ts" />
var DroneLogAPI = /** @class */ (function () {
//*************************************************** CONSTRUCTOR **************************************************
function DroneLogAPI(gameManager, team, flight_parameters) {
this._gameManager = gameManager;
this._team = team;
this._flight_parameters = flight_parameters;
}
Object.defineProperty(DroneLogAPI.prototype, "team", {
//*************************************************** ACCESSOR *****************************************************
get: function () {
if (this._team == "L")
return this._gameManager.teamLeft;
else if (this._team == "R")
return this._gameManager.teamRight;
},
enumerable: true,
configurable: true
});
//*************************************************** FUNCTIONS ****************************************************
//#region ------------------ Internal
DroneLogAPI.prototype.internal_sendMsg = function (msg, to) {
var _this = this;
_this._gameManager.delay(function () {
if (to < 0) {
// Send to all drones
_this.team.forEach(function (drone) {
if (drone.infosMesh) {
try {
drone.onGetMsg(msg);
}
catch (error) {
console.warn('Drone crashed on sendMsg due to error:', error);
drone._internal_crash();
}
}
});
}
else {
// Send to specific drone
if (drone.infosMesh) {
try {
_this.team[to].onGetMsg(msg);
}
catch (error) {
console.warn('Drone crashed on sendMsg due to error:', error);
_this.team[to]._internal_crash();
}
}
}
}, GAMEPARAMETERS.latency.communication);
};
//#endregion
//#region ------------------ Accessible from AI
DroneLogAPI.prototype.log = function (msg) {
console.log("API say : " + msg);
};
DroneLogAPI.prototype.getGameParameter = function (name) {
if (["gameTime", "mapSize", "teamSize", "derive", "meteo", "initialHumanAreaPosition"].includes(name))
return this._gameManager.gameParameter[name];
};
DroneLogAPI.prototype._isWithinDroneView = function (drone_position, element_position) {
// Check if element is under the drone cone-view
var angle = GAMEPARAMETERS.drone.viewAngle ? GAMEPARAMETERS.drone.viewAngle : 60,
radius = drone_position.z * Math.tan(angle/2 * Math.PI/180),
distance = (drone_position.x - element_position.x) * (drone_position.x - element_position.x) +
(drone_position.y - element_position.y) * (drone_position.y - element_position.y);
if (distance < (radius*radius))
return true;
return false;
};
DroneLogAPI.prototype._getProbabilityOfDetection = function (drone_position) {
var h = drone_position.z,
km = GAMEPARAMETERS.meteo;
prob = 20 * (1 + (110-h)/25) * km;
return prob;
};
DroneLogAPI.prototype.isHumanPositionSpottedCalculation = function (drone) {
var context = this,
result = false,
drone_position = drone.infosMesh.position;
//swap axes back
drone_position = {
x: drone_position.x,
y: drone_position.z,
z: drone_position.y
};
context._gameManager.teamRight.forEach(function (human) {
if (human.infosMesh && context._isWithinDroneView(drone_position, human.position)) {
var prob = context._getProbabilityOfDetection(drone_position),
random = Math.floor(Math.random()*101);
if (random < prob)
result = true;
}
});
return result;
};
DroneLogAPI.prototype.isHumanPositionSpotted = function (drone) {
var context = this,
human_detected;
if (drone.__is_calculating_human_position !== true) {
drone.__is_calculating_human_position = true;
//human detection is done with the info captured by the drone
//at the moment this method is called
human_detected = context.isHumanPositionSpottedCalculation(drone);
context._gameManager.delay(function () {
drone.__is_calculating_human_position = false;
try {
drone.onCapture(human_detected);
} catch (error) {
console.warn('Drone crashed on capture due to error:', error);
drone._internal_crash();
}
}, 2000);
}
};
DroneLogAPI.prototype.processCoordinates = function (x, y, z) {
if(isNaN(x) || isNaN(y) || isNaN(z)){
throw new Error('Target coordinates must be numbers');
}
return {
x: x,
y: y,
z: z
};
};
DroneLogAPI.prototype.getDroneAI = function () {
return 'function distance(p1, p2) {' +
'var a = p1[0] - p2[0],' +
'b = p1[1] - p2[1];' +
'return Math.sqrt(a * a + b * b);' +
'}' +
'me.onStart = function() {' +
'console.log("DRONE LOG START!");' +
'if (!me.getFlightParameters())' +
'throw "DroneLog API must implement getFlightParameters";' +
'me.flightParameters = me.getFlightParameters();' +
'me.checkpoint_list = me.flightParameters.converted_log_point_list;' +
'me.startTime = new Date();' +
'me.initTimestamp = me.flightParameters.converted_log_point_list[0][3];' +
'me.setTargetCoordinates(me.checkpoint_list[0][0], me.checkpoint_list[0][1], me.checkpoint_list[0][2]);' +
'me.last_checkpoint_reached = -1;' +
'me.setAcceleration(10);' +
'};' +
'me.onUpdate = function () {' +
'var next_checkpoint = me.checkpoint_list[me.last_checkpoint_reached+1];' +
'if (distance([me.position.x, me.position.y], next_checkpoint) < 12) {' +
'var log_elapsed = next_checkpoint[3] - me.initTimestamp,' +
'time_elapsed = new Date() - me.startTime;' +
'if (time_elapsed < log_elapsed) {' +
'me.setDirection(0, 0, 0);' +
'return;' +
'}' +
'if (me.last_checkpoint_reached + 1 === me.checkpoint_list.length - 1) {' +
'me.setTargetCoordinates(me.position.x, me.position.y, me.position.z);' +
'return;' +
'}' +
'me.last_checkpoint_reached += 1;' +
'next_checkpoint = me.checkpoint_list[me.last_checkpoint_reached+1];' +
'me.setTargetCoordinates(next_checkpoint[0], next_checkpoint[1], next_checkpoint[2]);' +
'} else {' +
'me.setTargetCoordinates(next_checkpoint[0], next_checkpoint[1], next_checkpoint[2]);' +
'}' +
'};';
};
DroneLogAPI.prototype.setAltitude = function (altitude) {
return altitude;
};
DroneLogAPI.prototype.getMaxSpeed = function () {
return 3000;
};
DroneLogAPI.prototype.getInitialAltitude = function () {
return 0;
};
DroneLogAPI.prototype.getAltitudeAbs = function () {
return 0;
};
DroneLogAPI.prototype.getMinHeight = function () {
return 0;
};
DroneLogAPI.prototype.getMaxHeight = function () {
return 220;
};
DroneLogAPI.prototype.getFlightParameters = function () {
return this._flight_parameters;
};
return DroneLogAPI;
}());
/*global window, rJS, jIO, RSVP, domsugar, console,
requestAnimationFrame, cancelAnimationFrame,
Worker,
DroneGameManager*/
/*global GameManager, console*/
/*jslint nomen: true, indent: 2, maxerr: 3, maxlen: 80 */
var runGame;
var runGame, updateGame, eventGame, game_manager_instance;
// game.js
(function () {
"use strict";
console.log('game logic');
runGame = function (canvas, script, game_parameters_json, log) {
runGame = function (canvas) {
function processLog(game_parameters_json, log) {
var MAP_SIZE = 1000,
MIN_HEIGHT = 15,
MIN_X,
MAX_X,
MIN_Y,
MAX_Y,
SPEED_FACTOR = 0.75,
log_point_list = [],
converted_log_point_list = [];
function longitudToX(lon) {
return (MAP_SIZE / 360.0) * (180 + lon);
}
function latitudeToY(lat) {
return (MAP_SIZE / 180.0) * (90 - lat);
}
function normalizeToMap(x, y) {
var n_x = (x - MIN_X) / (MAX_X - MIN_X),
n_y = (y - MIN_Y) / (MAX_Y - MIN_Y);
return [n_x * 1000 - MAP_SIZE / 2, n_y * 1000 - MAP_SIZE / 2];
}
function latLonDistance(c1, c2) {
var R = 6371e3,
q1 = c1[0] * Math.PI / 180,
q2 = c2[0] * Math.PI / 180,
dq = (c2[0] - c1[0]) * Math.PI / 180,
dl = (c2[1] - c1[1]) * Math.PI / 180,
a = Math.sin(dq / 2) * Math.sin(dq / 2) +
Math.cos(q1) * Math.cos(q2) *
Math.sin(dl / 2) * Math.sin(dl / 2),
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
function distance(p1, p2) {
return Math.sqrt(Math.pow(p1[0] - p2[0], 2) +
Math.pow(p1[1] - p2[1], 2));
}
var path_point_list = [], max_width, max_height,
line_list = log.split('\n'), log_entry_list = [],
i, start_time, end_time, log_entry, splitted_log_entry,
lat, lon, x, y, position, min_lon = 99999, min_lat = 99999,
max_lon = 0, max_lat = 0, previous, start_position, dist = 0,
path_point, average_speed = 0, flight_time, log_interval_time,
previous_log_time, height, timestamp, destination_lon,
destination_lat, log_header_found, time_offset = 1,
flight_dist = 0, start_AMSL = 0;
for (i = 0; i < line_list.length; i += 1) {
if (!log_header_found && !line_list[i].includes("timestamp;")) {
continue;
} else {
log_header_found = true;
}
if (line_list[i].indexOf("AMSL") >= 0 ||
!line_list[i].includes(";")) {
continue;
}
log_entry = line_list[i].trim();
if (log_entry) {
log_entry_list.push(log_entry);
splitted_log_entry = log_entry.split(";");
lat = parseFloat(splitted_log_entry[1]);
lon = parseFloat(splitted_log_entry[2]);
//get min and max lat and lon
if (lon < min_lon) {
min_lon = lon;
}
if (lat < min_lat) {
min_lat = lat;
}
if (lon > max_lon) {
max_lon = lon;
}
if (lat > max_lat) {
max_lat = lat;
}
}
}
//get map size from max distance
max_width = latLonDistance([min_lat, min_lon], [min_lat, max_lon]);
max_height = latLonDistance([min_lat, min_lon], [max_lat, min_lon]);
MAP_SIZE = Math.ceil(Math.max(max_width, max_height)) * 0.6;
MIN_X = longitudToX(min_lon);
MAX_X = longitudToX(max_lon);
MIN_Y = latitudeToY(min_lat);
MAX_Y = latitudeToY(max_lat);
if (log_entry_list[0] && log_entry_list[1]) {
var entry_1 = log_entry_list[0].split(";"),
entry_2 = log_entry_list[1].split(";"),
interval = parseInt(entry_2[0], 10) - parseInt(entry_1[0], 10);
//if interval > 1' then timestamp is in microseconds
if (Math.floor(interval / 1000) > 60) {
time_offset = 1000;
}
}
for (i = 0; i < log_entry_list.length; i += 1) {
splitted_log_entry = log_entry_list[i].split(";");
timestamp = parseInt(splitted_log_entry[0], 10);
if (i === 0) {
log_interval_time = 0;
start_time = timestamp;
} else {
log_interval_time += (parseInt(splitted_log_entry[0], 10) -
previous_log_time);
}
previous_log_time = parseInt(splitted_log_entry[0], 10);
average_speed += parseFloat(splitted_log_entry[8]);
lat = parseFloat(splitted_log_entry[1]);
lon = parseFloat(splitted_log_entry[2]);
if (i === log_entry_list.length - 1) {
destination_lon = lon;
destination_lat = lat;
end_time = timestamp;
}
height = parseFloat(splitted_log_entry[4]);
if (height < MIN_HEIGHT) {
height = MIN_HEIGHT;
} else {
height = height;
}
x = longitudToX(lon);
y = latitudeToY(lat);
position = normalizeToMap(x, y);
if (!previous) {
start_AMSL = parseFloat(splitted_log_entry[3]);
start_position = position;
start_position.push(height);
previous = position;
}
dist = distance(previous, position);
flight_dist += dist;
if (dist > 15) {
previous = position;
path_point = {
"type": "box",
"position": {
"x": position[0],
"y": position[1],
"z": height
},
"scale": {
"x": 3.5,
"y": 3.5,
"z": 3.5
},
"rotation": {
"x": 0,
"y": 0,
"z": 0
},
"color": {
"r": 0,
"g": 255,
"b": 0
},
"timestamp": timestamp
};
path_point_list.push(path_point);
}
converted_log_point_list.push([position[0],
position[1],
height, timestamp / time_offset]);
log_point_list.push([parseFloat(splitted_log_entry[1]),
parseFloat(splitted_log_entry[2]),
height, timestamp]);
}
average_speed = average_speed / log_entry_list.length;
log_interval_time = log_interval_time / log_entry_list.length / time_offset;
flight_time = (end_time - start_time) / 1000 / time_offset;
game_parameters_json.compareFlights = {
log: true,
draw: true,
map_width: MAP_SIZE,
map_height: MAP_SIZE,
MAP_SIZE: MAP_SIZE,
MIN_X: MIN_X,
MAX_X: MAX_X,
MIN_Y: MIN_Y,
MAX_Y: MAX_Y,
start_AMSL: start_AMSL,
flight_time: flight_time,
average_speed: average_speed,
log_interval_time: log_interval_time,
path: path_point_list,
full_log: log_point_list,
converted_log_point_list: converted_log_point_list
};
game_parameters_json.drone.maxSpeed = (flight_dist / flight_time) * SPEED_FACTOR;
game_parameters_json.obstacles = path_point_list;
game_parameters_json.randomSpawn.leftTeam.position.x = start_position[0];
game_parameters_json.randomSpawn.leftTeam.position.y = start_position[1];
game_parameters_json.randomSpawn.leftTeam.position.z = start_position[2];
game_parameters_json.gameTime = flight_time;
//give map some margin from the flight
game_parameters_json.mapSize.width = MAP_SIZE * 1.10;
game_parameters_json.mapSize.depth = MAP_SIZE * 1.10;
//flight destination
var destination_x = longitudToX(destination_lon),
destination_y = latitudeToY(destination_lat),
destination = normalizeToMap(destination_x, destination_y);
game_parameters_json.randomSpawn.rightTeam.position.x = destination[0];
game_parameters_json.randomSpawn.rightTeam.position.y = destination[1];
return game_parameters_json;
}
console.log('runGame', canvas);
// Create the Babylon engine
var engine = new BABYLON.Engine(canvas, true);
engine.enableOfflineSupport = false;
// Create the base scene
var scene = new BABYLON.Scene(engine);
scene.clearColor = new BABYLON.Color4(88/255,171/255,217/255,255/255);
// this._scene.debugLayer.show();
// Collisions
scene.collisionsEnabled = true;
// Camera
//cap camera distance to 1km
var camera = new BABYLON.ArcRotateCamera("camera", 3, 1.25, 800, new BABYLON.Vector3(1, 0, 1), scene);
camera.wheelPrecision = 10;
//camera.attachControl(scene.getEngine().getRenderingCanvas());
camera.maxz = 40000
scene.render();
game_parameters_json = processLog(game_parameters_json, log);
if (!game_manager_instance) {
game_manager_instance = new GameManager(canvas, script,
game_parameters_json, 5);
}
return game_manager_instance.run();
};
/*
// Resize canvas on window resize
window.addEventListener('resize', function () {
engine.resize();
});
*/
updateGame = function () {
return game_manager_instance.update();
};
eventGame = function (event) {
return game_manager_instance.event(event);
};
/*// Resize canvas on window resize
window.addEventListener('resize', function () {
engine.resize();
});*/
}(this));
\ No newline at end of file
......@@ -244,7 +244,7 @@
</item>
<item>
<key> <string>serial</string> </key>
<value> <string>1002.51126.415.26214</string> </value>
<value> <string>1003.8464.37017.2594</string> </value>
</item>
<item>
<key> <string>state</string> </key>
......@@ -262,7 +262,7 @@
</tuple>
<state>
<tuple>
<float>1662499095.93</float>
<float>1663849971.49</float>
<string>UTC</string>
</tuple>
</state>
......
/// <reference path="./typings/babylon.3.1.d.ts" />
var MapManager = /** @class */ (function () {
//*************************************************** CONSTRUCTOR **************************************************
function MapManager(scene) {
var _this = this;
var max = GAMEPARAMETERS.mapSize.width;
if (GAMEPARAMETERS.mapSize.depth > max)
max = GAMEPARAMETERS.mapSize.depth;
if (GAMEPARAMETERS.mapSize.height > max)
max = GAMEPARAMETERS.mapSize.height;
max = max < GAMEPARAMETERS.mapSize.depth ? GAMEPARAMETERS.mapSize.depth : max;
// Skybox
var max_sky = (max * 10 < 20000) ? max * 10 : 20000,
skybox = BABYLON.Mesh.CreateBox("skyBox", max_sky, scene);
skybox.infiniteDistance = true;
skybox.renderingGroupId = 0;
var skyboxMat = new BABYLON.StandardMaterial("skybox", scene);
skyboxMat.backFaceCulling = false;
skyboxMat.disableLighting = true;
skyboxMat.reflectionTexture = new BABYLON.CubeTexture("./assets/skybox/sky", scene);
skyboxMat.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
skyboxMat.infiniteDistance = true;
skybox.material = skyboxMat;
// Plane from bottom
var largeGroundMat = new BABYLON.StandardMaterial("largeGroundMat", scene);
largeGroundMat.specularColor = BABYLON.Color3.Black();
largeGroundMat.alpha = 0.4;
var largeGroundBottom = BABYLON.Mesh.CreatePlane("largeGroundBottom", max * 11, scene);
largeGroundBottom.position.y = -0.01;
largeGroundBottom.rotation.x = -Math.PI / 2;
largeGroundBottom.rotation.y = Math.PI;
largeGroundBottom.material = largeGroundMat;
// Camera
scene.activeCamera.upperRadiusLimit = max * 4;
// Terrain
var width = GAMEPARAMETERS.mapSize.width,
depth = GAMEPARAMETERS.mapSize.depth,
height = GAMEPARAMETERS.mapSize.height,
terrain = scene.getMeshByName("terrain001");
terrain.isVisible = true;
terrain.position = BABYLON.Vector3.Zero();
terrain.scaling = new BABYLON.Vector3(depth / 50000, depth / 50000, width / 50000);
// Goals
this._rGoal = BABYLON.Mesh.CreateSphere("rightGoal", 32, GAMEPARAMETERS.goalDiameter, scene);
var rGoalMat = new BABYLON.StandardMaterial("rGoalMat", scene);
rGoalMat.alpha = 0.0;
rGoalMat.diffuseColor = BABYLON.Color3.Red();
this._rGoal.material = rGoalMat;
this._rGoal.position = new BABYLON.Vector3(GAMEPARAMETERS.goalPositionRightTeam.x, GAMEPARAMETERS.goalPositionRightTeam.y, GAMEPARAMETERS.goalPositionRightTeam.z);
this._rGoal.computeWorldMatrix(true);
this._lGoal = BABYLON.Mesh.CreateSphere("leftGoal", 32, GAMEPARAMETERS.goalDiameter, scene);
goal_x = GAMEPARAMETERS.goalPositionLeftTeam.x;
goal_y = GAMEPARAMETERS.goalPositionLeftTeam.y;
goal_z = GAMEPARAMETERS.goalPositionLeftTeam.z;
this._lGoal.position = new BABYLON.Vector3(goal_x, goal_y, goal_z);
var lGoalMat = new BABYLON.StandardMaterial("lGoalMat", scene);
lGoalMat.alpha = 0.0;
lGoalMat.diffuseColor = BABYLON.Color3.Blue();
this._lGoal.material = lGoalMat;
this._lGoal.computeWorldMatrix(true);
//base is now a boat (special object)
ObstacleManager.Prefab.rotation = new BABYLON.Vector3(20.4, 0, 0);
ObstacleManager.Prefab.scaling = new BABYLON.Vector3(15, 15, 15);
goalPart1 = new ObstacleManager("goal_1", scene);
goalPart1.setStartingPosition(goal_x, goal_y, goal_z);
goalPart2 = BABYLON.MeshBuilder.CreateBox("goal_2", { 'size': 1 }, scene);
goalPart2.position = new BABYLON.Vector3(goal_x - 0.5, goal_y + 1.5, goal_z + 1.5);
goalPart2.rotation = new BABYLON.Vector3(0, 0, 0);
goalPart2.scaling = new BABYLON.Vector3(2, 2, 1.5);
goalPart3 = BABYLON.MeshBuilder.CreateCylinder("goal_3", {
'diameterBottom': 1.5,
'diameterTop': 1.5,
'height': 1
}, scene);
goalPart3.position = new BABYLON.Vector3(goal_x + 2.5, goal_y + 1.5, goal_z + 1.5);
goalPart3.rotation = new BABYLON.Vector3(0, 0, 0);
goalPart3.scaling = new BABYLON.Vector3(1.5, 3.5, 1.5);
// Obstacles
var count = 0;
this._obstacles = [];
GAMEPARAMETERS.obstacles.forEach(function (obs) {
var newObj;
switch (obs.type) {
case "box":
newObj = BABYLON.MeshBuilder.CreateBox("obs_" + count, { 'size': 1 }, scene);
break;
case "cylinder":
newObj = BABYLON.MeshBuilder.CreateCylinder("obs_" + count, {
'diameterBottom': obs.diameterBottom,
'diameterTop': obs.diameterTop,
'height': 1
}, scene);
break;
case "sphere":
newObj = BABYLON.MeshBuilder.CreateSphere("obs_" + count, {
'diameterX': obs.scale.x,
'diameterY': obs.scale.y,
'diameterZ': obs.scale.z
}, scene);
break;
case "boat":
ObstacleManager.Prefab.rotation = new BABYLON.Vector3(obs.rotation.x, obs.rotation.y, obs.rotation.z);
ObstacleManager.Prefab.scaling = new BABYLON.Vector3(obs.scale.x * 2, obs.scale.y * 2, obs.scale.z * 2);
newObj = new ObstacleManager("obs_" + count, scene);
newObj.setStartingPosition(obs.position.x, obs.position.y, obs.position.z);
break;
default:
return;
}
newObj["obsType"] = obs.type;
var convertion = Math.PI / 180;
if ("position" in obs)
newObj.position = new BABYLON.Vector3(obs.position.x, obs.position.y, obs.position.z);
if ("rotation" in obs)
newObj.rotation = new BABYLON.Vector3(obs.rotation.x * convertion, obs.rotation.y * convertion, obs.rotation.z * convertion);
if ("scale" in obs)
newObj.scaling = new BABYLON.Vector3(obs.scale.x, obs.scale.y, obs.scale.z);
if ("color" in obs) {
var material = new BABYLON.StandardMaterial(scene);
material.alpha = 1;
material.diffuseColor = new BABYLON.Color3(obs.color.r, obs.color.g, obs.color.b);
newObj.material = material;
}
_this._obstacles.push(newObj);
});
}
Object.defineProperty(MapManager.prototype, "lGoal", {
get: function () { return this._lGoal; },
enumerable: true,
configurable: true
});
Object.defineProperty(MapManager.prototype, "rGoal", {
get: function () { return this._rGoal; },
enumerable: true,
configurable: true
});
Object.defineProperty(MapManager.prototype, "obstacles", {
get: function () { return this._obstacles; },
enumerable: true,
configurable: true
});
return MapManager;
}());
/// <reference path="./typings/babylon.3.1.d.ts" />
var ObstacleManager = /** @class */ (function () {
//*************************************************** CONSTRUCTOR **************************************************
function ObstacleManager(id, scene) {
// Mesh
this._mesh = null;
this._controlMesh = null;
this._colliderBackMesh = null;
this._maxOrientation = Math.PI / 4;
this._scene = scene;
this._id = id;
// Create the control mesh
this._controlMesh = BABYLON.Mesh.CreateBox("obstacleControl_" + id, 0.01, this._scene);
this._controlMesh.isVisible = false;
this._controlMesh.rotation = new BABYLON.Vector3(0, Math.PI, 0);
this._controlMesh.computeWorldMatrix(true);
// Create the mesh from the obstacle prefab
console.log("ObstacleManager.Prefab:", ObstacleManager.Prefab);
this._mesh = ObstacleManager.Prefab.clone("obstacle_" + id, this._controlMesh);
this._mesh.position = BABYLON.Vector3.Zero();
this._mesh.isVisible = true;
this._mesh.computeWorldMatrix(true);
this._propellerAnimMeshes = [];
}
// API
ObstacleManager.prototype._swapAxe = function (vector) {
return new BABYLON.Vector3(vector.x, vector.z, vector.y);
};
Object.defineProperty(ObstacleManager.prototype, "colliderMesh", {
//*************************************************** ACCESSOR *****************************************************
get: function () { return this._mesh; },
enumerable: true,
configurable: true
});
Object.defineProperty(ObstacleManager.prototype, "colliderBackMesh", {
get: function () { return this._colliderBackMesh; },
enumerable: true,
configurable: true
});
Object.defineProperty(ObstacleManager.prototype, "infosMesh", {
get: function () { return this._controlMesh; },
enumerable: true,
configurable: true
});
Object.defineProperty(ObstacleManager.prototype, "position", {
get: function () {
if (this._controlMesh !== null) {
return this._swapAxe(this._controlMesh.position);
}
return null;
},
enumerable: true,
configurable: true
});
//*************************************************** FUNCTIONS ****************************************************
// -- Starting info
/**
* Set the starting position of the obstacle
* Take x,y,z coordinates as parameters
*/
ObstacleManager.prototype.setStartingPosition = function (x, y, z) {
this._controlMesh.position = new BABYLON.Vector3(x, y, z);
this._controlMesh.computeWorldMatrix(true);
this._mesh.computeWorldMatrix(true);
};
return ObstacleManager;
}());
......@@ -103,7 +103,7 @@
</item>
<item>
<key> <string>title</string> </key>
<value> <string>Play Drone in WebWorker</string> </value>
<value> <string>Drone in WebWorker Page</string> </value>
</item>
<item>
<key> <string>version</string> </key>
......@@ -242,7 +242,7 @@
</item>
<item>
<key> <string>serial</string> </key>
<value> <string>1002.51126.10432.54818</string> </value>
<value> <string>1002.51488.47400.14882</string> </value>
</item>
<item>
<key> <string>state</string> </key>
......@@ -260,7 +260,7 @@
</tuple>
<state>
<tuple>
<float>1662499005.88</float>
<float>1662499250.39</float>
<string>UTC</string>
</tuple>
</state>
......
......@@ -105,7 +105,7 @@
</item>
<item>
<key> <string>title</string> </key>
<value> <string>Play Drone in WebWorker JS</string> </value>
<value> <string>Drone in WebWorker Page JS</string> </value>
</item>
<item>
<key> <string>version</string> </key>
......@@ -244,7 +244,7 @@
</item>
<item>
<key> <string>serial</string> </key>
<value> <string>1002.51485.29446.12083</string> </value>
<value> <string>1003.10118.17019.16759</string> </value>
</item>
<item>
<key> <string>state</string> </key>
......@@ -262,7 +262,7 @@
</tuple>
<state>
<tuple>
<float>1662499048.26</float>
<float>1663954426.68</float>
<string>UTC</string>
</tuple>
</state>
......
......@@ -244,7 +244,7 @@
</item>
<item>
<key> <string>serial</string> </key>
<value> <string>1002.51134.58025.699</string> </value>
<value> <string>1003.10284.59408.13346</string> </value>
</item>
<item>
<key> <string>state</string> </key>
......@@ -262,7 +262,7 @@
</tuple>
<state>
<tuple>
<float>1662499082.61</float>
<float>1663959195.15</float>
<string>UTC</string>
</tuple>
</state>
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment