fix warnings in rtsim

This commit is contained in:
Isse 2023-03-22 10:59:34 +01:00 committed by Joshua Barretto
parent adb2e1ba85
commit 7ac6c6b453
24 changed files with 98 additions and 96 deletions

View File

@ -747,9 +747,14 @@ impl ServerChatCommand {
ServerChatCommand::Lightning => { ServerChatCommand::Lightning => {
cmd(vec![], "Lightning strike at current position", Some(Admin)) cmd(vec![], "Lightning strike at current position", Some(Admin))
}, },
ServerChatCommand::Scale => { ServerChatCommand::Scale => cmd(
cmd(vec![Float("factor", 1.0, Required), Boolean("reset_mass", true.to_string(), Optional)], "Scale your character", Some(Admin)) vec![
}, Float("factor", 1.0, Required),
Boolean("reset_mass", true.to_string(), Optional),
],
"Scale your character",
Some(Admin),
),
} }
} }

View File

@ -81,38 +81,47 @@ impl NpcBuilder {
self.health = health.into(); self.health = health.into();
self self
} }
pub fn with_poise(mut self, poise: comp::Poise) -> Self { pub fn with_poise(mut self, poise: comp::Poise) -> Self {
self.poise = poise; self.poise = poise;
self self
} }
pub fn with_agent(mut self, agent: impl Into<Option<comp::Agent>>) -> Self { pub fn with_agent(mut self, agent: impl Into<Option<comp::Agent>>) -> Self {
self.agent = agent.into(); self.agent = agent.into();
self self
} }
pub fn with_anchor(mut self, anchor: comp::Anchor) -> Self { pub fn with_anchor(mut self, anchor: comp::Anchor) -> Self {
self.anchor = Some(anchor); self.anchor = Some(anchor);
self self
} }
pub fn with_rtsim(mut self, rtsim: RtSimEntity) -> Self { pub fn with_rtsim(mut self, rtsim: RtSimEntity) -> Self {
self.rtsim_entity = Some(rtsim); self.rtsim_entity = Some(rtsim);
self self
} }
pub fn with_projectile(mut self, projectile: impl Into<Option<comp::Projectile>>) -> Self { pub fn with_projectile(mut self, projectile: impl Into<Option<comp::Projectile>>) -> Self {
self.projectile = projectile.into(); self.projectile = projectile.into();
self self
} }
pub fn with_scale(mut self, scale: comp::Scale) -> Self { pub fn with_scale(mut self, scale: comp::Scale) -> Self {
self.scale = scale; self.scale = scale;
self self
} }
pub fn with_inventory(mut self, inventory: comp::Inventory) -> Self { pub fn with_inventory(mut self, inventory: comp::Inventory) -> Self {
self.inventory = inventory; self.inventory = inventory;
self self
} }
pub fn with_skill_set(mut self, skill_set: comp::SkillSet) -> Self { pub fn with_skill_set(mut self, skill_set: comp::SkillSet) -> Self {
self.skill_set = skill_set; self.skill_set = skill_set;
self self
} }
pub fn with_loot(mut self, loot: LootSpec<String>) -> Self { pub fn with_loot(mut self, loot: LootSpec<String>) -> Self {
self.loot = loot; self.loot = loot;
self self

View File

@ -7,8 +7,8 @@ use crate::{
}, },
lottery::LootSpec, lottery::LootSpec,
npc::{self, NPC_NAMES}, npc::{self, NPC_NAMES},
trade::SiteInformation,
rtsim, rtsim,
trade::SiteInformation,
}; };
use enum_map::EnumMap; use enum_map::EnumMap;
use serde::Deserialize; use serde::Deserialize;

View File

@ -3,8 +3,8 @@
// `Agent`). When possible, this should be moved to the `rtsim` // `Agent`). When possible, this should be moved to the `rtsim`
// module in `server`. // module in `server`.
use serde::{Deserialize, Serialize};
use specs::Component; use specs::Component;
use serde::{Serialize, Deserialize};
use vek::*; use vek::*;
use crate::comp::dialogue::MoodState; use crate::comp::dialogue::MoodState;

View File

