34 Commits

Author SHA1 Message Date
7e46184566 fix flag 2026-02-19 10:58:06 -08:00
4877923655 move PlaybackState to module 2026-02-19 10:51:13 -08:00
144bfc7a2b PlaybackState 2026-02-19 10:08:30 -08:00
b42c0ea254 temp: use all libs by path 2026-02-19 10:08:05 -08:00
56a7912dbf use Head for playback 2026-02-19 09:00:45 -08:00
a9db4e38eb temp: use roblox_bot_file by path 2026-02-19 08:53:08 -08:00
0be798b6ab float sucks 2026-02-19 08:53:08 -08:00
4a8c9e05a1 setup graphics directly 2026-02-18 10:50:22 -08:00
3117a56d51 remove unused deps 2026-02-18 10:49:33 -08:00
bd8981bb2f rename Bot to CompleteBot 2026-02-18 10:22:40 -08:00
d0e71b8431 separate map from graphics 2026-02-18 10:21:54 -08:00
2646e96c33 write comment 2026-02-18 09:57:14 -08:00
0b98f051f2 use tuple syntax 2026-02-18 09:36:23 -08:00
0597889aad inline setup code 2026-02-18 09:29:04 -08:00
e3d6933f25 move setup into strafesnet_graphics 2026-02-18 09:21:07 -08:00
9a65740c54 share code with lib setup 2026-02-18 09:11:25 -08:00
a39f0fe4db move setup into lib 2026-02-18 09:06:57 -08:00
a43f4720a1 refactor setup 2026-02-18 09:01:35 -08:00
89386f12a0 fix resize 2026-02-18 07:46:48 -08:00
7882a92059 fmt 2026-02-18 07:46:34 -08:00
32b4b1e88a demo 2026-02-17 11:46:21 -08:00
8eb63436fb fix async 2026-02-17 11:46:21 -08:00
5b5ad0c63e change out-dir 2026-02-17 10:12:53 -08:00
27589446b2 add readme 2026-02-17 09:49:44 -08:00
2f8c1ed6f4 api 2026-02-17 09:22:55 -08:00
e054886a27 it builds 2026-02-17 08:54:43 -08:00
e985d4d955 add setup 2026-02-17 08:54:15 -08:00
ad8e9bdbe9 module 2026-02-17 08:53:59 -08:00
29744b9f6a fix deps 2026-02-17 08:53:59 -08:00
d9be6584b7 remove lifetime pollution from lib 2026-02-17 07:35:54 -08:00
fc829b9956 error traits 2026-02-17 07:17:55 -08:00
14649e4454 init graphics inside lib 2026-02-17 07:17:15 -08:00
ee94e8a13e add build profile 2026-02-16 10:20:05 -08:00
ccc6f0f812 native player 2026-02-16 09:58:22 -08:00
26 changed files with 2527 additions and 47 deletions

1383
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -6,8 +6,13 @@ members = [
]
resolver = "3"
[profile.release]
# lto = true
strip = true
codegen-units = 1
[workspace.dependencies]
strafesnet_common = { version = "0.8.0", registry = "strafesnet" }
strafesnet_graphics = { version = "0.0.1", registry = "strafesnet" }
strafesnet_roblox_bot_file = { version = "0.8.1", registry = "strafesnet" }
strafesnet_snf = { version = "0.3.2", registry = "strafesnet" }
strafesnet_common = { version = "0.8.0", registry = "strafesnet", path = "../strafe-project/lib/common" }
strafesnet_graphics = { version = "0.0.2", registry = "strafesnet", path = "../strafe-project/engine/graphics" }
strafesnet_roblox_bot_file = { version = "0.8.1", registry = "strafesnet", path = "../roblox_bot_file" }
strafesnet_snf = { version = "0.3.2", registry = "strafesnet", path = "../strafe-project/lib/snf" }

17
README.md Normal file
View File

@@ -0,0 +1,17 @@
How to build the wasm module:
```
cd wasm-module
wasm-pack build --target web --out-dir ../web-demo/pkg
```
How to serve the web demo (requires wasm module):
```
cd web-demo
python3 -m http.server
```
How to run the native player:
```
cd native-player
cargo run --release
```

View File

@@ -4,7 +4,9 @@ version = "0.1.0"
edition = "2024"
[dependencies]
glam = "0.31.0"
strafesnet_common.workspace = true
strafesnet_graphics.workspace = true
strafesnet_roblox_bot_file.workspace = true
strafesnet_snf.workspace = true
wgpu = "28.0.0"

31
lib/src/bot.rs Normal file
View File

@@ -0,0 +1,31 @@
/// A loaded bot file.
pub struct CompleteBot{
//Instructions
timelines:strafesnet_roblox_bot_file::v0::Block,
offset:f64,
duration:f64,
}
impl CompleteBot{
pub(crate) const CAMERA_OFFSET:glam::Vec3=glam::vec3(0.0,2.0,0.0);
pub fn new(
data:&[u8],
)->Result<Self,strafesnet_roblox_bot_file::v0::Error>{
let timelines=strafesnet_roblox_bot_file::v0::read_all_to_block(std::io::Cursor::new(data))?;
let first=timelines.output_events.first().unwrap();
let last=timelines.output_events.last().unwrap();
Ok(Self{
offset:first.time,
duration:last.time-first.time,
timelines,
})
}
pub const fn offset(&self)->f64{
self.offset
}
pub const fn duration(&self)->f64{
self.duration
}
pub const fn timelines(&self)->&strafesnet_roblox_bot_file::v0::Block{
&self.timelines
}
}

51
lib/src/graphics.rs Normal file
View File

