Skip to main content

EngineSim

Struct EngineSim 

Source
pub struct EngineSim<G: GameDef> {
    pub cfg: EngineConfig,
    pub world: PhysicsWorld,
    pub map: Option<GameMap>,
    pub nav: Option<NavigationSystem>,
    pub spatial: SpatialGrid,
    pub rng: Rng,
    pub events: Vec<CoreEvent>,
    pub sim: G::Sim,
    /* private fields */
}
Expand description

Движковый каркас симуляции: физический мир, карта, нав-граф/сетка ботов, PRNG, аккумулятор фиксированного шага, очередь удаления тел, события. Игровая логика (участники/оружие/снапшот-блоки) вынесена в G::Sim (см. core/src/sim.rs) — движок зовёт её только через on_fixed_step/on_contacts/on_before_destroy/on_ai_tick, не зная деталей конкретной игры. Конкретная игра (тип G, дефолт для GameState-алиасов — забота game-crate) не импортируется движком.

Fields§

§cfg: EngineConfig§world: PhysicsWorld§map: Option<GameMap>§nav: Option<NavigationSystem>§spatial: SpatialGrid§rng: Rng§events: Vec<CoreEvent>§sim: G::Sim

Implementations§

Source§

impl<G: GameDef> EngineSim<G>

Source

pub fn new(cfg: EngineConfig, game_cfg: &G::Config) -> Self

Source

pub fn load_map(&mut self, json: &str) -> Result<(), String>

Создаёт карту из JSON (масштабирование внутри) и нав-граф ботов.

Source

pub fn map_info_json(&self) -> String

Информация о загруженной карте: setId, масштабированные респауны, размеры мира (JSON) — ‘null’, если карта не загружена.

Source

pub fn spawn_actor( &mut self, game_id: u32, model_name: &str, team_id: u8, x: f32, y: f32, angle_deg: f32, ) -> Result<(), String>

Source

pub fn remove_actor(&mut self, game_id: u32)

Source

pub fn reset_actor( &mut self, game_id: u32, team_id: u8, x: f32, y: f32, angle_deg: f32, )

Source

pub fn reset_all_vitals(&mut self)

Source

pub fn spawn_scripted_actor( &mut self, game_id: u32, model_name: &str, team_id: u8, x: f32, y: f32, angle_deg: f32, ) -> Result<(), String>

Source

pub fn remove_scripted_actor(&mut self, game_id: u32)

Source

pub fn apply_input( &mut self, game_id: u32, seq: u32, action: &str, key_name: &str, )

Source

pub fn apply_aim(&mut self, game_id: u32, seq: u32, x: f32, y: f32, flags: u32)

Ввод указателем: мировая точка + биты состояния (см. GameSim::apply_aim).

Source

pub fn last_input_seq(&self, game_id: u32) -> u32

Source

pub fn take_events_json(&mut self) -> String

События за тик (kill/health/ammo/weapon/shake) одной JSON-строкой; буфер очищается.

Source

pub fn is_alive(&self, game_id: u32) -> bool

Source

pub fn actor_position(&self, game_id: u32) -> Option<[f32; 2]>

Source

pub fn prediction_state(&self, game_id: u32) -> Option<([f32; 8], bool)>

Source

pub fn alive_players_flat(&self) -> Vec<f32>

Source

pub fn players_json(&self) -> String

Полный снапшот игроков (Game.getPlayersData), не дренируя накопители событий — для первого кадра (FIRST_SHOT_DATA).

Source

pub fn step(&mut self, dt: f32)

Обновляет физику фиксированными шагами (Game.updateData), затем ИИ скриптовых участников (VIMP._onShotTick).

Source

pub fn build_snapshot_blocks(&mut self) -> Vec<(String, Block)>

Собирает блоки тела снапшота, дренируя накопители событий. Вызывается на каждый отправляемый кадр (throttle — забота JS).

Source

pub fn body_has_events(&self) -> bool

Содержал ли последний собранный body событийные блоки — для классификации канала WebRTC (meta reliable / state unreliable).

Source

pub fn remove_players_and_shots(&mut self) -> Vec<String>

Удаляет всех игроков и снаряды, возвращает имена для очистки полотна клиентов (Game.removePlayersAndShots).

Source

pub fn clear(&mut self)

Полная очистка игрового мира (Game.clear + сброс ботов).

Source

pub fn debug_json(&self) -> String

Курированный дамп мира (тела, коллайдеры, карта, нав-граф, spatial-сетка, rng, аккумулятор фикс-шага) — читаемая альтернатива сырому serialize_state (см. crate::debug).

Source

pub fn serialize_state(&self) -> Result<Vec<u8>, String>

Сериализует состояние симуляции для эстафетной передачи между инстансами WASM. Накопители снапшота должны быть дренированы (pack_body) перед вызовом.

Source

pub fn deserialize_state(&mut self, data: &[u8]) -> Result<(), String>

Восстанавливает состояние из дампа. Конфиг ядра должен совпадать с конфигом инстанса, создавшего дамп.

Auto Trait Implementations§

§

impl<G> !RefUnwindSafe for EngineSim<G>

§

impl<G> !UnwindSafe for EngineSim<G>

§

impl<G> Freeze for EngineSim<G>
where <G as GameDef>::Sim: Freeze,

§

impl<G> Send for EngineSim<G>
where <G as GameDef>::Sim: Send,

§

impl<G> Sync for EngineSim<G>
where <G as GameDef>::Sim: Sync,

§

impl<G> Unpin for EngineSim<G>
where <G as GameDef>::Sim: Unpin,

§

impl<G> UnsafeUnpin for EngineSim<G>
where <G as GameDef>::Sim: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_sync(self: Box<T>) -> Box<dyn Any + Sync + Send>

Converts Box<Trait> (where Trait: DowncastSync) to Box<dyn Any + Send + Sync>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Converts Arc<Trait> (where Trait: DowncastSync) to Arc<Any>, which can then be downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.