@ -6,7 +6,7 @@ use crate::{
skillset::skills, skillset::skills,
Behavior, BehaviorCapability, CharacterState, Projectile, StateUpdate, Behavior, BehaviorCapability, CharacterState, Projectile, StateUpdate,
}, },
event::{LocalEvent, ServerEvent, NpcBuilder}, event::{LocalEvent, NpcBuilder, ServerEvent},
outcome::Outcome, outcome::Outcome,
skillset_builder::{self, SkillSetBuilder}, skillset_builder::{self, SkillSetBuilder},
states::{ states::{
@ -181,15 +181,15 @@ impl CharacterBehavior for Data {
.with_agent( .with_agent(
comp::Agent::from_body(&body) comp::Agent::from_body(&body)
.with_behavior(Behavior::from(BehaviorCapability::SPEAK)) .with_behavior(Behavior::from(BehaviorCapability::SPEAK))
.with_no_flee_if(true) .with_no_flee_if(true),
) )
.with_scale( .with_scale(
self self.static_data
.static_data
.summon_info .summon_info
.scale .scale
.unwrap_or(comp::Scale(1.0)) .unwrap_or(comp::Scale(1.0)),
).with_projectile(projectile) )
.with_projectile(projectile),
}); });
// Send local event used for frontend shenanigans // Send local event used for frontend shenanigans

View File

@ -5,8 +5,8 @@ use crate::{
item::{tool::AbilityMap, MaterialStatManifest}, item::{tool::AbilityMap, MaterialStatManifest},
ActiveAbilities, Beam, Body, CharacterState, Combo, ControlAction, Controller, ActiveAbilities, Beam, Body, CharacterState, Combo, ControlAction, Controller,
ControllerInputs, Density, Energy, Health, InputAttr, InputKind, Inventory, ControllerInputs, Density, Energy, Health, InputAttr, InputKind, Inventory,
InventoryAction, Mass, Melee, Ori, PhysicsState, Pos, SkillSet, Stance, StateUpdate, Stats, InventoryAction, Mass, Melee, Ori, PhysicsState, Pos, Scale, SkillSet, Stance, StateUpdate, Stats,
Vel, Scale, Vel,
}, },
link::Is, link::Is,
mounting::Rider, mounting::Rider,

View File