@@ -0,0 +1,51 @@
use strafesnet_graphics::graphics::GraphicsState;
/// The graphics state, essentially a handle to all the information on the GPU.
pub struct Graphics{
graphics:GraphicsState,
config:wgpu::SurfaceConfiguration,
device:wgpu::Device,
queue:wgpu::Queue,
}
impl Graphics{
pub fn new(device:wgpu::Device,queue:wgpu::Queue,config:wgpu::SurfaceConfiguration)->Self{
let mut graphics=strafesnet_graphics::graphics::GraphicsState::new(&device,&queue,&config);
graphics.resize(&device,&config,glam::Vec2::ONE);
Self{
graphics,
device,
queue,
config,
}
}
pub fn change_map(&mut self,map:&crate::map::CompleteMap){
self.graphics.clear();
self.graphics.generate_models(&self.device,&self.queue,map.map());
}
pub fn resize(&mut self,surface:&wgpu::Surface<'_>,size:glam::UVec2){
self.config.width=size.x.max(1);
self.config.height=size.y.max(1);
surface.configure(&self.device,&self.config);
self.graphics.resize(&self.device,&self.config,glam::Vec2::ONE);
}
pub fn render(&mut self,surface:&wgpu::Surface<'_>,pos:glam::Vec3,angles:glam::Vec2){
//this has to go deeper somehow
let frame=match surface.get_current_texture(){
Ok(frame)=>frame,
Err(_)=>{
surface.configure(&self.device,&self.config);
surface
.get_current_texture()
.expect("Failed to acquire next surface texture!")
}
};
let view=frame.texture.create_view(&wgpu::TextureViewDescriptor{
format:Some(self.config.view_formats[0]),
..wgpu::TextureViewDescriptor::default()
});
self.graphics.render(&view,&self.device,&self.queue,strafesnet_graphics::graphics::view_inv(pos,angles));
frame.present();
}
}

91
lib/src/head.rs Normal file
View File

@@ -0,0 +1,91 @@
use glam::Vec3Swizzles;
use strafesnet_common::timer::{Timer,Scaled};
use strafesnet_common::session::{Time as SessionTime,TimeInner as SessionTimeInner};
use strafesnet_common::physics::{Time as PhysicsTime,TimeInner as PhysicsTimeInner};
use strafesnet_roblox_bot_file::v0::{EventType,Head,Timed};
use crate::bot::CompleteBot;
use crate::state::PlaybackState;
fn vector3_to_glam(v:&strafesnet_roblox_bot_file::v0::Vector3)->glam::Vec3{
glam::vec3(v.x,v.y,v.z)
}
/// A playback context. Advance time and then generate a camera position to pass to the renderer.
pub struct PlaybackHead{
head:Head,
offset:f64,
timer:Timer<Scaled<SessionTimeInner,PhysicsTimeInner>>,
state:PlaybackState,
}
const HEAD_NO_CRASH:Head={
let mut head=Head::new();
// push one output event so that output-1 doesn't underflow
head.push(EventType::Output);
head
};
impl PlaybackHead{
pub fn new(time:SessionTime)->Self{
let timer=Timer::unpaused(time,PhysicsTime::ZERO);
Self{
head:HEAD_NO_CRASH,
offset:0.0,
timer,
state:PlaybackState::new(),
}
}
pub fn next_event(&self,bot:&CompleteBot)->Option<Timed<EventType>>{
self.head.next_event(bot.timelines())
}
pub fn process_event(&mut self,bot:&CompleteBot,event_type:EventType){
self.state.process_event(bot,event_type,self.head.get_event_index(event_type));
self.head.push(event_type);
}
pub fn advance_time(&mut self,bot:&CompleteBot,time:SessionTime){
let simulation_time=self.timer.time(time);
let mut time_float=simulation_time.get() as f64/PhysicsTime::ONE_SECOND.get() as f64+self.offset+bot.offset();
loop{
match self.next_event(bot){
Some(next_event)=>{
if next_event.time<time_float{
self.process_event(bot,next_event.event);
}else{
break;
}
},
None=>{
//reset playback
self.head=HEAD_NO_CRASH;
self.offset-=bot.duration();
time_float-=bot.duration();
},
}
}
}
pub fn get_position_angles(&self,bot:&CompleteBot,time:SessionTime)->(glam::Vec3,glam::Vec2){
let time=self.timer.time(time);
let event0=&bot.timelines().output_events[self.head.get_event_index(EventType::Output)-1];
let event1=&bot.timelines().output_events[self.head.get_event_index(EventType::Output)];
let p0=vector3_to_glam(&event0.event.position);
let p1=vector3_to_glam(&event1.event.position);
// let v0=vector3_to_glam(&event0.event.velocity);
// let v1=vector3_to_glam(&event1.event.velocity);
// let a0=vector3_to_glam(&event0.event.acceleration);
// let a1=vector3_to_glam(&event1.event.acceleration);
let t0=event0.time;
let t1=event1.time;
let time_float=time.get() as f64/PhysicsTime::ONE_SECOND.get() as f64;
let t=((time_float+self.offset+bot.offset()-t0)/(t1-t0)) as f32;
let p=p0.lerp(p1,t);
// let v=v0.lerp(v1,t);
// let a=a0.lerp(a1,t);
//println!("position={:?}",p);
let angles0=vector3_to_glam(&event0.event.angles);
let angles1=vector3_to_glam(&event1.event.angles);
let angles=angles0.lerp(angles1,t);
(p+CompleteBot::CAMERA_OFFSET,angles.yx())
}
}

View File

@@ -0,0 +1,15 @@
pub mod bot;
pub mod map;
pub mod head;
pub mod state;
// pub mod surface;
pub mod graphics;
// Create Surface
// Create Graphics from map file and with surface as sample
// Create bot from bot file
// Create playback head
// loop{
// advance head
// render frame
// }

29
lib/src/map.rs Normal file
View File

