~starkingdoms/starkingdoms

2ff032b8302daf309f9818173462bc26b0e12330 — ghostlyzsh 1 year, 11 months ago 8d3a996 + d3e61d6
Merge branch 'bevy_rewrite' of https://gitlab.com/starkingdoms.tk/starkingdoms.tk into bevy_rewrite
M server/src/component.rs => server/src/component.rs +6 -0
@@ 86,10 86,16 @@ pub struct PlanetBundle {
    pub transform: TransformBundle,
}

#[derive(Component, Copy, Clone)]
pub struct PartFlags {
    pub attached: bool,
}

#[derive(Bundle)]
pub struct PartBundle {
    pub transform: TransformBundle,
    pub part_type: PartType,
    pub flags: PartFlags,
}

#[derive(Bundle)]

M server/src/main.rs => server/src/main.rs +69 -19
@@ 170,9 170,11 @@ fn module_spawn(
        );
        transform.rotate_z(angle);
        if part_query.iter().count() < FREE_MODULE_CAP {
            let flags = PartFlags { attached: false };
            let mut entity = commands.spawn(PartBundle {
                part_type: PartType::Cargo,
                transform: TransformBundle::from(transform),
                flags,
            });
            entity
                .insert(RigidBody::Dynamic)


@@ 200,6 202,7 @@ fn module_spawn(
                part: Part {
                    part_type: PartType::Cargo,
                    transform: proto_transform!(transform),
                    flags: proto_part_flags!(flags),
                },
            };
            let buf = serde_json::to_vec(&packet).unwrap();


@@ 219,6 222,7 @@ fn on_message(
            &mut Transform,
            &mut Velocity,
            Option<&LooseAttach>,
            &mut PartFlags,
        ),
        (Without<PlanetType>, Without<Player>, Without<Attach>),
    >,


@@ 231,6 235,7 @@ fn on_message(
            &Velocity,
            Option<&CanAttach>,
            Option<&LooseAttach>,
            &mut PartFlags,
        ),
        (Without<PlanetType>, Without<Player>),
    >,


@@ 283,6 288,7 @@ fn on_message(
                            part: PartBundle {
                                part_type: PartType::Hearty,
                                transform: TransformBundle::from(transform),
                                flags: PartFlags { attached: false },
                            },
                            player: Player {
                                addr: *addr,


@@ 366,7 372,7 @@ fn on_message(

                    // tell the player where parts are
                    let mut parts = Vec::new();
                    for (entity, part_type, transform, _, _) in &part_query {
                    for (entity, part_type, transform, _, _, flags) in &part_query {
                        parts.push((
                            entity.index(),
                            Part {


@@ 374,10 380,11 @@ fn on_message(
                                transform: proto_transform!(Transform::from_translation(
                                    transform.translation * SCALE
                                )),
                                flags: proto_part_flags!(flags),
                            },
                        ));
                    }
                    for (entity, part_type, transform, _, _, _, _) in &attached_query {
                    for (entity, part_type, transform, _, _, _, _, flags) in &attached_query {
                        parts.push((
                            entity.index(),
                            Part {


@@ 385,6 392,7 @@ fn on_message(
                                transform: proto_transform!(Transform::from_translation(
                                    transform.translation * SCALE
                                )),
                                flags: proto_part_flags!(flags),
                            },
                        ));
                    }


@@ 396,6 404,7 @@ fn on_message(
                                transform.translation * SCALE
                            )
                            .with_rotation(transform.rotation)),
                            flags: ProtoPartFlags { attached: false },
                        },
                    ));
                    let packet = Packet::PartPositions { parts };


@@ 507,6 516,7 @@ fn on_message(
                                        module.2.rotation =
                                            Quat::from_euler(EulerRot::ZYX, angle, 0., 0.);
                                        module.3.linvel = velocity.linvel;
                                        module.5.attached = true;
                                        let joint = FixedJointBuilder::new()
                                            .local_anchor1(vec2(0. / SCALE, -53. / SCALE));
                                        let mut children = [None, None, None, None];


@@ 560,6 570,7 @@ fn on_message(
                                        module.2.rotation =
                                            Quat::from_euler(EulerRot::ZYX, angle + PI, 0., 0.);
                                        module.3.linvel = velocity.linvel;
                                        module.5.attached = true;
                                        let joint = FixedJointBuilder::new()
                                            .local_anchor1(vec2(0. / SCALE, 53. / SCALE));
                                        let mut children = [None, None, None, None];


@@ 617,6 628,7 @@ fn on_message(
                                            0.,
                                        );
                                        module.3.linvel = velocity.linvel;
                                        module.5.attached = true;
                                        let joint = FixedJointBuilder::new()
                                            .local_anchor1(vec2(53. / SCALE, 0. / SCALE))
                                            .local_basis2(std::f32::consts::PI / 2.);


@@ 679,6 691,7 @@ fn on_message(
                                            0.,
                                        );
                                        module.3.linvel = velocity.linvel;
                                        module.5.attached = true;
                                        let joint = FixedJointBuilder::new()
                                            .local_anchor1(vec2(-53. / SCALE, 0. / SCALE))
                                            .local_basis2(-std::f32::consts::PI / 2.);


@@ 725,12 738,13 @@ fn on_message(
                                        break;
                                    }
                                } else if attached_query.contains(select) {
                                    let module = attached_query.get(select).unwrap();
                                    let mut module = attached_query.get_mut(select).unwrap();
                                    let parent = module.3.parent.unwrap();
                                    commands.entity(select).remove::<ImpulseJoint>();
                                    commands.entity(select).remove::<Attach>();
                                    let children_attach = module.3.clone();
                                    if *module.1 == PartType::LandingThruster {
                                        module.7.attached = false;
                                        commands.entity(select).insert(LooseAttach {
                                            children: module.3.children,
                                        });


@@ 738,6 752,7 @@ fn on_message(
                                            .entity(module.3.children[2].unwrap())
                                            .remove::<Attach>();
                                    } else {
                                        module.7.attached = false;
                                        detach_recursive(
                                            &mut commands,
                                            module.3.clone(),


@@ 793,6 808,8 @@ fn on_message(
                                    &mut attached_query,
                                    &mut part_query,
                                ) {
                                    let mut part = part_query.get_mut(select).unwrap();
                                    part.5.attached = true; // all of this code is cursed. what the hell is it actually doing
                                    break;
                                }
                                // move module to cursor since no attach


@@ 807,7 824,7 @@ fn on_message(
                                }
                                break;
                            }
                            for (entity, part_type, transform, _m_attach, _velocity, _, _) in
                            for (entity, part_type, transform, _m_attach, _velocity, _, _, _) in
                                &attached_query
                            {
                                if *part_type == PartType::LandingThrusterSuspension {


@@ 837,7 854,7 @@ fn on_message(
                                    }
                                }
                            }
                            for (entity, part_type, transform, _, _) in &part_query {
                            for (entity, part_type, transform, _, _, _) in &part_query {
                                if *part_type == PartType::LandingThrusterSuspension {
                                    continue;
                                }


@@ 939,6 956,7 @@ fn detach_recursive(
            &Velocity,
            Option<&CanAttach>,
            Option<&LooseAttach>,
            &mut PartFlags,
        ),
        (Without<PlanetType>, Without<Player>),
    >,


@@ 946,8 964,8 @@ fn detach_recursive(
    for child in attach.children {
        if let Some(child) = child {
            {
                let (entity, part_type, _transform, attach, _velocity, _, _) =
                    attached_query.get(child).unwrap();
                let (entity, part_type, _transform, attach, _velocity, _, _, mut flags) =
                    attached_query.get_mut(child).unwrap();
                commands.entity(entity).remove::<Attach>();
                if *part_type == PartType::LandingThruster {
                    commands.entity(entity).insert(LooseAttach {


@@ 956,8 974,10 @@ fn detach_recursive(
                    commands
                        .entity(attach.children[2].unwrap())
                        .remove::<Attach>();
                    flags.attached = false;
                    continue;
                } else if *part_type == PartType::LandingThrusterSuspension {
                    flags.attached = false;
                    let parent = attach.parent.unwrap();
                    let parent_attach = attached_query.get(parent).unwrap().3;
                    println!("suspension {:?} {:?}", parent_attach.children, entity);


@@ 965,12 985,14 @@ fn detach_recursive(
                        children: parent_attach.children,
                    });
                } else {
                    flags.attached = false;
                    commands.entity(entity).remove::<ImpulseJoint>();
                    detach_recursive(commands, attach.clone(), attached_query);
                }
            }
            let (entity, _part_type, _transform, attach, _velocity, _, _) =
            let (entity, _part_type, _transform, attach, _velocity, _, _, mut flags) =
                attached_query.get_mut(child).unwrap();
            flags.attached = false;
            let parent = attach.parent.unwrap();
            if attached_query.contains(parent) {
                let mut parent_attach = attached_query.get_mut(parent).unwrap().3;


@@ 1002,6 1024,7 @@ fn attach_on_module_tree(
            &Velocity,
            Option<&CanAttach>,
            Option<&LooseAttach>,
            &mut PartFlags,
        ),
        (Without<PlanetType>, Without<Player>),
    >,


@@ 1012,6 1035,7 @@ fn attach_on_module_tree(
            &mut Transform,
            &mut Velocity,
            Option<&LooseAttach>,
            &mut PartFlags,
        ),
        (Without<PlanetType>, Without<Player>, Without<Attach>),
    >,


@@ 1019,7 1043,7 @@ fn attach_on_module_tree(
    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) =
            let (entity, _part_type, transform, mut attach, velocity, can_attach, loose_attach, _) =
                attached_query.get_mut(child).unwrap();

            let p_pos = transform.translation;


@@ 1068,6 1092,7 @@ fn attach_on_module_tree(
                    children,
                });
                attach.children[2] = Some(module.0);
                module.5.attached = true;
                return true;
            } else if attach.children[1] == None
                && attachable


@@ 1109,6 1134,7 @@ fn attach_on_module_tree(
                    children,
                });
                attach.children[1] = Some(module.0);
                module.5.attached = true;
                return true;
            } else if attach.children[3] == None
                && attachable


@@ 1150,6 1176,7 @@ fn attach_on_module_tree(
                    children,
                });
                attach.children[3] = Some(module.0);
                module.5.attached = true;
                return true;
            }
            ret = ret


@@ 1177,7 1204,14 @@ fn convert_modules(
    planet_query: Query<(Entity, &PlanetType, &Children)>,
    player_query: Query<&Attach, With<Player>>,
    mut attached_query: Query<
        (Entity, &mut PartType, &mut Attach, &Children, &Transform),
        (
            Entity,
            &mut PartType,
            &mut Attach,
            &Children,
            &Transform,
            &PartFlags,
        ),
        Without<Player>,
    >,
    mut collider_query: Query<


@@ 1239,7 1273,14 @@ fn convert_modules_recursive(
    planet_type: PlanetType,
    attach: Attach,
    attached_query: &mut Query<
        (Entity, &mut PartType, &mut Attach, &Children, &Transform),
        (
            Entity,
            &mut PartType,
            &mut Attach,
            &Children,
            &Transform,
            &PartFlags,
        ),
        Without<Player>,
    >,
    collider_query: &mut Query<


@@ 1250,7 1291,7 @@ fn convert_modules_recursive(
) {
    for child in attach.children {
        if let Some(child) = child {
            let (module_entity, mut part_type, mut attach, children, module_transform) =
            let (module_entity, mut part_type, mut attach, children, module_transform, part_flags) =
                attached_query.get_mut(child).unwrap();
            if *part_type == PartType::Cargo {
                match planet_type {


@@ 1278,6 1319,7 @@ fn convert_modules_recursive(
                            part: Part {
                                part_type: PartType::Hub,
                                transform: proto_transform!(transform),
                                flags: proto_part_flags!(part_flags),
                            },
                        };
                        let buf = serde_json::to_vec(&packet).unwrap();


@@ 1300,6 1342,7 @@ fn convert_modules_recursive(
                        let mut suspension = commands.spawn(PartBundle {
                            transform: TransformBundle::from(*module_transform),
                            part_type: PartType::LandingThrusterSuspension,
                            flags: PartFlags { attached: false },
                        });
                        suspension
                            .insert(RigidBody::Dynamic)


@@ 1338,6 1381,7 @@ fn convert_modules_recursive(
                            part: Part {
                                part_type: PartType::LandingThruster,
                                transform: proto_transform!(transform),
                                flags: proto_part_flags!(part_flags),
                            },
                        };
                        let buf = serde_json::to_vec(&packet).unwrap();


@@ 1349,6 1393,7 @@ fn convert_modules_recursive(
                            part: Part {
                                part_type: PartType::LandingThrusterSuspension,
                                transform: proto_transform!(transform),
                                flags: proto_part_flags!(part_flags),
                            },
                        };
                        let buf = serde_json::to_vec(&packet).unwrap();


@@ 1383,6 1428,7 @@ fn break_modules(
            &Velocity,
            Option<&CanAttach>,
            Option<&LooseAttach>,
            &mut PartFlags,
        ),
        (Without<PlanetType>, Without<Player>),
    >,


@@ 1390,13 1436,14 @@ fn break_modules(
) {
    let joints = rapier_context.entity2impulse_joint();
    let mut detach_list = Vec::new();
    for (entity, part_type, _, attach, _, _, _) in &mut attached_query {
    for (entity, part_type, _, attach, _, _, _, mut flags) in &mut attached_query {
        if *part_type == PartType::LandingThrusterSuspension {
            continue;
        }
        let handle = joints.get(&entity).unwrap();
        let joint = rapier_context.impulse_joints.get(*handle).unwrap();
        if joint.impulses.magnitude() > 0.00005 {
        if joint.impulses.magnitude() > 0.0001 {
            flags.attached = false;
            detach_list.push((entity, *part_type, attach.clone()));
        }
    }


@@ 1407,9 1454,11 @@ fn break_modules(
            commands.entity(entity).insert(LooseAttach {
                children: attach.children,
            });
            commands
                .entity(attach.children[2].unwrap())
                .remove::<Attach>();
            if (attach.children[2].is_some()) {
                commands
                    .entity(attach.children[2].unwrap())
                    .remove::<Attach>();
            }
        } else {
            detach_recursive(&mut commands, attach.clone(), &mut attached_query);
        }


@@ 1556,12 1605,12 @@ fn despawn_module_tree(

fn on_position_change(
    mut commands: Commands,
    part_query: Query<(Entity, &PartType, &Transform), Changed<Transform>>,
    part_query: Query<(Entity, &PartType, &Transform, &PartFlags), Changed<Transform>>,
    planet_query: Query<(Entity, &PlanetType, &Transform), Changed<Transform>>,
    mut packet_send: EventWriter<ServerEvent>,
) {
    let mut updated_parts = Vec::new();
    for (entity, part_type, transform) in part_query.iter() {
    for (entity, part_type, transform, flags) in part_query.iter() {
        let id = commands.entity(entity).id().index();
        updated_parts.push((
            id,


@@ 1571,6 1620,7 @@ fn on_position_change(
                    transform.translation * SCALE
                )
                .with_rotation(transform.rotation)),
                flags: proto_part_flags!(flags),
            },
        ));
    }

M server/src/packet.rs => server/src/packet.rs +15 -0
@@ 43,6 43,21 @@ pub struct Planet {
pub struct Part {
    pub part_type: PartType,
    pub transform: ProtoTransform,
    pub flags: ProtoPartFlags,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ProtoPartFlags {
    pub attached: bool,
}

#[macro_export]
macro_rules! proto_part_flags {
    ($e:expr) => {
        $crate::packet::ProtoPartFlags {
            attached: $e.attached,
        }
    };
}

#[derive(Debug, Serialize, Deserialize)]

M starkingdoms-client/src/globals.ts => starkingdoms-client/src/globals.ts +1 -0
@@ 28,6 28,7 @@ export interface GlobalRendering {
  player_text_map: Map<number, PIXI.Text>;
  planet_sprite_map: Map<number, PIXI.Sprite>;
  part_sprite_map: Map<number, PIXI.Sprite>;
  part_sprites_need_texture_change: number[];
}

export interface GlobalMe {

M starkingdoms-client/src/hub.ts => starkingdoms-client/src/hub.ts +33 -6
@@ 22,6 22,11 @@ import { part_texture_url } from "./textures.js";
import * as PIXI from "pixi.js";

const logger = createDebug("hub");
let hud = {
  x: 0,
  y: 0,
  next_poll: 0,
};

export interface ClientHub {
  socket: WebSocket;


@@ 36,6 41,9 @@ export async function hub_connect(
  url: string,
  username: string,
  chatbox: Chatbox,
  velocity: HTMLSpanElement,
  x_pos: HTMLSpanElement,
  y_pos: HTMLSpanElement,
): Promise<ClientHub | null> {
  logger("connecting to client hub at " + url);



@@ 203,14 211,33 @@ export async function hub_connect(
          let id = p.parts[i][0];
          let new_part = p.parts[i][1];

          let old_part = global.parts_map.get(id);
          if (
            old_part !== undefined &&
            (old_part.part_type !== new_part.part_type ||
              old_part.flags !== new_part.flags)
          ) {
            global.rendering?.part_sprites_need_texture_change.push(id);
          }

          global.parts_map.set(id, new_part);
          if (id === global.me?.part_id) {
            document.getElementById("pos-val-x")!.innerText = Math.round(
              new_part.transform.x,
            ).toString();
            document.getElementById("pos-val-y")!.innerText = Math.round(
              new_part.transform.y,
            ).toString();
            if (hud.next_poll <= 0) {
              velocity!.innerText = Math.round(
                Math.sqrt(
                  Math.pow(Math.abs(new_part.transform.x - hud.x), 2) +
                    Math.pow(Math.abs(new_part.transform.y - hud.y), 2),
                ),
              ).toString();
              hud.next_poll = 30;

              hud.x = new_part.transform.x;
              hud.y = new_part.transform.y;

              x_pos!.innerText = Math.round(new_part.transform.x).toString();
              y_pos!.innerText = Math.round(new_part.transform.y).toString();
            }
            hud.next_poll--;
          }
        }
      } else if (packet.t == PacketType.SpawnPart) {

M starkingdoms-client/src/pages/Play.svelte => starkingdoms-client/src/pages/Play.svelte +15 -4
@@ 10,9 10,13 @@
  import { onMount } from "svelte";
  import Popup from "../components/ui/Popup.svelte";
  import Checkbox from "../components/ui/Checkbox.svelte";
  import { global } from "../globals.ts";

  let config = DEFAULT_CONFIG;

  let velocity;
  let x_pos;
  let y_pos;
  let chatbox: Chatbox;

  const logger = createDebug("main");


@@ 64,7 68,14 @@

    let server = config.servers[server_id];

    await hub_connect(server.clientHubUrl, username, chatbox);
    await hub_connect(
      server.clientHubUrl,
      username,
      chatbox,
      velocity,
      x_pos,
      y_pos,
    );
  });
</script>



@@ 121,12 132,12 @@
      <tbody>
        <tr>
          <td id="pos">
            <span id="pos-val-x">--</span>
            <span id="pos-val-x" bind:this={y_pos}>--</span>
            ,
            <span id="pos-val-y">--</span>
            <span id="pos-val-y" bind:this={y_pos}>--</span>
          </td>
          <td id="velocity">
            <span id="velocity-val">--</span>
            <span id="velocity-val" bind:this={velocity}>--</span>
          </td>
          <td id="track">
            <span id="track-val">--</span>

M starkingdoms-client/src/protocol.ts => starkingdoms-client/src/protocol.ts +4 -0
@@ 28,6 28,10 @@ export interface Planet {
export interface Part {
  part_type: PartType;
  transform: ProtoTransform;
  flags: PartFlags;
}
export interface PartFlags {
  attached: boolean;
}
export interface ClientLoginPacket {
  username: string;

M starkingdoms-client/src/rendering.ts => starkingdoms-client/src/rendering.ts +10 -1
@@ 25,6 25,7 @@ export function startRender() {
    player_text_map: new Map(),
    planet_sprite_map: new Map(),
    part_sprite_map: new Map(),
    part_sprites_need_texture_change: [],
  };

  app.ticker.add(() => {


@@ 38,8 39,16 @@ export function startRender() {

      if (global.rendering!.part_sprite_map.has(id)) {
        part_sprite = global.rendering!.part_sprite_map.get(id)!;
        if (global.rendering!.part_sprites_need_texture_change.includes(id)) {
          // slow :(
          part_sprite.texture = PIXI.Texture.from(
            part_texture_url(part.part_type, part.flags.attached),
          );
        }
      } else {
        part_sprite = PIXI.Sprite.from(part_texture_url(part.part_type));
        part_sprite = PIXI.Sprite.from(
          part_texture_url(part.part_type, part.flags.attached),
        );
        global.rendering!.part_sprite_map.set(id, part_sprite);
        global.rendering!.app.stage.addChild(part_sprite);
      }

M starkingdoms-client/src/textures.ts => starkingdoms-client/src/textures.ts +8 -5
@@ 4,8 4,11 @@ import tex_moon from "./assets/moon.svg";
import tex_mars from "./assets/mars.svg";
import tex_hearty from "./assets/hearty.svg";
import tex_cargo_off from "./assets/cargo_off.svg";
import tex_cargo_on from "./assets/cargo_on.svg";
import tex_hub_off from "./assets/hub_off.svg";
import tex_landing_thruster from "./assets/landingthruster_off.svg";
import tex_hub_on from "./assets/hub_on.svg";
import tex_landing_thruster_off from "./assets/landingthruster_off.svg";
import tex_landing_thruster_on from "./assets/landingthruster_on.svg";
import tex_landing_thruster_suspension from "./assets/landingleg.svg";
import tex_missing from "./assets/missing.svg";



@@ 20,15 23,15 @@ export function planet_texture_url(type: PlanetType): string {
  return tex_missing;
}

export function part_texture_url(type: PartType): string {
export function part_texture_url(type: PartType, attached: boolean): string {
  if (type == PartType.Hearty) {
    return tex_hearty;
  } else if (type == PartType.Cargo) {
    return tex_cargo_off;
    return attached ? tex_cargo_on : tex_cargo_off;
  } else if (type == PartType.Hub) {
    return tex_hub_off;
    return attached ? tex_hub_on : tex_hub_off;
  } else if (type == PartType.LandingThruster) {
    return tex_landing_thruster;
    return attached ? tex_landing_thruster_on : tex_landing_thruster_off;
  } else if (type == PartType.LandingThrusterSuspension) {
    return tex_landing_thruster_suspension;
  }