@ -76,7 +76,8 @@ impl CharacterBehavior for Data {
// They've climbed atop something, give them a boost // They've climbed atop something, give them a boost
output_events.emit_local(LocalEvent::Jump( output_events.emit_local(LocalEvent::Jump(
data.entity, data.entity,
CLIMB_BOOST_JUMP_FACTOR * impulse / data.mass.0 * data.scale.map_or(1.0, |s| s.0.powf(13.0).powf(0.25)), CLIMB_BOOST_JUMP_FACTOR * impulse / data.mass.0
* data.scale.map_or(1.0, |s| s.0.powf(13.0).powf(0.25)),
)); ));
}; };
update.character = CharacterState::Idle(idle::Data::default()); update.character = CharacterState::Idle(idle::Data::default());
@ -122,10 +123,14 @@ impl CharacterBehavior for Data {
// Apply Vertical Climbing Movement // Apply Vertical Climbing Movement
match climb { match climb {
Climb::Down => { Climb::Down => {
update.vel.0.z += data.dt.0 * (GRAVITY - self.static_data.movement_speed.powi(2) * data.scale.map_or(1.0, |s| s.0)) update.vel.0.z += data.dt.0
* (GRAVITY
- self.static_data.movement_speed.powi(2) * data.scale.map_or(1.0, |s| s.0))
}, },
Climb::Up => { Climb::Up => {
update.vel.0.z += data.dt.0 * (GRAVITY + self.static_data.movement_speed.powi(2) * data.scale.map_or(1.0, |s| s.0)) update.vel.0.z += data.dt.0
* (GRAVITY
+ self.static_data.movement_speed.powi(2) * data.scale.map_or(1.0, |s| s.0))
}, },
Climb::Hold => update.vel.0.z += data.dt.0 * GRAVITY, Climb::Hold => update.vel.0.z += data.dt.0 * GRAVITY,
} }

View File

@ -388,7 +388,8 @@ fn basic_move(data: &JoinData<'_>, update: &mut StateUpdate, efficiency: f32) {
data.body.base_accel() data.body.base_accel()
* data.scale.map_or(1.0, |s| s.0.sqrt()) * data.scale.map_or(1.0, |s| s.0.sqrt())
* block.get_traction() * block.get_traction()
* block.get_friction() / FRIC_GROUND * block.get_friction()
/ FRIC_GROUND
} else { } else {
data.body.air_accel() data.body.air_accel()
} * efficiency; } * efficiency;
@ -437,8 +438,11 @@ pub fn handle_forced_movement(
// FRIC_GROUND temporarily used to normalize things around expected values // FRIC_GROUND temporarily used to normalize things around expected values
data.body.base_accel() * block.get_traction() * block.get_friction() / FRIC_GROUND data.body.base_accel() * block.get_traction() * block.get_friction() / FRIC_GROUND
}) { }) {
update.vel.0 += update.vel.0 += Vec2::broadcast(data.dt.0)
Vec2::broadcast(data.dt.0) * accel * data.scale.map_or(1.0, |s| s.0.sqrt()) * Vec2::from(*data.ori) * strength; * accel
* data.scale.map_or(1.0, |s| s.0.sqrt())
* Vec2::from(*data.ori)
* strength;
} }
}, },
ForcedMovement::Reverse(strength) => { ForcedMovement::Reverse(strength) => {
@ -447,8 +451,11 @@ pub fn handle_forced_movement(
// FRIC_GROUND temporarily used to normalize things around expected values // FRIC_GROUND temporarily used to normalize things around expected values
data.body.base_accel() * block.get_traction() * block.get_friction() / FRIC_GROUND data.body.base_accel() * block.get_traction() * block.get_friction() / FRIC_GROUND
}) { }) {
update.vel.0 += update.vel.0 += Vec2::broadcast(data.dt.0)
Vec2::broadcast(data.dt.0) * accel * data.scale.map_or(1.0, |s| s.0.sqrt()) * -Vec2::from(*data.ori) * strength; * accel
* data.scale.map_or(1.0, |s| s.0.sqrt())
* -Vec2::from(*data.ori)
* strength;
} }
}, },
ForcedMovement::Sideways(strength) => { ForcedMovement::Sideways(strength) => {
@ -470,7 +477,11 @@ pub fn handle_forced_movement(
} }
}; };
update.vel.0 += Vec2::broadcast(data.dt.0) * accel * data.scale.map_or(1.0, |s| s.0.sqrt()) * direction * strength; update.vel.0 += Vec2::broadcast(data.dt.0)
* accel
* data.scale.map_or(1.0, |s| s.0.sqrt())
* direction
* strength;
} }
}, },
ForcedMovement::DirectedReverse(strength) => { ForcedMovement::DirectedReverse(strength) => {
@ -532,7 +543,8 @@ pub fn handle_forced_movement(
* (1.0 - data.inputs.look_dir.z.abs()); * (1.0 - data.inputs.look_dir.z.abs());
}, },
ForcedMovement::Hover { move_input } => { ForcedMovement::Hover { move_input } => {
update.vel.0 = Vec3::new(data.vel.0.x, data.vel.0.y, 0.0) + move_input update.vel.0 = Vec3::new(data.vel.0.x, data.vel.0.y, 0.0)
+ move_input
* data.scale.map_or(1.0, |s| s.0.sqrt()) * data.scale.map_or(1.0, |s| s.0.sqrt())
* data.inputs.move_dir.try_normalized().unwrap_or_default(); * data.inputs.move_dir.try_normalized().unwrap_or_default();
}, },
@ -574,8 +586,7 @@ pub fn handle_orientation(
.map_or_else(|| to_horizontal_fast(data.ori), |dir| dir.into()) .map_or_else(|| to_horizontal_fast(data.ori), |dir| dir.into())
}; };
// unit is multiples of 180° // unit is multiples of 180°
let half_turns_per_tick = data.body.base_ori_rate() let half_turns_per_tick = data.body.base_ori_rate() / data.scale.map_or(1.0, |s| s.0.sqrt())
/ data.scale.map_or(1.0, |s| s.0.sqrt())
* efficiency * efficiency
* if data.physics.on_ground.is_some() { * if data.physics.on_ground.is_some() {
1.0 1.0

View File

@ -3,8 +3,7 @@ use crate::{
comp::{fluid_dynamics::LiquidKind, tool::ToolKind}, comp::{fluid_dynamics::LiquidKind, tool::ToolKind},
consts::FRIC_GROUND, consts::FRIC_GROUND,
lottery::LootSpec, lottery::LootSpec,
make_case_elim, make_case_elim, rtsim,
rtsim,
}; };
use num_derive::FromPrimitive; use num_derive::FromPrimitive;
use num_traits::FromPrimitive; use num_traits::FromPrimitive;
@ -196,7 +195,9 @@ impl Block {
} }
} }
/// Returns the rtsim resource, if any, that this block corresponds to. If you want the scarcity of a block to change with rtsim's resource depletion tracking, you can do so by editing this function. /// Returns the rtsim resource, if any, that this block corresponds to. If
/// you want the scarcity of a block to change with rtsim's resource
/// depletion tracking, you can do so by editing this function.
#[inline] #[inline]
pub fn get_rtsim_resource(&self) -> Option<rtsim::ChunkResource> { pub fn get_rtsim_resource(&self) -> Option<rtsim::ChunkResource> {
match self.get_sprite()? { match self.get_sprite()? {

View File

@ -240,7 +240,7 @@ impl<R: Send + Sync + 'static, F: FnMut(&mut NpcCtx) -> A + Send + Sync + 'stati
Action<R> for Now<F, A> Action<R> for Now<F, A>
{ {
// TODO: This doesn't compare?! // TODO: This doesn't compare?!
fn is_same(&self, other: &Self) -> bool { true } fn is_same(&self, _other: &Self) -> bool { true }
fn dyn_is_same(&self, other: &dyn Action<R>) -> bool { self.dyn_is_same_sized(other) } fn dyn_is_same(&self, other: &dyn Action<R>) -> bool { self.dyn_is_same_sized(other) }
@ -293,7 +293,7 @@ impl<
> Action<()> for Until<F, A, R> > Action<()> for Until<F, A, R>
{ {
// TODO: This doesn't compare?! // TODO: This doesn't compare?!
fn is_same(&self, other: &Self) -> bool { true } fn is_same(&self, _other: &Self) -> bool { true }
fn dyn_is_same(&self, other: &dyn Action<()>) -> bool { self.dyn_is_same_sized(other) } fn dyn_is_same(&self, other: &dyn Action<()>) -> bool { self.dyn_is_same_sized(other) }
@ -345,11 +345,11 @@ pub struct Just<F, R = ()>(F, PhantomData<R>);
impl<R: Send + Sync + 'static, F: FnMut(&mut NpcCtx) -> R + Send + Sync + 'static> Action<R> impl<R: Send + Sync + 'static, F: FnMut(&mut NpcCtx) -> R + Send + Sync + 'static> Action<R>
for Just<F, R> for Just<F, R>
{ {
fn is_same(&self, other: &Self) -> bool { true } fn is_same(&self, _other: &Self) -> bool { true }
fn dyn_is_same(&self, other: &dyn Action<R>) -> bool { self.dyn_is_same_sized(other) } fn dyn_is_same(&self, other: &dyn Action<R>) -> bool { self.dyn_is_same_sized(other) }
fn backtrace(&self, bt: &mut Vec<String>) {} fn backtrace(&self, _bt: &mut Vec<String>) {}
// TODO: Reset closure? // TODO: Reset closure?
fn reset(&mut self) {} fn reset(&mut self) {}
@ -369,7 +369,7 @@ impl<R: Send + Sync + 'static, F: FnMut(&mut NpcCtx) -> R + Send + Sync + 'stati
/// // Make the current NPC say 'Hello, world!' exactly once /// // Make the current NPC say 'Hello, world!' exactly once
/// just(|ctx| ctx.controller.say("Hello, world!")) /// just(|ctx| ctx.controller.say("Hello, world!"))
/// ``` /// ```
pub fn just<F, R: Send + Sync + 'static>(mut f: F) -> Just<F, R> pub fn just<F, R: Send + Sync + 'static>(f: F) -> Just<F, R>
where where
F: FnMut(&mut NpcCtx) -> R + Send + Sync + 'static, F: FnMut(&mut NpcCtx) -> R + Send + Sync + 'static,
{ {
@ -383,15 +383,15 @@ where
pub struct Finish; pub struct Finish;
impl Action<()> for Finish { impl Action<()> for Finish {
fn is_same(&self, other: &Self) -> bool { true } fn is_same(&self, _other: &Self) -> bool { true }
fn dyn_is_same(&self, other: &dyn Action<()>) -> bool { self.dyn_is_same_sized(other) } fn dyn_is_same(&self, other: &dyn Action<()>) -> bool { self.dyn_is_same_sized(other) }
fn backtrace(&self, bt: &mut Vec<String>) {} fn backtrace(&self, _bt: &mut Vec<String>) {}
fn reset(&mut self) {} fn reset(&mut self) {}
fn tick(&mut self, ctx: &mut NpcCtx) -> ControlFlow<()> { ControlFlow::Break(()) } fn tick(&mut self, _ctx: &mut NpcCtx) -> ControlFlow<()> { ControlFlow::Break(()) }
} }
/// An action that immediately finishes without doing anything. /// An action that immediately finishes without doing anything.
@ -443,7 +443,7 @@ pub struct Tree<F, R> {
impl<F: FnMut(&mut NpcCtx) -> Node<R> + Send + Sync + 'static, R: 'static> Action<R> impl<F: FnMut(&mut NpcCtx) -> Node<R> + Send + Sync + 'static, R: 'static> Action<R>
for Tree<F, R> for Tree<F, R>
{ {
fn is_same(&self, other: &Self) -> bool { true } fn is_same(&self, _other: &Self) -> bool { true }
fn dyn_is_same(&self, other: &dyn Action<R>) -> bool { self.dyn_is_same_sized(other) } fn dyn_is_same(&self, other: &dyn Action<R>) -> bool { self.dyn_is_same_sized(other) }
@ -626,7 +626,7 @@ pub struct Sequence<I, A, R = ()>(I, I, Option<A>, PhantomData<R>);
impl<R: Send + Sync + 'static, I: Iterator<Item = A> + Clone + Send + Sync + 'static, A: Action<R>> impl<R: Send + Sync + 'static, I: Iterator<Item = A> + Clone + Send + Sync + 'static, A: Action<R>>
Action<()> for Sequence<I, A, R> Action<()> for Sequence<I, A, R>
{ {
fn is_same(&self, other: &Self) -> bool { true } fn is_same(&self, _other: &Self) -> bool { true }
fn dyn_is_same(&self, other: &dyn Action<()>) -> bool { self.dyn_is_same_sized(other) } fn dyn_is_same(&self, other: &dyn Action<()>) -> bool { self.dyn_is_same_sized(other) }

View File

@ -1,7 +1,5 @@
use super::Actor; use super::Actor;
pub use common::rtsim::FactionId; pub use common::rtsim::FactionId;
use common::{store::Id, uid::Uid};
use hashbrown::HashMap;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use slotmap::HopSlotMap; use slotmap::HopSlotMap;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};

View File

@ -12,10 +12,7 @@ pub use self::{
use common::resources::TimeOfDay; use common::resources::TimeOfDay;
use enum_map::{enum_map, EnumArray, EnumMap}; use enum_map::{enum_map, EnumArray, EnumMap};
use serde::{ use serde::{de, ser, Deserialize, Serialize};
de::{self, Error as _},
ser, Deserialize, Serialize,
};
use std::{ use std::{
cmp::PartialEq, cmp::PartialEq,
fmt, fmt,
@ -81,7 +78,7 @@ fn rugged_ser_enum_map<
) -> Result<S::Ok, S::Error> { ) -> Result<S::Ok, S::Error> {
ser.collect_map( ser.collect_map(
map.iter() map.iter()
.filter(|(k, v)| v != &&V::from(DEFAULT)) .filter(|(_, v)| v != &&V::from(DEFAULT))
.map(|(k, v)| (k, v)), .map(|(k, v)| (k, v)),
) )
} }
@ -93,7 +90,7 @@ fn rugged_de_enum_map<
D: de::Deserializer<'a>, D: de::Deserializer<'a>,
const DEFAULT: i16, const DEFAULT: i16,
>( >(
mut de: D, de: D,
) -> Result<EnumMap<K, V>, D::Error> { ) -> Result<EnumMap<K, V>, D::Error> {
struct Visitor<K, V, const DEFAULT: i16>(PhantomData<(K, V)>); struct Visitor<K, V, const DEFAULT: i16>(PhantomData<(K, V)>);

View File

@ -18,7 +18,7 @@ pub struct Nature {
impl Nature { impl Nature {
pub fn generate(world: &World) -> Self { pub fn generate(world: &World) -> Self {
Self { Self {
chunks: Grid::populate_from(world.sim().get_size().map(|e| e as i32), |pos| Chunk { chunks: Grid::populate_from(world.sim().get_size().map(|e| e as i32), |_| Chunk {
res: EnumMap::<_, f32>::default().map(|_, _| 1.0), res: EnumMap::<_, f32>::default().map(|_, _| 1.0),
}), }),
} }

View File

@ -1,25 +1,18 @@
use crate::ai::{Action, NpcCtx}; use crate::ai::Action;
pub use common::rtsim::{NpcId, Profession}; pub use common::rtsim::{NpcId, Profession};
use common::{ use common::{
comp, comp,
grid::Grid, grid::Grid,
rtsim::{FactionId, RtSimController, SiteId, VehicleId}, rtsim::{FactionId, SiteId, VehicleId},
store::Id, store::Id,
uid::Uid,
vol::RectVolSize, vol::RectVolSize,
}; };
use hashbrown::HashMap;
use rand::prelude::*; use rand::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use slotmap::HopSlotMap; use slotmap::HopSlotMap;
use std::{ use std::{
collections::VecDeque, collections::VecDeque,
ops::{Deref, DerefMut, Generator, GeneratorState}, ops::{Deref, DerefMut},
pin::Pin,
sync::{
atomic::{AtomicPtr, Ordering},
Arc,
},
}; };
use vek::*; use vek::*;
use world::{ use world::{

View File

@ -2,7 +2,6 @@ pub use common::rtsim::SiteId;
use common::{ use common::{
rtsim::{FactionId, NpcId}, rtsim::{FactionId, NpcId},
store::Id, store::Id,
uid::Uid,
}; };
use hashbrown::{HashMap, HashSet}; use hashbrown::{HashMap, HashSet};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};

View File

@ -1,10 +1,9 @@
use crate::data::Faction; use crate::data::Faction;
use rand::prelude::*; use rand::prelude::*;
use vek::*;
use world::{IndexRef, World}; use world::{IndexRef, World};
impl Faction { impl Faction {
pub fn generate(world: &World, index: IndexRef, rng: &mut impl Rng) -> Self { pub fn generate(_world: &World, _index: IndexRef, rng: &mut impl Rng) -> Self {
Self { Self {
leader: None, leader: None,
good_or_evil: rng.gen(), good_or_evil: rng.gen(),

View File

@ -3,7 +3,7 @@ pub mod site;
use crate::data::{ use crate::data::{
faction::{Faction, Factions}, faction::{Faction, Factions},
npc::{Npc, Npcs, Profession, Vehicle, VehicleKind}, npc::{Npc, Npcs, Profession, Vehicle},
site::{Site, Sites}, site::{Site, Sites},
Data, Nature, Data, Nature,
}; };
@ -15,7 +15,6 @@ use common::{
terrain::TerrainChunkSize, terrain::TerrainChunkSize,
vol::RectVolSize, vol::RectVolSize,
}; };
use hashbrown::HashMap;
use rand::prelude::*; use rand::prelude::*;
use tracing::info; use tracing::info;
use vek::*; use vek::*;

View File

@ -10,7 +10,7 @@ use world::{
impl Site { impl Site {
pub fn generate( pub fn generate(
world_site_id: Id<WorldSite>, world_site_id: Id<WorldSite>,
world: &World, _world: &World,
index: IndexRef, index: IndexRef,
nearby_factions: &[(Vec2<i32>, FactionId)], nearby_factions: &[(Vec2<i32>, FactionId)],
factions: &Factions, factions: &Factions,

View File

@ -1,5 +1,4 @@
#![feature( #![feature(
generic_associated_types,
never_type, never_type,
try_blocks, try_blocks,
generator_trait, generator_trait,
@ -91,7 +90,7 @@ impl RtState {
pub fn bind<R: Rule, E: Event>( pub fn bind<R: Rule, E: Event>(
&mut self, &mut self,
mut f: impl FnMut(EventCtx<R, E>) + Send + Sync + 'static, f: impl FnMut(EventCtx<R, E>) + Send + Sync + 'static,
) { ) {
let f = AtomicRefCell::new(f); let f = AtomicRefCell::new(f);
self.event_handlers self.event_handlers

View File

@ -1,13 +1,13 @@
use std::{collections::VecDeque, hash::BuildHasherDefault}; use std::hash::BuildHasherDefault;
use crate::{ use crate::{
ai::{casual, choose, finish, important, just, now, seq, until, urgent, watch, Action, NpcCtx}, ai::{casual, choose, finish, important, just, now, seq, until, urgent, Action, NpcCtx},
data::{ data::{
npc::{Brain, Controller, Npc, NpcId, PathData, PathingMemory, VehicleKind}, npc::{Brain, Controller, PathData},
Sites, Sites,
}, },
event::OnTick, event::OnTick,
EventCtx, RtState, Rule, RuleError, RtState, Rule, RuleError,
}; };
use common::{ use common::{
astar::{Astar, PathResult}, astar::{Astar, PathResult},
@ -22,11 +22,6 @@ use fxhash::FxHasher64;
use itertools::Itertools; use itertools::Itertools;
use rand::prelude::*; use rand::prelude::*;
use rayon::iter::{IntoParallelRefMutIterator, ParallelIterator}; use rayon::iter::{IntoParallelRefMutIterator, ParallelIterator};
use std::{
any::{Any, TypeId},
marker::PhantomData,
ops::ControlFlow,
};
use vek::*; use vek::*;
use world::{ use world::{
civ::{self, Track}, civ::{self, Track},
@ -212,11 +207,9 @@ fn path_towns(
} }
} }
const MAX_STEP: f32 = 32.0;
impl Rule for NpcAi { impl Rule for NpcAi {
fn start(rtstate: &mut RtState) -> Result<Self, RuleError> { fn start(rtstate: &mut RtState) -> Result<Self, RuleError> {
rtstate.bind::<Self, OnTick>(|mut ctx| { rtstate.bind::<Self, OnTick>(|ctx| {
let mut npc_data = { let mut npc_data = {
let mut data = ctx.state.data_mut(); let mut data = ctx.state.data_mut();
data.npcs data.npcs
@ -351,8 +344,6 @@ fn goto(wpos: Vec3<f32>, speed_factor: f32, goal_dist: f32) -> impl Action {
/// Try to walk toward a 2D position on the terrain without caring for /// Try to walk toward a 2D position on the terrain without caring for
/// obstacles. /// obstacles.
fn goto_2d(wpos2d: Vec2<f32>, speed_factor: f32, goal_dist: f32) -> impl Action { fn goto_2d(wpos2d: Vec2<f32>, speed_factor: f32, goal_dist: f32) -> impl Action {
const MIN_DIST: f32 = 2.0;
now(move |ctx| { now(move |ctx| {
let wpos = wpos2d.with_z(ctx.world.sim().get_alt_approx(wpos2d.as_()).unwrap_or(0.0)); let wpos = wpos2d.with_z(ctx.world.sim().get_alt_approx(wpos2d.as_()).unwrap_or(0.0));
goto(wpos, speed_factor, goal_dist) goto(wpos, speed_factor, goal_dist)
@ -421,7 +412,6 @@ fn travel_to_site(tgt_site: SiteId) -> impl Action {
if let Some(current_site) = ctx.npc.current_site if let Some(current_site) = ctx.npc.current_site
&& let Some(tracks) = path_towns(current_site, tgt_site, sites, ctx.world) && let Some(tracks) = path_towns(current_site, tgt_site, sites, ctx.world)
{ {
let track_count = tracks.path.len();
let mut nodes = tracks.path let mut nodes = tracks.path
.into_iter() .into_iter()
@ -625,6 +615,7 @@ fn villager(visiting_site: SiteId) -> impl Action {
.debug(move || format!("villager at site {:?}", visiting_site)) .debug(move || format!("villager at site {:?}", visiting_site))
} }
/*
fn follow(npc: NpcId, distance: f32) -> impl Action { fn follow(npc: NpcId, distance: f32) -> impl Action {
const STEP_DIST: f32 = 1.0; const STEP_DIST: f32 = 1.0;
now(move |ctx| { now(move |ctx| {
@ -643,6 +634,7 @@ fn follow(npc: NpcId, distance: f32) -> impl Action {
.debug(move || format!("Following npc({npc:?})")) .debug(move || format!("Following npc({npc:?})"))
.map(|_| {}) .map(|_| {})
} }
*/
fn chunk_path( fn chunk_path(
from: Vec2<i32>, from: Vec2<i32>,
@ -794,7 +786,7 @@ fn bird_large() -> impl Action {
if let Some(home) = ctx.npc.home { if let Some(home) = ctx.npc.home {
let is_home = ctx.npc.current_site.map_or(false, |site| home == site); let is_home = ctx.npc.current_site.map_or(false, |site| home == site);
if is_home { if is_home {
if let Some((id, site)) = data if let Some((_, site)) = data
.sites .sites
.iter() .iter()
.filter(|(id, site)| { .filter(|(id, site)| {

View File

@ -1,8 +1,5 @@
use crate::{event::OnTick, RtState, Rule, RuleError}; use crate::{event::OnTick, RtState, Rule, RuleError};
use common::{terrain::TerrainChunkSize, vol::RectVolSize};
use rand::prelude::*; use rand::prelude::*;
use tracing::info;
use vek::*;
pub struct ReplenishResources; pub struct ReplenishResources;

View File

@ -113,7 +113,9 @@ impl Rule for SimulateNpcs {
Npc::new( Npc::new(
rng.gen(), rng.gen(),
rand_wpos(&mut rng), rand_wpos(&mut rng),
Body::BirdLarge(comp::body::bird_large::Body::random_with(&mut rng, species)), Body::BirdLarge(comp::body::bird_large::Body::random_with(
&mut rng, species,
)),
) )
.with_home(site_id), .with_home(site_id),
); );

View File

@ -2003,13 +2003,10 @@ fn handle_kill_npcs(
.get(entity) .get(entity)
.copied() .copied()
{ {
ecs ecs.write_resource::<crate::rtsim2::RtSim>()
.write_resource::<crate::rtsim2::RtSim>()
.hook_rtsim_entity_delete( .hook_rtsim_entity_delete(
&ecs.read_resource::<Arc<world::World>>(), &ecs.read_resource::<Arc<world::World>>(),
ecs ecs.read_resource::<world::IndexOwned>().as_index_ref(),
.read_resource::<world::IndexOwned>()
.as_index_ref(),
rtsim_entity, rtsim_entity,
); );
} }

View File

@ -13,13 +13,12 @@ use common::{
}, },
event::{EventBus, ServerEvent}, event::{EventBus, ServerEvent},
path::TraversalConfig, path::TraversalConfig,
rtsim::RtSimEvent,
}; };
use common_base::prof_span; use common_base::prof_span;
use common_ecs::{Job, Origin, ParMode, Phase, System}; use common_ecs::{Job, Origin, ParMode, Phase, System};
use rand::thread_rng; use rand::thread_rng;
use rayon::iter::ParallelIterator; use rayon::iter::ParallelIterator;
use specs::{saveload::MarkerAllocator, Join, ParJoin, Read, WriteExpect, WriteStorage}; use specs::{saveload::MarkerAllocator, Join, ParJoin, Read, WriteStorage};
/// This system will allow NPCs to modify their controller /// This system will allow NPCs to modify their controller
#[derive(Default)] #[derive(Default)]