@@ -0,0 +1,29 @@
#[derive(Debug)]
pub enum Error{
File(strafesnet_snf::Error),
Map(strafesnet_snf::map::Error),
}
impl std::fmt::Display for Error{
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
write!(f,"{self:?}")
}
}
impl std::error::Error for Error{}
pub struct CompleteMap{
complete_map:strafesnet_common::map::CompleteMap,
}
impl CompleteMap{
pub fn new(
data:&[u8],
)->Result<Self,Error>{
let complete_map=strafesnet_snf::read_map(std::io::Cursor::new(data))
.map_err(Error::File)?
.into_complete_map()
.map_err(Error::Map)?;
Ok(Self{complete_map})
}
pub const fn map(&self)->&strafesnet_common::map::CompleteMap{
&self.complete_map
}
}

186
lib/src/state.rs Normal file
View File

@@ -0,0 +1,186 @@
use std::collections::HashMap;
use strafesnet_common::run;
use strafesnet_common::physics::Time as PhysicsTime;
use strafesnet_roblox_bot_file::v0;
use crate::bot::CompleteBot;
struct Run{
run:run::RunState,
flag_reason:Option<v0::FlagReason>,
}
impl Run{
fn new()->Self{
Self{
run:run::RunState::Created,
flag_reason:None,
}
}
fn flag(&mut self,flag_reason:v0::FlagReason){
if self.flag_reason.is_none(){
self.flag_reason=Some(flag_reason);
}
}
fn is_invalid(&self)->bool{
self.flag_reason.is_some()
}
fn is_in_progress(&self)->bool{
matches!(&self.run,run::RunState::Started{..})
}
}
pub struct PlaybackState{
// EventType::Input
game_controls:v0::GameControls,
mouse_pos:v0::Vector2,
// EventType::Output
jump_count:u32,
// EventType::Sound
// EventType::World
// EventType::Gravity
gravity:v0::Vector3,
// EventType::Run
runs:HashMap<v0::ModeID,Run>,
style:v0::Style,
// EventType::Camera
// TODO: camera punch
// EventType::Setting
absolute_sensitivity_enabled:bool,
fov_y:f64,
sens_x:f64,
vertical_sensitivity_multipler:f64,
turn_speed:f64,
}
impl PlaybackState{
pub fn new()->Self{
Self{
game_controls:v0::GameControls::empty(),
mouse_pos:v0::Vector2{x:0.0,y:0.0},
jump_count:0,
gravity:v0::Vector3{x:0.0,y:0.0,z:0.0},
runs:HashMap::new(),
style:v0::Style::Autohop,
absolute_sensitivity_enabled:false,
fov_y:1.0,
sens_x:1.0,
vertical_sensitivity_multipler:1.0,
turn_speed:1.0,
}
}
fn push_output(&mut self,event:&v0::OutputEvent){
if event.tick_info.contains(v0::TickInfo::Jump){
self.jump_count+=1;
}
}
fn push_input(&mut self,event:&v0::InputEvent){
self.game_controls=event.game_controls;
self.mouse_pos=event.mouse_pos;
}
fn push_gravity(&mut self,event:&v0::GravityEvent){
self.gravity=event.gravity;
}
fn push_run(&mut self,event:&v0::Timed<v0::RunEvent>){
match &event.event{
v0::RunEvent::Prepare(run_event_prepare)=>{
self.runs.insert(run_event_prepare.mode,Run::new());
self.style=run_event_prepare.style;
},
v0::RunEvent::Start(run_event_zone)=>{
let time=PhysicsTime::raw((event.time*PhysicsTime::ONE_SECOND.get() as f64) as i64);
if let Some(run)=self.runs.get_mut(&run_event_zone.mode){
_=run.run.start(time);
}
},
v0::RunEvent::Finish(run_event_zone)=>{
let time=PhysicsTime::raw((event.time*PhysicsTime::ONE_SECOND.get() as f64) as i64);
if let Some(run)=self.runs.get_mut(&run_event_zone.mode){
_=run.run.finish(time);
}
},
v0::RunEvent::Clear(run_event_clear)=>{
match run_event_clear.mode{
v0::ModeSpec::Exactly(mode_id)=>{
self.runs.remove(&mode_id);
},
v0::ModeSpec::All=>{
self.runs.clear();
},
v0::ModeSpec::Invalid=>{
self.runs.retain(|_,run|!run.is_invalid());
},
v0::ModeSpec::InProgress=>{
self.runs.retain(|_,run|!run.is_in_progress());
},
}
},
v0::RunEvent::Flag(run_event_flag)=>{
match run_event_flag.mode{
v0::ModeSpec::Exactly(mode_id)=>{
if let Some(run)=self.runs.get_mut(&mode_id){
run.flag(run_event_flag.flag_reason);
}
},
v0::ModeSpec::All=>{
for run in self.runs.values_mut(){
run.flag(run_event_flag.flag_reason);
}
},
v0::ModeSpec::Invalid=>{
for run in self.runs.values_mut(){
if run.is_invalid(){
run.flag(run_event_flag.flag_reason);
}
}
},
v0::ModeSpec::InProgress=>{
for run in self.runs.values_mut(){
if run.is_in_progress(){
run.flag(run_event_flag.flag_reason);
}
}
},
}
},
// these should never appear in a uploaded bot file,
// they are just part of the network protocol for spectating
// someone in practice mode.
//
// Yes, this is a design mistake.
// I didn't understand Session vs Simulation when I rewrote bhop in 2022
v0::RunEvent::LoadState(_run_event_practice)=>{},
v0::RunEvent::SaveState(_run_event_practice)=>{},
}
}
fn push_setting(&mut self,event:&v0::SettingEvent){
match event{
v0::SettingEvent::FieldOfView(setting_event_field_of_view)=>{
self.fov_y=setting_event_field_of_view.fov;
},
v0::SettingEvent::Sensitivity(setting_event_sensitivity)=>{
self.sens_x=setting_event_sensitivity.sensitivity;
},
v0::SettingEvent::VerticalSensitivityMultiplier(setting_event_vertical_sensitivity_multiplier)=>{
self.vertical_sensitivity_multipler=setting_event_vertical_sensitivity_multiplier.multiplier;
},
v0::SettingEvent::AbsoluteSensitivity(setting_event_absolute_sensitivity)=>{
self.absolute_sensitivity_enabled=setting_event_absolute_sensitivity.enabled;
},
v0::SettingEvent::TurnSpeed(setting_event_turn_speed)=>{
self.turn_speed=setting_event_turn_speed.turn_speed;
},
}
}
pub(crate) fn process_event(&mut self,bot:&CompleteBot,event_type:v0::EventType,event_index:usize){
match event_type{
v0::EventType::Input=>self.push_input(&bot.timelines().input_events[event_index].event),
v0::EventType::Output=>self.push_output(&bot.timelines().output_events[event_index].event),
v0::EventType::Sound=>{},
v0::EventType::World=>{},
v0::EventType::Gravity=>self.push_gravity(&bot.timelines().gravity_events[event_index].event),
v0::EventType::Run=>self.push_run(&bot.timelines().run_events[event_index]),
v0::EventType::Camera=>{},
v0::EventType::Setting=>self.push_setting(&bot.timelines().setting_events[event_index].event),
}
}
}

