use std::f32::consts::PI;
// StarKingdoms.IO, a browser game about drifting through space
// Copyright (C) 2023 ghostly_zsh, TerraMaster85, core
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see .
use std::net::Ipv4Addr;
use crate::mathutil::rot2d;
use bevy::log::Level;
use bevy::log::LogPlugin;
use bevy::math::{vec2, vec3};
use bevy::{ecs::event::ManualEventReader, prelude::*};
use bevy_rapier2d::prelude::*;
use bevy_twite::{twite::frame::MessageType, ServerEvent, TwiteServerConfig, TwiteServerPlugin};
use component::Input;
use component::*;
use packet::*;
use rand::Rng;
pub mod component;
pub mod macros;
pub mod mathutil;
pub mod packet;
const SCALE: f32 = 10.0;
const EARTH_SIZE: f32 = 1000.0;
const MOON_SIZE: f32 = EARTH_SIZE / 4.;
const MARS_SIZE: f32 = EARTH_SIZE / 2.;
const EARTH_MASS: f32 = 10000.0;
const MOON_MASS: f32 = EARTH_MASS / 30.;
const MARS_MASS: f32 = EARTH_MASS / 8.;
const GRAVITY: f32 = 0.02;
const PART_HALF_SIZE: f32 = 25.0;
const HEARTY_THRUSTER_FORCE: f32 = 0.08;
const LANDING_THRUSTER_FORCE: f32 = 5.;
// maybe make this only cargo modules later
const FREE_MODULE_CAP: usize = 30;
fn main() {
App::new()
.insert_resource(TwiteServerConfig {
addr: Ipv4Addr::new(0, 0, 0, 0),
port: 3000,
})
.add_plugins(MinimalPlugins)
.add_plugins(LogPlugin {
level: Level::DEBUG,
filter: "wgpu=error,bevy_render=info,bevy_ecs=trace".to_string(),
})
.insert_resource(RapierConfiguration {
gravity: Vect { x: 0.0, y: 0.0 },
..Default::default()
})
.init_resource::()
.add_plugins(RapierPhysicsPlugin::::pixels_per_meter(SCALE))
.add_plugins(TwiteServerPlugin)
.add_systems(Startup, setup_integration_parameters)
.add_systems(Startup, spawn_planets)
.add_systems(FixedUpdate, module_spawn)
.add_systems(Update, on_message)
.add_systems(Update, on_close)
.add_systems(FixedUpdate, on_position_change)
.add_systems(FixedUpdate, (gravity_update, player_input_update).chain())
.add_systems(FixedUpdate, convert_modules)
//.insert_resource(Time::::from_seconds(1.0/20.0))
.run();
info!("Goodbye!");
}
fn setup_integration_parameters(mut context: ResMut) {
context.integration_parameters.dt = 1.0 / 60.0;
context.integration_parameters.joint_erp = 0.2;
context.integration_parameters.erp = 0.5;
context.integration_parameters.max_stabilization_iterations = 16;
}
fn spawn_planets(mut commands: Commands) {
info!("Spawning planets");
let earth_pos = Transform::from_xyz(0.0, 0.0, 0.0);
commands
.spawn(PlanetBundle {
planet_type: PlanetType::Earth,
transform: TransformBundle::from(earth_pos),
})
.insert(Collider::ball(EARTH_SIZE / SCALE))
.insert(AdditionalMassProperties::Mass(EARTH_MASS))
.insert(ReadMassProperties::default())
.with_children(|children| {
children
.spawn(Collider::ball((EARTH_SIZE + 3.) / SCALE))
.insert(ActiveEvents::COLLISION_EVENTS)
.insert(Sensor);
})
.insert(RigidBody::Fixed);
let moon_pos = Transform::from_xyz(3000.0 / SCALE, 0.0, 0.0);
commands
.spawn(PlanetBundle {
planet_type: PlanetType::Moon,
transform: TransformBundle::from(moon_pos),
})
.insert(Collider::ball(MOON_SIZE / SCALE))
.insert(AdditionalMassProperties::Mass(MOON_MASS))
.insert(ReadMassProperties::default())
.with_children(|children| {
children
.spawn(Collider::ball((MOON_SIZE + 3.) / SCALE))
.insert(ActiveEvents::COLLISION_EVENTS)
.insert(Sensor);
})
.insert(RigidBody::Fixed);
let mars_pos = Transform::from_xyz(3000.0 / SCALE, 700.0 / SCALE, 0.0);
commands
.spawn(PlanetBundle {
planet_type: PlanetType::Mars,
transform: TransformBundle::from(mars_pos),
})
.insert(Collider::ball(MARS_SIZE / SCALE))
.insert(AdditionalMassProperties::Mass(MARS_MASS))
.insert(ReadMassProperties::default())
.with_children(|children| {
children
.spawn(Collider::ball((MARS_SIZE + 3.) / SCALE))
.insert(ActiveEvents::COLLISION_EVENTS)
.insert(Sensor);
})
.insert(RigidBody::Fixed);
}
fn module_spawn(
mut commands: Commands,
time: Res,
mut module_timer: ResMut,
part_query: Query<&PartType, Without>,
mut packet_send: EventWriter,
) {
if module_timer.0.tick(time.delta()).just_finished() {
let angle: f32 = {
let mut rng = rand::thread_rng();
rng.gen::() * std::f32::consts::PI * 2.
};
let mut transform = Transform::from_xyz(
angle.cos() * 1500.0 / SCALE,
angle.sin() * 1500.0 / SCALE,
0.0,
);
transform.rotate_z(angle);
if part_query.iter().count() < FREE_MODULE_CAP {
let mut entity = commands.spawn(PartBundle {
part_type: PartType::Cargo,
transform: TransformBundle::from(transform),
});
entity
.insert(RigidBody::Dynamic)
.with_children(|children| {
children
.spawn(Collider::cuboid(18.75 / SCALE, 23.4375 / SCALE))
.insert(TransformBundle::from(Transform::from_xyz(
0.,
1.5625 / SCALE,
0.,
)));
})
.insert(ExternalForce::default())
.insert(ExternalImpulse::default())
.insert(Velocity::default())
.insert(ReadMassProperties::default());
let packet = Packet::SpawnPart {
id: entity.id().index(),
part: Part {
part_type: PartType::Cargo,
transform: proto_transform!(transform),
},
};
let buf = serde_json::to_vec(&packet).unwrap();
packet_send.send(ServerEvent::Broadcast(MessageType::Text, buf));
}
}
}
fn on_message(
mut commands: Commands,
planet_query: Query<(Entity, &PlanetType, &Transform)>,
mut part_query: Query<
(
Entity,
&PartType,
&mut Transform,
&mut Velocity,
Option<&LooseAttach>,
),
(Without, Without, Without),
>,
mut attached_query: Query<
(
Entity,
&PartType,
&mut Transform,
&mut Attach,
&Velocity,
Option<&CanAttach>,
Option<&LooseAttach>,
),
(Without, Without),
>,
mut player_query: Query<
(Entity, &mut Player, &Transform, &Velocity, &mut Attach),
Without,
>,
mut packet_recv: Local>,
mut packet_event_send: ResMut>,
) {
let mut event_queue = Vec::new();
for ev in packet_recv.read(&packet_event_send) {
if let ServerEvent::Recv(addr, MessageType::Text, data) = ev {
let data = String::from_utf8_lossy(&data);
let packet: Packet = err_or_cont!(serde_json::from_str(&data));
match packet {
Packet::ClientLogin { username, .. } => {
let angle: f32 = {
let mut rng = rand::thread_rng();
rng.gen::() * std::f32::consts::PI * 2.
};
let mut transform = Transform::from_xyz(
angle.cos() * 1100.0 / SCALE,
angle.sin() * 1100.0 / SCALE,
0.0,
);
transform.rotate_z(angle);
let entity_id = commands
.spawn(PlayerBundle {
part: PartBundle {
part_type: PartType::Hearty,
transform: TransformBundle::from(transform),
},
player: Player {
addr: *addr,
username: username.to_string(),
input: component::Input::default(),
selected: None,
},
attach: Attach {
associated_player: None,
parent: None,
children: [None, None, None, None],
},
})
.insert(Collider::cuboid(
PART_HALF_SIZE / SCALE,
PART_HALF_SIZE / SCALE,
))
.insert(AdditionalMassProperties::MassProperties(MassProperties {
local_center_of_mass: vec2(0.0, 0.0),
mass: 0.0001,
principal_inertia: 0.005,
}))
.insert(ExternalImpulse {
impulse: Vec2::ZERO,
torque_impulse: 0.0,
})
.insert(ExternalForce::default())
.insert(ReadMassProperties::default())
.insert(Velocity::default())
.insert(RigidBody::Dynamic)
.id();
let id = entity_id.index();
// tell this player the planets
let mut planets = Vec::new();
for (entity, planet_type, transform) in planet_query.iter() {
let translation = transform.translation;
planets.push((
entity.index(),
Planet {
planet_type: *planet_type,
transform: proto_transform!(Transform::from_translation(
translation * SCALE
)),
radius: match *planet_type {
PlanetType::Earth => EARTH_SIZE,
PlanetType::Moon => MOON_SIZE,
PlanetType::Mars => MARS_SIZE,
},
},
));
}
let packet = Packet::PlanetPositions { planets };
let buf = serde_json::to_vec(&packet).unwrap();
event_queue.push(ServerEvent::Send(*addr, MessageType::Text, buf));
// tell the player already existing users
let mut players = Vec::new();
for (entity, player, _, _, _) in &player_query {
players.push((entity.index(), player.username.clone()));
}
let packet = Packet::PlayerList { players };
let buf = serde_json::to_vec(&packet).unwrap();
event_queue.push(ServerEvent::Send(*addr, MessageType::Text, buf));
// tell other players that a player has spawned in
let packet = Packet::SpawnPlayer {
id,
username: username.to_string(),
};
let buf = serde_json::to_vec(&packet).unwrap();
event_queue.push(ServerEvent::Broadcast(MessageType::Text, buf));
let packet = Packet::Message {
message_type: packet::MessageType::Server,
actor: "SERVER".to_string(),
content: format!("{} has joined the server!", username),
};
let buf = serde_json::to_vec(&packet).unwrap();
event_queue.push(ServerEvent::Broadcast(MessageType::Text, buf));
// tell the player where parts are
let mut parts = Vec::new();
for (entity, part_type, transform, _, _) in &part_query {
parts.push((
entity.index(),
Part {
part_type: *part_type,
transform: proto_transform!(Transform::from_translation(
transform.translation * SCALE
)),
},
));
}
for (entity, part_type, transform, _, _, _, _) in &attached_query {
parts.push((
entity.index(),
Part {
part_type: *part_type,
transform: proto_transform!(Transform::from_translation(
transform.translation * SCALE
)),
},
));
}
parts.push((
id,
Part {
part_type: PartType::Hearty,
transform: proto_transform!(Transform::from_translation(
transform.translation * SCALE
)
.with_rotation(transform.rotation)),
},
));
let packet = Packet::PartPositions { parts };
let buf = serde_json::to_vec(&packet).unwrap();
event_queue.push(ServerEvent::Send(*addr, MessageType::Text, buf));
// and send the welcome message :)
let packet = Packet::Message {
message_type: packet::MessageType::Server,
actor: "SERVER".to_string(),
content: "Welcome to StarKingdoms.IO! Have fun!".to_string(),
};
let buf = serde_json::to_vec(&packet).unwrap();
event_queue.push(ServerEvent::Send(*addr, MessageType::Text, buf));
}
Packet::SendMessage { target, content } => {
// find our player
let mut player = None;
for (_, q_player, _, _, _) in &player_query {
if q_player.addr == *addr {
player = Some(q_player);
}
}
let player = player.unwrap();
if let Some(target_username) = target {
let mut target_player = None;
for (_, q_player, _, _, _) in &player_query {
if q_player.username == target_username {
target_player = Some(q_player);
}
}
let target_player = target_player.unwrap();
let packet = Packet::Message {
message_type: packet::MessageType::Direct,
actor: player.username.clone(),
content,
};
let buf = serde_json::to_vec(&packet).unwrap();
event_queue.push(ServerEvent::Send(
target_player.addr,
MessageType::Text,
buf.clone(),
));
event_queue.push(ServerEvent::Send(*addr, MessageType::Text, buf));
} else {
// send to general chat
let packet = Packet::Message {
message_type: packet::MessageType::Chat,
actor: player.username.clone(),
content,
};
let buf = serde_json::to_vec(&packet).unwrap();
event_queue.push(ServerEvent::Broadcast(MessageType::Text, buf));
}
}
Packet::PlayerInput {
up,
down,
left,
right,
} => {
for (_, mut q_player, _, _, _) in &mut player_query {
if q_player.addr == *addr {
q_player.input.up = up;
q_player.input.down = down;
q_player.input.left = left;
q_player.input.right = right;
}
}
}
Packet::PlayerMouseInput {
x,
y,
released,
button: _,
} => {
for (entity, mut q_player, transform, velocity, mut attach) in &mut player_query
{
if q_player.addr == *addr {
if released {
let select = if let Some(s) = q_player.selected {
s
} else {
break;
};
q_player.selected = None;
if part_query.contains(select) {
let mut module = part_query.get_mut(select).unwrap();
// attach module
let p_pos = transform.translation;
let (rel_x, rel_y) = (p_pos.x - x / SCALE, p_pos.y - y / SCALE);
let angle = transform.rotation.to_euler(EulerRot::ZYX).0;
let (rel_x, rel_y) = (
rel_x * (-angle).cos() - rel_y * (-angle).sin(),
rel_x * (-angle).sin() + rel_y * (-angle).cos(),
);
if attach.children[2] == None
&& 15. / SCALE < rel_y
&& rel_y < 30. / SCALE
&& -20. / SCALE < rel_x
&& rel_x < 20. / SCALE
{
module.2.translation = vec3(
p_pos.x + 53. / SCALE * angle.sin(),
p_pos.y - 53. / SCALE * angle.cos(),
0.,
);
module.2.rotation =
Quat::from_euler(EulerRot::ZYX, angle, 0., 0.);
module.3.linvel = velocity.linvel;
let joint = FixedJointBuilder::new()
.local_anchor1(vec2(0. / SCALE, -53. / SCALE));
let mut children = [None, None, None, None];
if let Some(loose_attach) = module.4 {
commands.entity(entity).remove::();
if *module.1 == PartType::LandingThruster {
commands
.entity(loose_attach.children[2].unwrap())
.insert(Attach {
associated_player: attach.associated_player,
parent: Some(entity),
children: [None, None, None, None],
});
}
children = loose_attach.children;
}
let mut module_entity = commands.entity(module.0);
module_entity.insert(ImpulseJoint::new(entity, joint));
module_entity.insert(Attach {
associated_player: Some(entity),
parent: Some(entity),
children,
});
attach.children[2] = Some(module.0);
if *module.1 == PartType::LandingThruster {
let loose_attach = module.4.unwrap().clone();
let mut transform = part_query
.get_mut(loose_attach.children[2].unwrap())
.unwrap()
.2;
transform.translation = vec3(
p_pos.x + 53. / SCALE * angle.sin(),
p_pos.y - 53. / SCALE * angle.cos(),
0.,
);
transform.rotation =
Quat::from_euler(EulerRot::ZYX, angle, 0., 0.);
}
break;
} else if attach.children[0] == None
&& -30. / SCALE < rel_y
&& rel_y < -15. / SCALE
&& -20. / SCALE < rel_x
&& rel_x < 20. / SCALE
{
module.2.translation = vec3(
p_pos.x - 53. / SCALE * angle.sin(),
p_pos.y + 53. / SCALE * angle.cos(),
0.,
);
module.2.rotation =
Quat::from_euler(EulerRot::ZYX, angle + PI, 0., 0.);
module.3.linvel = velocity.linvel;
let joint = FixedJointBuilder::new()
.local_anchor1(vec2(0. / SCALE, 53. / SCALE));
let mut children = [None, None, None, None];
if let Some(loose_attach) = module.4 {
commands.entity(entity).remove::();
if *module.1 == PartType::LandingThruster {
commands
.entity(loose_attach.children[2].unwrap())
.insert(Attach {
associated_player: attach.associated_player,
parent: Some(entity),
children: [None, None, None, None],
});
}
children = loose_attach.children;
}
let mut module_entity = commands.entity(module.0);
module_entity.insert(ImpulseJoint::new(entity, joint));
module_entity.insert(Attach {
associated_player: Some(entity),
parent: Some(entity),
children,
});
attach.children[0] = Some(module.0);
if *module.1 == PartType::LandingThruster {
let loose_attach = module.4.unwrap().clone();
let mut transform = part_query
.get_mut(loose_attach.children[2].unwrap())
.unwrap()
.2;
transform.translation = vec3(
p_pos.x - 53. / SCALE * angle.sin(),
p_pos.y + 53. / SCALE * angle.cos(),
0.,
);
transform.rotation =
Quat::from_euler(EulerRot::ZYX, angle + PI, 0., 0.);
}
break;
} else if attach.children[1] == None
&& -30. / SCALE < rel_x
&& rel_x < -15. / SCALE
&& -20. / SCALE < rel_y
&& rel_y < 20. / SCALE
{
module.2.translation = vec3(
p_pos.x + 53. / SCALE * angle.cos(),
p_pos.y + 53. / SCALE * angle.sin(),
0.,
);
module.2.rotation = Quat::from_euler(
EulerRot::ZYX,
angle + (PI / 2.),
0.,
0.,
);
module.3.linvel = velocity.linvel;
let joint = FixedJointBuilder::new()
.local_anchor1(vec2(53. / SCALE, 0. / SCALE))
.local_basis2(std::f32::consts::PI / 2.);
let mut children = [None, None, None, None];
if let Some(loose_attach) = module.4 {
commands.entity(entity).remove::();
if *module.1 == PartType::LandingThruster {
commands
.entity(loose_attach.children[2].unwrap())
.insert(Attach {
associated_player: attach.associated_player,
parent: Some(entity),
children: [None, None, None, None],
});
}
children = loose_attach.children;
}
let mut module_entity = commands.entity(module.0);
module_entity.insert(ImpulseJoint::new(entity, joint));
module_entity.insert(Attach {
associated_player: Some(entity),
parent: Some(entity),
children,
});
attach.children[1] = Some(module.0);
if *module.1 == PartType::LandingThruster {
let loose_attach = module.4.unwrap().clone();
let mut transform = part_query
.get_mut(loose_attach.children[2].unwrap())
.unwrap()
.2;
transform.translation = vec3(
p_pos.x + 53. / SCALE * angle.cos(),
p_pos.y + 53. / SCALE * angle.sin(),
0.,
);
transform.rotation = Quat::from_euler(
EulerRot::ZYX,
angle + (PI / 2.),
0.,
0.,
);
}
break;
} else if attach.children[3] == None
&& 15. / SCALE < rel_x
&& rel_x < 30. / SCALE
&& -20. / SCALE < rel_y
&& rel_y < 20. / SCALE
{
module.2.translation = vec3(
p_pos.x - 53. / SCALE * angle.cos(),
p_pos.y - 53. / SCALE * angle.sin(),
0.,
);
module.2.rotation = Quat::from_euler(
EulerRot::ZYX,
angle - (PI / 2.),
0.,
0.,
);
module.3.linvel = velocity.linvel;
let joint = FixedJointBuilder::new()
.local_anchor1(vec2(-53. / SCALE, 0. / SCALE))
.local_basis2(-std::f32::consts::PI / 2.);
let mut children = [None, None, None, None];
if let Some(loose_attach) = module.4 {
commands.entity(entity).remove::();
if *module.1 == PartType::LandingThruster {
commands
.entity(loose_attach.children[2].unwrap())
.insert(Attach {
associated_player: attach.associated_player,
parent: Some(entity),
children: [None, None, None, None],
});
}
children = loose_attach.children;
}
let mut module_entity = commands.entity(module.0);
module_entity.insert(ImpulseJoint::new(entity, joint));
module_entity.insert(Attach {
associated_player: Some(entity),
parent: Some(entity),
children,
});
attach.children[3] = Some(module.0);
if *module.1 == PartType::LandingThruster {
let loose_attach = module.4.unwrap().clone();
let mut transform = part_query
.get_mut(loose_attach.children[2].unwrap())
.unwrap()
.2;
transform.translation = vec3(
p_pos.x - 53. / SCALE * angle.cos(),
p_pos.y - 53. / SCALE * angle.sin(),
0.,
);
transform.rotation = Quat::from_euler(
EulerRot::ZYX,
angle - (PI / 2.),
0.,
0.,
);
}
break;
}
} else if attached_query.contains(select) {
let module = attached_query.get(select).unwrap();
let parent = module.3.parent.unwrap();
commands.entity(select).remove::();
commands.entity(select).remove::();
let children_attach = module.3.clone();
if *module.1 == PartType::LandingThruster {
commands.entity(select).insert(LooseAttach {
children: module.3.children,
});
commands
.entity(module.3.children[2].unwrap())
.remove::();
} else {
detach_recursive(
&mut commands,
module.3.clone(),
&mut attached_query,
);
}
if attached_query.contains(parent) {
{
let mut parent_attach =
attached_query.get_mut(parent).unwrap().3;
let children = parent_attach.children.clone();
for (i, child) in children.iter().enumerate() {
if let Some(child) = child {
if *child == select {
parent_attach.children[i] = None;
}
}
}
}
let mut module = attached_query.get_mut(select).unwrap();
module.2.translation = vec3(x / SCALE, y / SCALE, 0.);
} else {
for (i, child) in attach.children.clone().iter().enumerate()
{
if let Some(child) = child {
if *child == select {
attach.children[i] = None;
let mut module =
attached_query.get_mut(select).unwrap();
module.2.translation =
vec3(x / SCALE, y / SCALE, 0.);
if *module.1 == PartType::LandingThruster {
let sub_entity =
children_attach.children[2].unwrap();
let mut suspension = attached_query
.get_mut(sub_entity)
.unwrap();
suspension.2.translation =
vec3(x / SCALE, y / SCALE, 0.);
}
}
}
}
}
break;
}
if attach_on_module_tree(
x,
y,
&mut commands,
attach.clone(),
select,
&mut attached_query,
&mut part_query,
) {
break;
}
// move module to cursor since no attach
let mut part = part_query.get_mut(select).unwrap();
part.2.translation = vec3(x / SCALE, y / SCALE, 0.);
if *part.1 == PartType::LandingThruster {
if let Some(loose_attach) = part.4 {
let sub_entity = loose_attach.children[2].unwrap();
let mut part = part_query.get_mut(sub_entity).unwrap();
part.2.translation = vec3(x / SCALE, y / SCALE, 0.);
}
}
break;
}
for (entity, part_type, transform, _m_attach, _velocity, _, _) in
&attached_query
{
if *part_type == PartType::LandingThrusterSuspension {
continue;
}
let pos = transform.translation;
let rel_x = pos.x - x / SCALE;
let rel_y = pos.y - y / SCALE;
let angle = -transform.rotation.z;
let x = rel_x * angle.cos() - rel_y * angle.sin();
let y = rel_x * angle.sin() + rel_y * angle.cos();
let mut bound =
[-25. / SCALE, 25. / SCALE, -25. / SCALE, 25. / SCALE]; // left, right, top, bottom
if let PartType::Cargo = part_type {
bound = [
-18.75 / SCALE,
18.75 / SCALE,
-25. / SCALE,
21.875 / SCALE,
];
}
if bound[0] < x && x < bound[1] {
if bound[2] < y && y < bound[3] {
q_player.selected = Some(entity);
break;
}
}
}
for (entity, part_type, transform, _, _) in &part_query {
if *part_type == PartType::LandingThrusterSuspension {
continue;
}
let pos = transform.translation;
let rel_x = pos.x - x / SCALE;
let rel_y = pos.y - y / SCALE;
let angle = -transform.rotation.z;
let x = rel_x * angle.cos() - rel_y * angle.sin();
let y = rel_x * angle.sin() + rel_y * angle.cos();
let mut bound =
[-25. / SCALE, 25. / SCALE, -25. / SCALE, 25. / SCALE]; // left, right, top, bottom
if let PartType::Cargo = part_type {
bound = [
-18.75 / SCALE,
18.75 / SCALE,
-25. / SCALE,
21.875 / SCALE,
];
}
if bound[0] < x && x < bound[1] {
if bound[2] < y && y < bound[3] {
q_player.selected = Some(entity);
break;
}
}
}
}
}
}
_ => continue,
}
}
}
for event in event_queue {
packet_event_send.send(event);
}
}
fn detach_recursive(
commands: &mut Commands,
attach: Attach,
attached_query: &mut Query<
(
Entity,
&PartType,
&mut Transform,
&mut Attach,
&Velocity,
Option<&CanAttach>,
Option<&LooseAttach>,
),
(Without, Without),
>,
) {
for child in attach.children {
if let Some(child) = child {
{
let (entity, part_type, _transform, attach, _velocity, _, _) =
attached_query.get(child).unwrap();
commands.entity(entity).remove::();
if *part_type == PartType::LandingThruster {
commands.entity(entity).insert(LooseAttach {
children: attach.children,
});
commands
.entity(attach.children[2].unwrap())
.remove::();
continue;
} else if *part_type == PartType::LandingThrusterSuspension {
let parent = attach.parent.unwrap();
let parent_attach = attached_query.get(parent).unwrap().3;
println!("suspension {:?} {:?}", parent_attach.children, entity);
commands.entity(parent).insert(LooseAttach {
children: parent_attach.children,
});
} else {
commands.entity(entity).remove::();
detach_recursive(commands, attach.clone(), attached_query);
}
}
let (entity, _part_type, _transform, attach, _velocity, _, _) =
attached_query.get_mut(child).unwrap();
let parent = attach.parent.unwrap();
if attached_query.contains(parent) {
let mut parent_attach = attached_query.get_mut(parent).unwrap().3;
let children = parent_attach.children.clone();
for (i, child) in children.iter().enumerate() {
if let Some(child) = child {
if *child == entity {
parent_attach.children[i] = None;
}
}
}
}
}
}
}
fn attach_on_module_tree(
x: f32,
y: f32,
commands: &mut Commands,
attach: Attach,
select: Entity,
attached_query: &mut Query<
(
Entity,
&PartType,
&mut Transform,
&mut Attach,
&Velocity,
Option<&CanAttach>,
Option<&LooseAttach>,
),
(Without, Without),
>,
part_query: &mut Query<
(
Entity,
&PartType,
&mut Transform,
&mut Velocity,
Option<&LooseAttach>,
),
(Without, Without, Without),
>,
) -> bool {
let mut ret = false;
for child in attach.children {
if let Some(child) = child {
let (entity, _part_type, transform, mut attach, velocity, can_attach, loose_attach) =
attached_query.get_mut(child).unwrap();
let p_pos = transform.translation;
let (rel_x, rel_y) = (p_pos.x - x / SCALE, p_pos.y - y / SCALE);
let angle = transform.rotation.to_euler(EulerRot::ZYX).0;
let (rel_x, rel_y) = (
rel_x * (-angle).cos() - rel_y * (-angle).sin(),
rel_x * (-angle).sin() + rel_y * (-angle).cos(),
);
let mut module = part_query.get_mut(select).unwrap();
let attachable = can_attach != None;
if attach.children[2] == None
&& attachable
&& 15. / SCALE < rel_y
&& rel_y < 30. / SCALE
&& -20. / SCALE < rel_x
&& rel_x < 20. / SCALE
{
module.2.translation = vec3(
p_pos.x + 53. / SCALE * angle.sin(),
p_pos.y - 53. / SCALE * angle.cos(),
0.,
);
module.2.rotation = Quat::from_euler(EulerRot::ZYX, angle, 0., 0.);
module.3.linvel = velocity.linvel;
let joint = FixedJointBuilder::new().local_anchor1(vec2(0. / SCALE, -53. / SCALE));
let mut children = [None, None, None, None];
if let Some(loose_attach) = loose_attach {
commands.entity(entity).remove::();
if *module.1 == PartType::LandingThruster {
commands
.entity(loose_attach.children[2].unwrap())
.insert(Attach {
associated_player: attach.associated_player,
parent: Some(entity),
children: [None, None, None, None],
});
}
children = loose_attach.children;
}
let mut module_entity = commands.entity(module.0);
module_entity.insert(ImpulseJoint::new(entity, joint));
module_entity.insert(Attach {
associated_player: attach.associated_player,
parent: Some(entity),
children,
});
attach.children[2] = Some(module.0);
return true;
} else if attach.children[1] == None
&& attachable
&& -30. / SCALE < rel_x
&& rel_x < -15. / SCALE
&& -20. / SCALE < rel_y
&& rel_y < 20. / SCALE
{
module.2.translation = vec3(
p_pos.x + 53. / SCALE * angle.cos(),
p_pos.y + 53. / SCALE * angle.sin(),
0.,
);
module.2.rotation =
Quat::from_euler(EulerRot::ZYX, angle + (std::f32::consts::PI / 2.), 0., 0.);
module.3.linvel = velocity.linvel;
let joint = FixedJointBuilder::new()
.local_anchor1(vec2(53. / SCALE, 0. / SCALE))
.local_basis2(std::f32::consts::PI / 2.);
let mut children = [None, None, None, None];
if let Some(loose_attach) = loose_attach {
commands.entity(entity).remove::();
if *module.1 == PartType::LandingThruster {
commands
.entity(loose_attach.children[2].unwrap())
.insert(Attach {
associated_player: attach.associated_player,
parent: Some(entity),
children: [None, None, None, None],
});
}
children = loose_attach.children;
}
let mut module_entity = commands.entity(module.0);
module_entity.insert(ImpulseJoint::new(entity, joint));
module_entity.insert(Attach {
associated_player: attach.associated_player,
parent: Some(entity),
children,
});
attach.children[1] = Some(module.0);
return true;
} else if attach.children[3] == None
&& attachable
&& 15. / SCALE < rel_x
&& rel_x < 30. / SCALE
&& -20. / SCALE < rel_y
&& rel_y < 20. / SCALE
{
module.2.translation = vec3(
p_pos.x - 53. / SCALE * angle.cos(),
p_pos.y - 53. / SCALE * angle.sin(),
0.,
);
module.2.rotation =
Quat::from_euler(EulerRot::ZYX, angle - (std::f32::consts::PI / 2.), 0., 0.);
module.3.linvel = velocity.linvel;
let joint = FixedJointBuilder::new()
.local_anchor1(vec2(-53. / SCALE, 0. / SCALE))
.local_basis2(-std::f32::consts::PI / 2.);
let mut children = [None, None, None, None];
if let Some(loose_attach) = loose_attach {
commands.entity(entity).remove::();
if *module.1 == PartType::LandingThruster {
commands
.entity(loose_attach.children[2].unwrap())
.insert(Attach {
associated_player: attach.associated_player,
parent: Some(entity),
children: [None, None, None, None],
});
}
children = loose_attach.children;
}
let mut module_entity = commands.entity(module.0);
module_entity.insert(ImpulseJoint::new(entity, joint));
module_entity.insert(Attach {
associated_player: attach.associated_player,
parent: Some(entity),
children,
});
attach.children[3] = Some(module.0);
return true;
}
ret = ret
| if *module.1 != PartType::LandingThruster {
attach_on_module_tree(
x,
y,
commands,
attach.clone(),
select,
attached_query,
part_query,
)
} else {
false
};
}
}
return ret;
}
fn convert_modules(
mut commands: Commands,
rapier_context: Res,
planet_query: Query<(Entity, &PlanetType, &Children)>,
player_query: Query<&Attach, With>,
mut attached_query: Query<
(Entity, &mut PartType, &mut Attach, &Children, &Transform),
Without,
>,
mut collider_query: Query<
(&mut Collider, &mut Transform, &Parent),
(Without, Without),
>,
mut packet_send: EventWriter,
) {
for (_planet_entity, planet_type, children) in &planet_query {
for (entity1, entity2, intersecting) in
rapier_context.intersections_with(*children.first().unwrap())
{
if intersecting {
let other = if *children.first().unwrap() == entity1 {
entity2
} else {
entity1
};
let player_entity = if player_query.contains(other) {
other
} else if attached_query.contains(other) {
attached_query
.get(other)
.unwrap()
.2
.associated_player
.unwrap()
} else if collider_query.contains(other) {
let parent = collider_query.get(other).unwrap().2.get();
if attached_query.contains(parent) {
attached_query
.get(parent)
.unwrap()
.2
.associated_player
.unwrap()
} else {
continue;
}
} else {
continue;
};
let player_attach = player_query.get(player_entity).unwrap();
convert_modules_recursive(
&mut commands,
*planet_type,
player_attach.clone(),
&mut attached_query,
&mut collider_query,
&mut packet_send,
);
}
}
}
}
fn convert_modules_recursive(
commands: &mut Commands,
planet_type: PlanetType,
attach: Attach,
attached_query: &mut Query<
(Entity, &mut PartType, &mut Attach, &Children, &Transform),
Without,
>,
collider_query: &mut Query<
(&mut Collider, &mut Transform, &Parent),
(Without, Without),
>,
packet_send: &mut EventWriter,
) {
for child in attach.children {
if let Some(child) = child {
let (module_entity, mut part_type, mut attach, children, module_transform) =
attached_query.get_mut(child).unwrap();
if *part_type == PartType::Cargo {
match planet_type {
PlanetType::Mars => {
*part_type = PartType::Hub;
let (mut collider, mut transform, _) =
collider_query.get_mut(*children.first().unwrap()).unwrap();
*collider =
Collider::cuboid(PART_HALF_SIZE / SCALE, PART_HALF_SIZE / SCALE);
*transform = Transform::from_xyz(0., 0., 0.);
commands
.get_entity(module_entity)
.unwrap()
.remove::();
commands
.get_entity(module_entity)
.unwrap()
.insert(CanAttach(15));
let packet = Packet::DespawnPart { id: child.index() };
let buf = serde_json::to_vec(&packet).unwrap();
packet_send.send(ServerEvent::Broadcast(MessageType::Text, buf.clone()));
let packet = Packet::SpawnPart {
id: child.index(),
part: Part {
part_type: PartType::Hub,
transform: proto_transform!(transform),
},
};
let buf = serde_json::to_vec(&packet).unwrap();
packet_send.send(ServerEvent::Broadcast(MessageType::Text, buf));
}
PlanetType::Moon => {
*part_type = PartType::LandingThruster;
let (mut collider, mut transform, _) =
collider_query.get_mut(*children.first().unwrap()).unwrap();
*collider = Collider::cuboid(PART_HALF_SIZE / SCALE, 18.75 / SCALE);
*transform = Transform::from_xyz(0., 6.25 / SCALE, 0.);
//commands.get_entity(module_entity).unwrap().remove::();
let joint = PrismaticJointBuilder::new(Vec2::new(0., 1.))
.local_anchor1(Vec2::new(0., 0.))
.local_anchor2(Vec2::new(0., 0.))
.motor_position(0., 150., 10.)
.limits([0., 50. / SCALE])
.build();
let mut suspension = commands.spawn(PartBundle {
transform: TransformBundle::from(*module_transform),
part_type: PartType::LandingThrusterSuspension,
});
suspension
.insert(RigidBody::Dynamic)
.with_children(|children| {
children
.spawn(Collider::cuboid(PART_HALF_SIZE / SCALE, 1. / SCALE))
.insert(TransformBundle::from(Transform::from_xyz(
0.,
-24. / SCALE,
0.,
)));
})
.insert(ImpulseJoint::new(module_entity, joint))
.insert(ExternalForce::default())
.insert(ExternalImpulse::default())
.insert(Velocity::default())
.insert(ReadMassProperties::default())
.insert(Attach {
associated_player: attach.associated_player,
parent: Some(module_entity),
children: [None, None, None, None],
});
attach.children[2] = Some(suspension.id());
let packet = Packet::DespawnPart { id: child.index() };
let buf = serde_json::to_vec(&packet).unwrap();
packet_send.send(ServerEvent::Broadcast(MessageType::Text, buf.clone()));
let packet = Packet::SpawnPart {
id: child.index(),
part: Part {
part_type: PartType::LandingThruster,
transform: proto_transform!(transform),
},
};
let buf = serde_json::to_vec(&packet).unwrap();
packet_send.send(ServerEvent::Broadcast(MessageType::Text, buf));
let packet = Packet::SpawnPart {
id: suspension.id().index(),
part: Part {
part_type: PartType::LandingThrusterSuspension,
transform: proto_transform!(transform),
},
};
let buf = serde_json::to_vec(&packet).unwrap();
packet_send.send(ServerEvent::Broadcast(MessageType::Text, buf));
}
_ => {}
}
}
if *part_type != PartType::LandingThruster {
convert_modules_recursive(
commands,
planet_type,
attach.clone(),
attached_query,
collider_query,
packet_send,
);
}
}
}
}
fn on_close(
player_query: Query<(Entity, &Player, &Attach)>,
attached_query: Query<&Attach, With>,
part_query: Query<&PartType>,
mut commands: Commands,
mut packet_recv: Local>,
mut packet_send: ResMut>,
) {
let mut packets = Vec::new();
for packet in packet_recv.read(&packet_send) {
if let ServerEvent::Close(addr) = packet {
for (entity, player, attach) in &player_query {
if player.addr == *addr {
despawn_module_tree(
&mut commands,
attach,
&attached_query,
&part_query,
&mut packets,
);
commands.entity(entity).despawn_recursive();
let packet = Packet::PlayerLeave { id: entity.index() };
let buf = serde_json::to_vec(&packet).unwrap();
for (in_entity, player, _) in &player_query {
if entity != in_entity {
packets.push(ServerEvent::Send(
player.addr,
MessageType::Text,
buf.clone(),
));
}
}
}
}
}
}
for packet in packets {
packet_send.send(packet);
}
}
fn despawn_module_tree(
commands: &mut Commands,
attach: &Attach,
attached_query: &Query<&Attach, With>,
part_query: &Query<&PartType>,
packets: &mut Vec,
) {
for child in attach.children {
if let Some(child) = child {
commands.entity(child).despawn_recursive();
let packet = Packet::DespawnPart { id: child.index() };
let buf = serde_json::to_vec(&packet).unwrap();
packets.push(ServerEvent::Broadcast(MessageType::Text, buf.clone()));
let attach = match attached_query.get(child) {
Ok(s) => s,
Err(_) => match part_query.get(child) {
Ok(_) => {
continue;
}
Err(e) => panic!("{}", e),
},
};
despawn_module_tree(commands, attach, attached_query, part_query, packets);
}
}
}
fn on_position_change(
mut commands: Commands,
part_query: Query<(Entity, &PartType, &Transform), Changed>,
planet_query: Query<(Entity, &PlanetType, &Transform), Changed>,
mut packet_send: EventWriter,
) {
let mut updated_parts = Vec::new();
for (entity, part_type, transform) in part_query.iter() {
let id = commands.entity(entity).id().index();
updated_parts.push((
id,
Part {
part_type: *part_type,
transform: proto_transform!(Transform::from_translation(
transform.translation * SCALE
)
.with_rotation(transform.rotation)),
},
));
}
if !updated_parts.is_empty() {
let packet = Packet::PartPositions {
parts: updated_parts,
};
let buf = serde_json::to_vec(&packet).unwrap();
packet_send.send(ServerEvent::Broadcast(MessageType::Text, buf));
}
let mut planets = Vec::new();
for (entity, planet_type, transform) in planet_query.iter() {
let id = commands.entity(entity).id().index();
planets.push((
id,
Planet {
planet_type: *planet_type,
transform: proto_transform!(Transform::from_translation(
transform.translation * SCALE
)),
radius: match *planet_type {
PlanetType::Earth => EARTH_SIZE,
PlanetType::Moon => MOON_SIZE,
PlanetType::Mars => MARS_SIZE,
},
},
));
}
if !planets.is_empty() {
let packet = Packet::PlanetPositions { planets };
let buf = serde_json::to_vec(&packet).unwrap();
packet_send.send(ServerEvent::Broadcast(MessageType::Text, buf));
}
}
fn player_input_update(
mut player_and_body_query: Query<(
Entity,
&mut Player,
&Attach,
&mut ExternalForce,
&Transform,
)>,
mut attached_query: Query<
(&Attach, &PartType, &mut ExternalForce, &Transform),
Without,
>,
) {
for (_, player, attach, mut forces, transform) in &mut player_and_body_query {
//forces.torque = 0.0;
//forces.force = Vec2::ZERO;
if !(player.input.up || player.input.down || player.input.right || player.input.left) {
continue;
}
let mut fmul_bottom_left_thruster: f32 = 0.0;
let mut fmul_bottom_right_thruster: f32 = 0.0;
let mut fmul_top_left_thruster: f32 = 0.0;
let mut fmul_top_right_thruster: f32 = 0.0;
if player.input.up {
fmul_bottom_left_thruster += 1.0;
fmul_bottom_right_thruster += 1.0;
}
if player.input.down {
fmul_top_left_thruster -= 1.0;
fmul_top_right_thruster -= 1.0;
}
if player.input.left {
fmul_top_left_thruster += 1.0;
fmul_bottom_right_thruster -= 1.0;
}
if player.input.right {
fmul_top_right_thruster += 1.0;
fmul_bottom_left_thruster -= 1.0;
}
fmul_top_left_thruster = fmul_top_left_thruster.clamp(-1.0, 1.0);
fmul_top_right_thruster = fmul_top_right_thruster.clamp(-1.0, 1.0);
fmul_bottom_left_thruster = fmul_bottom_left_thruster.clamp(-1.0, 1.0);
fmul_bottom_right_thruster = fmul_bottom_right_thruster.clamp(-1.0, 1.0);
if player.input.up {
fmul_bottom_left_thruster -= 60.0;
fmul_bottom_right_thruster -= 60.0;
}
if player.input.down {
fmul_top_left_thruster += 60.0;
fmul_top_right_thruster += 60.0;
}
let rot = transform.rotation.to_euler(EulerRot::ZYX).0;
let thrusters = [
(fmul_bottom_left_thruster, -PART_HALF_SIZE, -PART_HALF_SIZE),
(fmul_bottom_right_thruster, PART_HALF_SIZE, -PART_HALF_SIZE),
(fmul_top_left_thruster, -PART_HALF_SIZE, PART_HALF_SIZE),
(fmul_top_right_thruster, PART_HALF_SIZE, PART_HALF_SIZE),
];
for (force_multiplier, x_offset, y_offset) in thrusters {
if force_multiplier != 0.0 {
let thruster_pos_uncast = vec2(x_offset / SCALE, y_offset / SCALE);
let thruster_pos_cast =
rot2d(thruster_pos_uncast, rot) + transform.translation.xy();
let thruster_force = force_multiplier * HEARTY_THRUSTER_FORCE;
let thruster_vec = vec2(
-thruster_force / SCALE * rot.sin(),
thruster_force / SCALE * rot.cos(),
);
let thruster_force = ExternalForce::at_point(
thruster_vec,
thruster_pos_cast,
transform.translation.xy(),
);
forces.force += thruster_force.force;
forces.torque += thruster_force.torque;
}
}
search_thrusters(
player.input,
attach.clone(),
*transform,
&mut attached_query,
);
}
}
fn search_thrusters(
input: Input,
attach: Attach,
p_transform: Transform,
attached_query: &mut Query<
(&Attach, &PartType, &mut ExternalForce, &Transform),
Without,
>,
) {
let p_angle = p_transform.rotation.to_euler(EulerRot::ZYX).0;
for child in attach.children {
if let Some(child) = child {
let (attach, part_type, mut force, transform) = attached_query.get_mut(child).unwrap();
let angle = transform.rotation.to_euler(EulerRot::ZYX).0;
let relative_angle = (p_angle - angle).abs();
let relative_pos = transform.translation - p_transform.translation;
let relative_pos = Vec2::new(
relative_pos
.x
.mul_add((-p_angle).cos(), -relative_pos.y * (-p_angle).sin()),
relative_pos
.x
.mul_add((-p_angle).sin(), relative_pos.y * (-p_angle).cos()),
);
let mut force_mult = 0.;
if *part_type == PartType::LandingThruster {
force_mult = LANDING_THRUSTER_FORCE;
}
if input.up {
if 3. * PI / 4. < relative_angle && relative_angle < 5. * PI / 4. {
let thruster_force = ExternalForce::at_point(
Vec2::new(
-force_mult / SCALE * angle.sin(),
force_mult / SCALE * angle.cos(),
),
transform.translation.xy(),
transform.translation.xy(),
);
force.force += thruster_force.force;
force.torque += thruster_force.torque;
}
}
if input.down {
if (0. < relative_angle && relative_angle < PI / 4.)
|| (7. * PI / 4. < relative_angle && relative_angle < 2. * PI)
{
let thruster_force = ExternalForce::at_point(
Vec2::new(
-force_mult / SCALE * angle.sin(),
force_mult / SCALE * angle.cos(),
),
transform.translation.xy(),
transform.translation.xy(),
);
force.force += thruster_force.force;
force.torque += thruster_force.torque;
}
}
if input.left {
if 3. * PI / 4. < relative_angle && relative_angle < 5. * PI / 4. {
if relative_pos.x > 24. / SCALE {
let thruster_force = ExternalForce::at_point(
Vec2::new(
-force_mult / SCALE * angle.sin(),
force_mult / SCALE * angle.cos(),
),
transform.translation.xy(),
transform.translation.xy(),
);
force.force += thruster_force.force;
force.torque += thruster_force.torque;
}
}
if (0. < relative_angle && relative_angle < PI / 4.)
|| (7. * PI / 4. < relative_angle && relative_angle < 2. * PI)
{
if relative_pos.x < -24. / SCALE {
let thruster_force = ExternalForce::at_point(
Vec2::new(
-force_mult / SCALE * angle.sin(),
force_mult / SCALE * angle.cos(),
),
transform.translation.xy(),
transform.translation.xy(),
);
force.force += thruster_force.force;
force.torque += thruster_force.torque;
}
}
if PI / 4. < relative_angle && relative_angle < 3. * PI / 4. {
if relative_pos.y < -24. / SCALE {
let thruster_force = ExternalForce::at_point(
Vec2::new(
-force_mult / SCALE * angle.sin(),
force_mult / SCALE * angle.cos(),
),
transform.translation.xy(),
transform.translation.xy(),
);
force.force += thruster_force.force;
force.torque += thruster_force.torque;
}
if -24. / SCALE < relative_pos.y && relative_pos.y < 24. / SCALE {
let thruster_force = ExternalForce::at_point(
Vec2::new(
-force_mult / SCALE * angle.sin(),
force_mult / SCALE * angle.cos(),
),
transform.translation.xy(),
transform.translation.xy(),
);
force.force += thruster_force.force;
force.torque += thruster_force.torque;
}
}
if 5. * PI / 4. < relative_angle && relative_angle < 7. * PI / 4. {
if relative_pos.y > 24. / SCALE {
let thruster_force = ExternalForce::at_point(
Vec2::new(
-force_mult / SCALE * angle.sin(),
force_mult / SCALE * angle.cos(),
),
transform.translation.xy(),
transform.translation.xy(),
);
force.force += thruster_force.force;
force.torque += thruster_force.torque;
}
if -24. / SCALE < relative_pos.y && relative_pos.y < 24. / SCALE {
let thruster_force = ExternalForce::at_point(
Vec2::new(
-force_mult / SCALE * angle.sin(),
force_mult / SCALE * angle.cos(),
),
transform.translation.xy(),
transform.translation.xy(),
);
force.force += thruster_force.force;
force.torque += thruster_force.torque;
}
}
}
if *part_type != PartType::LandingThruster {
search_thrusters(input, attach.clone(), p_transform, attached_query);
}
}
}
}
fn gravity_update(
mut part_query: Query<
(
&Transform,
&ReadMassProperties,
&mut ExternalForce,
&mut ExternalImpulse,
),
With,
>,
planet_query: Query<(&Transform, &ReadMassProperties), With>,
) {
for (part_transform, part_mp, mut forces, mut impulses) in &mut part_query {
impulses.impulse = Vec2::ZERO;
forces.force = Vec2::ZERO;
forces.torque = 0.;
let part_mp = part_mp.get();
let part_mass = part_mp.mass;
let part_translate = part_transform.translation;
for (planet_transform, planet_mp) in &planet_query {
let planet_mp = planet_mp.get();
let planet_mass = planet_mp.mass;
let planet_translate = planet_transform.translation;
let distance = planet_translate.distance(part_translate);
let force = GRAVITY * ((part_mass * planet_mass) / (distance * distance));
let direction = (planet_translate - part_translate).normalize() * force;
impulses.impulse += direction.xy();
}
}
}