2
lib/src/surface.rs Normal file
View File

@@ -0,0 +1,2 @@
/// A render surface configuration, containing information such as resolution and pixel format
pub struct Surface{}

View File

@@ -4,4 +4,12 @@ version = "0.1.0"
edition = "2024"
[dependencies]
pollster = "0.4.0"
strafesnet_roblox_bot_player = { version = "0.1.0", path = "../lib" }
wgpu = "28.0.0"
winit = "0.30.12"
strafesnet_common.workspace = true
strafesnet_graphics.workspace = true
strafesnet_roblox_bot_file.workspace = true
strafesnet_snf.workspace = true
glam = "0.31.0"

68
native-player/src/app.rs Normal file
View File

@@ -0,0 +1,68 @@
use crate::window::Instruction;
use strafesnet_common::integer;
use strafesnet_common::instruction::TimedInstruction;
use crate::window::WindowContext;
pub struct App<'a>{
root_time:std::time::Instant,
window_thread:WindowContext<'a>,
}
impl<'a> App<'a>{
pub fn new(
root_time:std::time::Instant,
window_thread:WindowContext<'a>,
)->App<'a>{
Self{
root_time,
window_thread,
}
}
fn send_timed_instruction(&mut self,instruction:Instruction){
let time=integer::Time::from_nanos(self.root_time.elapsed().as_nanos() as i64);
self.window_thread.send(TimedInstruction{time,instruction});
}
}
impl winit::application::ApplicationHandler for App<'_>{
fn resumed(&mut self,_event_loop:&winit::event_loop::ActiveEventLoop){
//
}
fn window_event(
&mut self,
event_loop:&winit::event_loop::ActiveEventLoop,
_window_id:winit::window::WindowId,
event:winit::event::WindowEvent,
){
match event{
winit::event::WindowEvent::KeyboardInput{
event:winit::event::KeyEvent{
logical_key:winit::keyboard::Key::Named(winit::keyboard::NamedKey::Escape),
state:winit::event::ElementState::Pressed,
..
},
..
}
|winit::event::WindowEvent::CloseRequested=>{
event_loop.exit();
},
_=>(),
}
self.send_timed_instruction(Instruction::WindowEvent(event));
}
fn device_event(
&mut self,
_event_loop:&winit::event_loop::ActiveEventLoop,
_device_id:winit::event::DeviceId,
event:winit::event::DeviceEvent,
){
self.send_timed_instruction(Instruction::DeviceEvent(event));
}
fn about_to_wait(
&mut self,
_event_loop:&winit::event_loop::ActiveEventLoop
){
self.send_timed_instruction(Instruction::WindowEvent(winit::event::WindowEvent::RedrawRequested));
}
}

116
native-player/src/file.rs Normal file
View File

@@ -0,0 +1,116 @@
use std::io::Read;
#[cfg(any(feature="roblox",feature="source"))]
use strafesnet_deferred_loader::deferred_loader::LoadFailureMode;
#[expect(dead_code)]
#[derive(Debug)]
pub enum ReadError{
#[cfg(feature="roblox")]
Roblox(strafesnet_rbx_loader::ReadError),
#[cfg(feature="source")]
Source(strafesnet_bsp_loader::ReadError),
#[cfg(feature="snf")]
StrafesNET(strafesnet_snf::Error),
#[cfg(feature="snf")]
StrafesNETMap(strafesnet_snf::map::Error),
#[cfg(feature="snf")]
StrafesNETBot(strafesnet_snf::bot::Error),
Io(std::io::Error),
UnknownFileFormat,
}
impl std::fmt::Display for ReadError{
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
write!(f,"{self:?}")
}
}
impl std::error::Error for ReadError{}
pub enum ReadFormat{
#[cfg(feature="roblox")]
Roblox(strafesnet_rbx_loader::Model),
#[cfg(feature="source")]
Source(strafesnet_bsp_loader::Bsp),
#[cfg(feature="snf")]
SNFM(strafesnet_common::map::CompleteMap),
#[cfg(feature="snf")]
SNFB(strafesnet_snf::bot::Segment),
}
pub fn read<R:Read+std::io::Seek>(input:R)->Result<ReadFormat,ReadError>{
let mut buf=std::io::BufReader::new(input);
let peek=std::io::BufRead::fill_buf(&mut buf).map_err(ReadError::Io)?[0..4].to_owned();
// reading the entire file is way faster than round tripping the disk constantly
let mut entire_file=Vec::new();
buf.read_to_end(&mut entire_file).map_err(ReadError::Io)?;
let cursor=std::io::Cursor::new(entire_file);
match peek.as_slice(){
#[cfg(feature="roblox")]
b"<rob"=>Ok(ReadFormat::Roblox(strafesnet_rbx_loader::read(cursor).map_err(ReadError::Roblox)?)),
#[cfg(feature="source")]
b"VBSP"=>Ok(ReadFormat::Source(strafesnet_bsp_loader::read(cursor).map_err(ReadError::Source)?)),
#[cfg(feature="snf")]
b"SNFM"=>Ok(ReadFormat::SNFM(
strafesnet_snf::read_map(cursor).map_err(ReadError::StrafesNET)?
.into_complete_map().map_err(ReadError::StrafesNETMap)?
)),
#[cfg(feature="snf")]
b"SNFB"=>Ok(ReadFormat::SNFB(
strafesnet_snf::read_bot(cursor).map_err(ReadError::StrafesNET)?
.read_all().map_err(ReadError::StrafesNETBot)?
)),
_=>Err(ReadError::UnknownFileFormat),
}
}
#[expect(dead_code)]
#[derive(Debug)]
pub enum LoadError{
ReadError(ReadError),
File(std::io::Error),
#[cfg(feature="roblox")]
LoadRoblox(strafesnet_rbx_loader::LoadError),
#[cfg(feature="source")]
LoadSource(strafesnet_bsp_loader::LoadError),
}
impl std::fmt::Display for LoadError{
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
write!(f,"{self:?}")
}
}
impl std::error::Error for LoadError{}
pub enum LoadFormat{
#[cfg(any(feature="snf",feature="roblox",feature="source"))]
Map(strafesnet_common::map::CompleteMap),
#[cfg(feature="snf")]
Bot(strafesnet_snf::bot::Segment),
}
pub fn load<P:AsRef<std::path::Path>>(path:P)->Result<LoadFormat,LoadError>{
//blocking because it's simpler...
let file=std::fs::File::open(path).map_err(LoadError::File)?;
match read(file).map_err(LoadError::ReadError)?{
#[cfg(feature="snf")]
ReadFormat::SNFB(bot)=>Ok(LoadFormat::Bot(bot)),
#[cfg(feature="snf")]
ReadFormat::SNFM(map)=>Ok(LoadFormat::Map(map)),
#[cfg(feature="roblox")]
ReadFormat::Roblox(model)=>{
let mut place=strafesnet_rbx_loader::Place::from(model);
let script_errors=place.run_scripts().unwrap();
for error in script_errors{
println!("Script error: {error}");
}
let (map,errors)=place.to_snf(LoadFailureMode::DefaultToNone).map_err(LoadError::LoadRoblox)?;
if errors.count()!=0{
print!("Errors encountered while loading the map:\n{}",errors);
}
Ok(LoadFormat::Map(map))
},
#[cfg(feature="source")]
ReadFormat::Source(bsp)=>Ok(LoadFormat::Map(
bsp.to_snf(LoadFailureMode::DefaultToNone,&[]).map_err(LoadError::LoadSource)?
)),
}
}

View File

@@ -1 +1,12 @@
fn main() {}
mod app;
mod file;
mod player;
mod setup;
mod window;
const TITLE:&'static str=concat!("Roblox Bot Player v",env!("CARGO_PKG_VERSION"));
fn main(){
pollster::block_on(setup::setup_and_start(TITLE));
}

View File

@@ -0,0 +1,56 @@
use strafesnet_common::instruction::TimedInstruction;
use strafesnet_common::session::Time as SessionTime;
use strafesnet_roblox_bot_player::{bot::CompleteBot,graphics::Graphics,head::PlaybackHead};
pub enum SessionControlInstruction{
SetPaused(bool),
}
pub enum SessionPlaybackInstruction{
SkipForward,
SkipBack,
DecreaseTimescale,
IncreaseTimescale,
}
pub enum Instruction{
SessionControl(SessionControlInstruction),
SessionPlayback(SessionPlaybackInstruction),
Render,
Resize(winit::dpi::PhysicalSize<u32>),
}
pub struct PlayerWorker<'a>{
surface:wgpu::Surface<'a>,
graphics_thread:Graphics,
bot:CompleteBot,
playback_head:PlaybackHead,
}
impl<'a> PlayerWorker<'a>{
pub fn new(
surface:wgpu::Surface<'a>,
bot:CompleteBot,
graphics_thread:Graphics,
)->Self{
let playback_head=PlaybackHead::new(SessionTime::ZERO);
Self{
surface,
graphics_thread,
bot,
playback_head,
}
}
pub fn send(&mut self,ins:TimedInstruction<Instruction,SessionTime>){
match ins.instruction{
Instruction::SessionControl(session_control_instruction)=>{},
Instruction::SessionPlayback(session_playback_instruction)=>{},
Instruction::Render=>{
self.playback_head.advance_time(&self.bot,ins.time);
let (pos,angles)=self.playback_head.get_position_angles(&self.bot,ins.time);
self.graphics_thread.render(&self.surface,pos,angles);
},
Instruction::Resize(physical_size)=>{
self.graphics_thread.resize(&self.surface,glam::uvec2(physical_size.width,physical_size.height));
},
}
}
}

View File

@@ -0,0 +1,51 @@
use strafesnet_graphics::setup;
fn create_window(title:&str,event_loop:&winit::event_loop::EventLoop<()>)->Result<winit::window::Window,winit::error::OsError>{
let mut attr=winit::window::WindowAttributes::default();
attr=attr.with_title(title);
event_loop.create_window(attr)
}
pub async fn setup_and_start(title:&str){
let event_loop=winit::event_loop::EventLoop::new().unwrap();
let window=create_window(title,&event_loop).unwrap();
println!("Initializing the surface...");
let instance=setup::step1::create_instance();
let surface=setup::step2::create_surface(&instance,&window).unwrap();
let adapter=setup::step3::pick_adapter(&instance,&surface).await.expect("No suitable GPU adapters found on the system!");
let (device,queue)=setup::step4::request_device(&adapter).await;
let size=window.inner_size();
let config=setup::step5::configure_surface(&adapter,&device,&surface,(size.width,size.height));
//dedicated thread to ping request redraw back and resize the window doesn't seem logical
//the thread that spawns the physics thread
let mut window_thread=crate::window::WindowContext::new(
&window,
device,
queue,
surface,
config,
);
for arg in std::env::args().skip(1){
window_thread.send(strafesnet_common::instruction::TimedInstruction{
time:strafesnet_common::integer::Time::ZERO,
instruction:crate::window::Instruction::WindowEvent(winit::event::WindowEvent::DroppedFile(arg.into())),
});
};
println!("Entering event loop...");
let mut app=crate::app::App::new(
std::time::Instant::now(),
window_thread
);
event_loop.run_app(&mut app).unwrap();
}

222
native-player/src/window.rs Normal file
View File

@@ -0,0 +1,222 @@
use strafesnet_common::instruction::TimedInstruction;
use strafesnet_common::session::Time as SessionTime;
use strafesnet_common::physics::{MiscInstruction,SetControlInstruction};
use crate::file::LoadFormat;
use crate::player::{PlayerWorker,Instruction as PhysicsWorkerInstruction,SessionControlInstruction,SessionPlaybackInstruction};
pub enum Instruction{
WindowEvent(winit::event::WindowEvent),
DeviceEvent(winit::event::DeviceEvent),
}
//holds thread handles to dispatch to
pub struct WindowContext<'a>{
manual_mouse_lock:bool,
mouse_pos:glam::DVec2,
simulation_paused:bool,
screen_size:glam::UVec2,
window:&'a winit::window::Window,
physics_thread:PlayerWorker<'a>,
}
impl WindowContext<'_>{
fn get_middle_of_screen(&self)->winit::dpi::PhysicalPosition<u32>{
winit::dpi::PhysicalPosition::new(self.screen_size.x/2,self.screen_size.y/2)
}
fn free_mouse(&mut self){
self.manual_mouse_lock=false;
match self.window.set_cursor_position(self.get_middle_of_screen()){
Ok(())=>(),
Err(e)=>println!("Could not set cursor position: {:?}",e),
}
match self.window.set_cursor_grab(winit::window::CursorGrabMode::None){
Ok(())=>(),
Err(e)=>println!("Could not release cursor: {:?}",e),
}
self.window.set_cursor_visible(true);
}
fn lock_mouse(&mut self){
//if cursor is outside window don't lock but apparently there's no get pos function
//let pos=window.get_cursor_pos();
match self.window.set_cursor_grab(winit::window::CursorGrabMode::Locked){
Ok(())=>(),
Err(_)=>{
match self.window.set_cursor_grab(winit::window::CursorGrabMode::Confined){
Ok(())=>(),
Err(e)=>{
self.manual_mouse_lock=true;
println!("Could not confine cursor: {:?}",e)
},
}
}
}
self.window.set_cursor_visible(false);
}
fn window_event(&mut self,time:SessionTime,event:winit::event::WindowEvent){
match event{
winit::event::WindowEvent::DroppedFile(path)=>{
match crate::file::load(path.as_path()){
// Ok(LoadFormat::Map(map))=>self.physics_thread.send(TimedInstruction{time,instruction:PhysicsWorkerInstruction::ChangeMap(map)}),
// Ok(LoadFormat::Bot(bot))=>self.physics_thread.send(TimedInstruction{time,instruction:PhysicsWorkerInstruction::LoadReplay(bot)}),
Err(e)=>println!("Failed to load file: {e}"),
}
},
winit::event::WindowEvent::Focused(state)=>{
// don't unpause if manually paused
if self.simulation_paused{
return;
}
//pause unpause
self.physics_thread.send(TimedInstruction{
time,
instruction:PhysicsWorkerInstruction::SessionControl(SessionControlInstruction::SetPaused(!state)),
});
//recalculate pressed keys on focus
},
winit::event::WindowEvent::KeyboardInput{
event:winit::event::KeyEvent{state,logical_key,repeat:false,..},
..
}=>{
match (logical_key,state){
(winit::keyboard::Key::Named(winit::keyboard::NamedKey::Tab),winit::event::ElementState::Pressed)=>self.free_mouse(),
(winit::keyboard::Key::Named(winit::keyboard::NamedKey::Tab),winit::event::ElementState::Released)=>self.lock_mouse(),
(winit::keyboard::Key::Named(winit::keyboard::NamedKey::F11),winit::event::ElementState::Pressed)=>{
if self.window.fullscreen().is_some(){
self.window.set_fullscreen(None);
}else{
self.window.set_fullscreen(Some(winit::window::Fullscreen::Borderless(None)));
}
},
(winit::keyboard::Key::Named(winit::keyboard::NamedKey::Escape),winit::event::ElementState::Pressed)=>{
self.manual_mouse_lock=false;
match self.window.set_cursor_grab(winit::window::CursorGrabMode::None){
Ok(())=>(),
Err(e)=>println!("Could not release cursor: {:?}",e),
}
self.window.set_cursor_visible(true);
},
(keycode,state)=>{
let s=state.is_pressed();
// internal variants for this scope
enum SessionInstructionSubset{
Control(SessionControlInstruction),
Playback(SessionPlaybackInstruction),
}
macro_rules! session_ctrl{
($variant:ident,$state:expr)=>{
s.then_some(SessionInstructionSubset::Control(SessionControlInstruction::$variant))
};
}
macro_rules! session_playback{
($variant:ident,$state:expr)=>{
s.then_some(SessionInstructionSubset::Playback(SessionPlaybackInstruction::$variant))
};
}
impl From<SessionInstructionSubset> for PhysicsWorkerInstruction{
fn from(value:SessionInstructionSubset)->Self{
match value{
SessionInstructionSubset::Control(session_control_instruction)=>PhysicsWorkerInstruction::SessionControl(session_control_instruction),
SessionInstructionSubset::Playback(session_playback_instruction)=>PhysicsWorkerInstruction::SessionPlayback(session_playback_instruction),
}
}
}
if let Some(session_instruction)=match keycode{
// TODO: bind system so playback pausing can use spacebar
winit::keyboard::Key::Named(winit::keyboard::NamedKey::Enter)=>if s{
let paused=!self.simulation_paused;
self.simulation_paused=paused;
if paused{
self.free_mouse();
}else{
self.lock_mouse();
}
Some(SessionInstructionSubset::Control(SessionControlInstruction::SetPaused(paused)))
}else{None},
winit::keyboard::Key::Named(winit::keyboard::NamedKey::ArrowUp)=>session_playback!(IncreaseTimescale,s),
winit::keyboard::Key::Named(winit::keyboard::NamedKey::ArrowDown)=>session_playback!(DecreaseTimescale,s),
winit::keyboard::Key::Named(winit::keyboard::NamedKey::ArrowLeft)=>session_playback!(SkipBack,s),
winit::keyboard::Key::Named(winit::keyboard::NamedKey::ArrowRight)=>session_playback!(SkipForward,s),
winit::keyboard::Key::Character(key)=>match key.as_str(){
// "R"|"r"=>s.then(||{
// //mouse needs to be reset since the position is absolute
// self.mouse_pos=glam::DVec2::ZERO;
// SessionInstructionSubset::Input(SessionInputInstruction::Mode(session::ImplicitModeInstruction::ResetAndRestart))
// }),
_=>None,
},
_=>None,
}{
self.physics_thread.send(TimedInstruction{
time,
instruction:session_instruction.into(),
});
}
},
}
},
winit::event::WindowEvent::Resized(size)=>{
self.physics_thread.send(
TimedInstruction{
time,
instruction:PhysicsWorkerInstruction::Resize(size)
}
);
},
winit::event::WindowEvent::RedrawRequested=>{
self.window.request_redraw();
self.physics_thread.send(
TimedInstruction{
time,
instruction:PhysicsWorkerInstruction::Render
}
);
},
_=>(),
}
}
fn device_event(&mut self,time:SessionTime,event:winit::event::DeviceEvent){
}
pub fn send(&mut self,ins:TimedInstruction<Instruction,SessionTime>){
match ins.instruction{
Instruction::WindowEvent(window_event)=>{
self.window_event(ins.time,window_event);
},
Instruction::DeviceEvent(device_event)=>{
self.device_event(ins.time,device_event);
},
}
}
pub fn new<'a>(
window:&'a winit::window::Window,
device:wgpu::Device,
queue:wgpu::Queue,
surface:wgpu::Surface<'a>,
config:wgpu::SurfaceConfiguration,
)->WindowContext<'a>{
let screen_size=glam::uvec2(config.width,config.height);
let bot=include_bytes!("../../web-demo/bhop_marble_7cf33a64-7120-4514-b9fa-4fe29d9523d.qbot");
let map=include_bytes!("../../web-demo/bhop_marble_5692093612.snfm");
let bot=strafesnet_roblox_bot_player::bot::CompleteBot::new(bot).unwrap();
let map=strafesnet_roblox_bot_player::map::CompleteMap::new(map).unwrap();
let mut graphics=strafesnet_roblox_bot_player::graphics::Graphics::new(device,queue,config);
graphics.change_map(&map);
WindowContext{
manual_mouse_lock:false,
mouse_pos:glam::DVec2::ZERO,
simulation_paused:false,
//make sure to update this!!!!!
screen_size,
window,
physics_thread:crate::player::PlayerWorker::new(
surface,
bot,
graphics,
),
}
}
}

View File

@@ -3,10 +3,18 @@ name = "strafesnet_roblox_bot_player_wasm_module"
version = "0.1.0"
edition = "2024"
[lib]
crate-type = ["cdylib"]
[dependencies]
strafesnet_roblox_bot_player = { version = "0.1.0", path = "../lib" }
wasm-bindgen = "0.2.108"
strafesnet_common.workspace = true
strafesnet_graphics.workspace = true
strafesnet_roblox_bot_file.workspace = true
strafesnet_snf.workspace = true
wasm-bindgen = "0.2.108"
wasm-bindgen-futures = "0.4.58"
web-sys = { version = "0.3.85", features = ["HtmlCanvasElement"] }
wgpu = "28.0.0"
[package.metadata.wasm-pack.profile.release]
wasm-opt = ["-Oz", "--enable-bulk-memory","--enable-nontrapping-float-to-int"]

View File

@@ -0,0 +1,108 @@
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::JsValue;
use strafesnet_roblox_bot_player::{bot,map,head,graphics};
use strafesnet_graphics::setup;
use strafesnet_common::session::Time as SessionTime;
// Hack to keep the code compiling,
// SurfaceTarget::Canvas is not available in IDE for whatever reason.
struct ToSurfaceTarget(web_sys::HtmlCanvasElement);
impl From<ToSurfaceTarget> for wgpu::SurfaceTarget<'static>{
fn from(ToSurfaceTarget(canvas):ToSurfaceTarget)->Self{
#[cfg(target_arch = "wasm32")]
let target=wgpu::SurfaceTarget::Canvas(canvas);
#[expect(unused)]
#[cfg(not(target_arch = "wasm32"))]
let target=panic!("{canvas:?}");
#[allow(unused)]
target
}
}
#[wasm_bindgen]
pub struct Graphics{
graphics:graphics::Graphics,
surface:wgpu::Surface<'static>,
}
#[wasm_bindgen]
pub async fn setup_graphics(canvas:web_sys::HtmlCanvasElement)->Graphics{
let size=(canvas.width(),canvas.height());
let instance=setup::step1::create_instance();
let surface=setup::step2::create_surface(&instance,ToSurfaceTarget(canvas)).unwrap();
let adapter=setup::step3::pick_adapter(&instance,&surface).await.expect("No suitable GPU adapters found on the system!");
let (device,queue)=setup::step4::request_device(&adapter).await;
let config=setup::step5::configure_surface(&adapter,&device,&surface,size);
Graphics{
graphics:graphics::Graphics::new(device,queue,config),
surface:surface,
}
}
#[wasm_bindgen]
impl Graphics{
#[wasm_bindgen]
pub fn render(&mut self,bot:&CompleteBot,head:&PlaybackHead,time:f64){
// TODO: check f64 range
let time=SessionTime::raw((time*SessionTime::ONE_SECOND.get() as f64) as i64);
let (pos,angles)=head.head.get_position_angles(&bot.bot,time);
self.graphics.render(&self.surface,pos,angles);
}
#[wasm_bindgen]
pub fn resize(&mut self,width:u32,height:u32){
self.graphics.resize(&self.surface,[width,height].into());
}
#[wasm_bindgen]
pub fn change_map(&mut self,map:&CompleteMap){
self.graphics.change_map(&map.map);
}
}
#[wasm_bindgen]
pub struct CompleteBot{
bot:bot::CompleteBot,
}
#[wasm_bindgen]
impl CompleteBot{
#[wasm_bindgen(constructor)]
pub fn new(data:&[u8])->Result<Self,JsValue>{
Ok(Self{
bot:bot::CompleteBot::new(data).map_err(|e|JsValue::from_str(&e.to_string()))?,
})
}
}
#[wasm_bindgen]
pub struct CompleteMap{
map:map::CompleteMap,
}
#[wasm_bindgen]
impl CompleteMap{
#[wasm_bindgen(constructor)]
pub fn new(data:&[u8])->Result<Self,JsValue>{
Ok(Self{
map:map::CompleteMap::new(data).map_err(|e|JsValue::from_str(&e.to_string()))?,
})
}
}
#[wasm_bindgen]
pub struct PlaybackHead{
head:head::PlaybackHead,
}
#[wasm_bindgen]
impl PlaybackHead{
#[wasm_bindgen(constructor)]
pub fn new(time:f64)->Result<Self,JsValue>{
// TODO: check f64 range
let time=SessionTime::raw((time*SessionTime::ONE_SECOND.get() as f64) as i64);
Ok(Self{
head:head::PlaybackHead::new(time),
})
}
#[wasm_bindgen]
pub fn advance_time(&mut self,bot:&CompleteBot,time:f64){
// TODO: check f64 range
let time=SessionTime::raw((time*SessionTime::ONE_SECOND.get() as f64) as i64);
self.head.advance_time(&bot.bot,time);
}
}

2
web-demo/.gitattributes vendored Normal file
View File

@@ -0,0 +1,2 @@
bhop_marble_7cf33a64-7120-4514-b9fa-4fe29d9523d.qbot filter=lfs diff=lfs merge=lfs -text
bhop_marble_5692093612.snfm filter=lfs diff=lfs merge=lfs -text

Binary file not shown.

13
web-demo/iframe-helper.js Normal file
View File

@@ -0,0 +1,13 @@
if (window.frameElement) {
const body = document.body;
const observer = new ResizeObserver(() => {
window.parent.postMessage({
cmd: "resize",
data: {
width: body.scrollWidth,
height: body.scrollHeight,
},
});
});
observer.observe(body);
}

33
web-demo/index.html Normal file
View File

@@ -0,0 +1,33 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<title>StrafesNET Roblox Bot Player Demo</title>
<style>
:root {
color-scheme: light dark;
}
html,
body {
margin: 0px;
width: 100%;
height: 100%;
overflow: hidden;
}
canvas {
margin: 0;
width: 100%;
height: 100%;
}
</style>
<script defer src="player.js" type="module"></script>
<script defer type="module" src="iframe-helper.js"></script>
</head>
<body>
<canvas></canvas>
</body>
</html>

46
web-demo/player.js Normal file
View File

@@ -0,0 +1,46 @@
import init, {
setup_graphics,
CompleteBot,
CompleteMap,
PlaybackHead,
} from "./pkg/strafesnet_roblox_bot_player_wasm_module.js";
await init(); // load the wasm module
const b = await fetch("bhop_marble_7cf33a64-7120-4514-b9fa-4fe29d9523d.qbot");
const m = await fetch("bhop_marble_5692093612.snfm");
const canvas = document.querySelector("canvas");
const graphics = await setup_graphics(canvas);
const bot = new CompleteBot(new Uint8Array(await b.arrayBuffer()));
const map = new CompleteMap(new Uint8Array(await m.arrayBuffer()));
const playback = new PlaybackHead(0);
graphics.change_map(map);
const startTime = performance.now();
function animate(now) {
const elapsedMs = now - startTime;
const elapsedSec = elapsedMs / 1000; // wasm expects seconds
// Advance the playback head to the current time
playback.advance_time(bot, elapsedSec);
// Render the frame that the bot is at that time
graphics.render(bot, playback, elapsedSec);
// Keep the loop going
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
function resize() {
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
graphics.resize(canvas.width, canvas.height);
}
window.addEventListener("resize", resize);
resize();