Compare commits
83 Commits
native
...
advanced-a
| Author | SHA1 | Date | |
|---|---|---|---|
|
42fc93f68d
|
|||
|
030adf2a87
|
|||
|
495092f79f
|
|||
|
e0a8175355
|
|||
|
006a70a18b
|
|||
|
7ce2ca8b0a
|
|||
|
6ef6c67703
|
|||
|
8dfb5f5094
|
|||
|
9e0e9a62e7
|
|||
|
6fbeba94ae
|
|||
|
01916e0682
|
|||
|
2af2134f72
|
|||
|
a3e7b5ff99
|
|||
|
58f9a70e16
|
|||
|
3b218856c9
|
|||
|
00393490a0
|
|||
|
f96891dcbc
|
|||
|
35a90f28ae
|
|||
|
c3676349b0
|
|||
|
299a2b8051
|
|||
|
a4c4f20bad
|
|||
|
3644dd7f15
|
|||
|
197f840246
|
|||
|
c3cca22839
|
|||
|
81a158d08f
|
|||
|
7a421d1eab
|
|||
|
e821fb6982
|
|||
|
cb71fa7257
|
|||
|
51fdc72e0e
|
|||
|
29e49587ff
|
|||
|
d03f84c893
|
|||
|
48a7b06b71
|
|||
|
43cc9b6416
|
|||
|
e4433cf06c
|
|||
|
54beb3e9df
|
|||
|
aa0a333431
|
|||
|
cb7474522f
|
|||
|
87fa1220c6
|
|||
|
4fb2e6c800
|
|||
|
b1ebd01463
|
|||
|
de8ef7fae2
|
|||
|
dd55987403
|
|||
|
e4f6f8490d
|
|||
|
db634247ac
|
|||
|
c5cd25c27a
|
|||
|
57c545efa6
|
|||
|
8ecb79a0b4
|
|||
|
98f56d0608
|
|||
|
cf59852468
|
|||
|
2f584744c7
|
|||
|
c33daaf0c6
|
|||
|
3dea810a50
|
|||
|
a238793cdc
|
|||
|
d9610901cb
|
|||
|
dd9cf502f1
|
|||
|
0be798b6ab
|
|||
|
4a8c9e05a1
|
|||
|
3117a56d51
|
|||
|
bd8981bb2f
|
|||
|
d0e71b8431
|
|||
|
2646e96c33
|
|||
|
0b98f051f2
|
|||
|
0597889aad
|
|||
|
e3d6933f25
|
|||
|
9a65740c54
|
|||
|
a39f0fe4db
|
|||
|
a43f4720a1
|
|||
|
89386f12a0
|
|||
|
7882a92059
|
|||
|
32b4b1e88a
|
|||
|
8eb63436fb
|
|||
|
5b5ad0c63e
|
|||
|
27589446b2
|
|||
|
2f8c1ed6f4
|
|||
|
e054886a27
|
|||
|
e985d4d955
|
|||
|
ad8e9bdbe9
|
|||
|
29744b9f6a
|
|||
|
d9be6584b7
|
|||
|
fc829b9956
|
|||
|
14649e4454
|
|||
|
ee94e8a13e
|
|||
|
ccc6f0f812
|
2
.cargo/config.toml
Normal file
2
.cargo/config.toml
Normal file
@@ -0,0 +1,2 @@
|
||||
[registries.strafesnet]
|
||||
index = "sparse+https://git.itzana.me/api/packages/strafesnet/cargo/"
|
||||
1540
Cargo.lock
generated
1540
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
13
Cargo.toml
13
Cargo.toml
@@ -6,8 +6,15 @@ 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" }
|
||||
glam = "0.32.0"
|
||||
|
||||
strafesnet_common = { version = "0.8.6", registry = "strafesnet" }
|
||||
strafesnet_graphics = { version = "0.0.5", registry = "strafesnet" }
|
||||
strafesnet_roblox_bot_file = { version = "0.9.3", registry = "strafesnet" }
|
||||
strafesnet_snf = { version = "0.3.2", registry = "strafesnet" }
|
||||
|
||||
176
LICENSE-APACHE
Normal file
176
LICENSE-APACHE
Normal file
@@ -0,0 +1,176 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
23
LICENSE-MIT
Normal file
23
LICENSE-MIT
Normal file
@@ -0,0 +1,23 @@
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
50
README.md
Normal file
50
README.md
Normal file
@@ -0,0 +1,50 @@
|
||||
### How to clone this repository:
|
||||
- Install git
|
||||
- Install git lfs (for test files)
|
||||
```
|
||||
git clone https://git.itzana.me/StrafesNET/roblox-bot-player
|
||||
cd roblox-bot-player
|
||||
git lfs pull
|
||||
```
|
||||
|
||||
### How to build the wasm module:
|
||||
- Install rust
|
||||
- Install wasm-pack
|
||||
```
|
||||
cd wasm-module
|
||||
wasm-pack build --target web --out-dir ../web-demo/pkg
|
||||
```
|
||||
|
||||
### How to serve the web demo (requires wasm module):
|
||||
- Install python3 or use your favourite http server
|
||||
```
|
||||
cd web-demo
|
||||
python3 -m http.server
|
||||
```
|
||||
|
||||
### How to run the native player:
|
||||
- Install rust
|
||||
```
|
||||
cd native-player
|
||||
cargo run --release -- ../web-demo/bhop_marble_5692093612.snfm ../web-demo/bhop_marble_7cf33a64-7120-4514-b9fa-4fe29d9523d.qbot
|
||||
```
|
||||
You can drag and drop map files and bot files to load them.
|
||||
|
||||
#### License
|
||||
|
||||
This code depends on a proprietary module, [strafesnet_graphics](https://git.itzana.me/StrafesNET/strafe-project/src/branch/master/engine/graphics). The resulting binary is
|
||||
not redistributable without the express permission of Rhys Lloyd. The code in this repository
|
||||
is MIT & Apache 2.0 dual licensed, and is free to use.
|
||||
|
||||
<sup>
|
||||
Licensed under either of <a href="LICENSE-APACHE">Apache License, Version
|
||||
2.0</a> or <a href="LICENSE-MIT">MIT license</a> at your option.
|
||||
</sup>
|
||||
|
||||
<br>
|
||||
|
||||
<sub>
|
||||
Unless you explicitly state otherwise, any contribution intentionally submitted
|
||||
for inclusion in this crate by you, as defined in the Apache-2.0 license, shall
|
||||
be dual licensed as above, without any additional terms or conditions.
|
||||
</sub>
|
||||
@@ -1,10 +1,11 @@
|
||||
[package]
|
||||
name = "strafesnet_roblox_bot_player"
|
||||
version = "0.1.0"
|
||||
version = "0.1.1"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
glam.workspace = true
|
||||
strafesnet_common.workspace = true
|
||||
strafesnet_graphics.workspace = true
|
||||
strafesnet_roblox_bot_file.workspace = true
|
||||
strafesnet_snf.workspace = true
|
||||
wgpu = "28.0.0"
|
||||
|
||||
60
lib/src/bot.rs
Normal file
60
lib/src/bot.rs
Normal file
@@ -0,0 +1,60 @@
|
||||
use strafesnet_common::timer::{TimerFixed,Realtime,Unpaused};
|
||||
use strafesnet_common::run::{Time as RunTime};
|
||||
use strafesnet_common::physics::{Time as PhysicsTime,TimeInner as PhysicsTimeInner};
|
||||
use strafesnet_roblox_bot_file::v0;
|
||||
|
||||
use crate::head::{Time as PlaybackTime,TimeInner as PlaybackTimeInner};
|
||||
|
||||
/// A loaded bot file.
|
||||
pub struct CompleteBot{
|
||||
//Instructions
|
||||
timelines:v0::Block,
|
||||
timer:TimerFixed<Realtime<PlaybackTimeInner,PhysicsTimeInner>,Unpaused>,
|
||||
duration:PhysicsTime,
|
||||
world_offset:glam::Vec3,
|
||||
}
|
||||
impl CompleteBot{
|
||||
pub(crate) const CAMERA_OFFSET:glam::Vec3=glam::vec3(0.0,2.0,0.0);
|
||||
pub fn new(
|
||||
timelines:v0::Block,
|
||||
)->Self{
|
||||
let start=crate::time::from_float(timelines.output_events.first().unwrap().time).unwrap();
|
||||
let end=crate::time::from_float(timelines.output_events.last().unwrap().time).unwrap();
|
||||
let world_position=timelines.world_events.iter().find_map(|event|match &event.event{
|
||||
v0::WorldEvent::Reset(world_reset_event)=>Some(world_reset_event.position),
|
||||
_=>None,
|
||||
}).expect("Map must contain a WorldReset event");
|
||||
Self{
|
||||
timer:TimerFixed::new(PlaybackTime::ZERO,start),
|
||||
duration:end-start,
|
||||
timelines,
|
||||
world_offset:glam::vec3(world_position.x,world_position.y,world_position.z),
|
||||
}
|
||||
}
|
||||
pub fn time(&self,time:PlaybackTime)->PhysicsTime{
|
||||
self.timer.time(time)
|
||||
}
|
||||
pub const fn duration(&self)->PhysicsTime{
|
||||
self.duration
|
||||
}
|
||||
pub const fn world_offset(&self)->glam::Vec3{
|
||||
self.world_offset
|
||||
}
|
||||
pub const fn timelines(&self)->&v0::Block{
|
||||
&self.timelines
|
||||
}
|
||||
pub fn run_duration(&self,mode_id:v0::ModeID)->Option<RunTime>{
|
||||
let mut it=self.timelines.run_events.iter().rev();
|
||||
let end=it.find_map(|event|match &event.event{
|
||||
v0::RunEvent::Finish(run_start_event) if run_start_event.mode==mode_id=>Some(event.time),
|
||||
_=>None,
|
||||
})?;
|
||||
let start=it.find_map(|event|match &event.event{
|
||||
v0::RunEvent::Start(run_start_event) if run_start_event.mode==mode_id=>Some(event.time),
|
||||
_=>None,
|
||||
})?;
|
||||
let start=crate::time::from_float(start).unwrap();
|
||||
let end=crate::time::from_float(end).unwrap();
|
||||
Some(end-start)
|
||||
}
|
||||
}
|
||||
56
lib/src/graphics.rs
Normal file
56
lib/src/graphics.rs
Normal file
@@ -0,0 +1,56 @@
|
||||
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,
|
||||
start_offset:glam::Vec3,
|
||||
}
|
||||
impl Graphics{
|
||||
pub fn new(device:wgpu::Device,queue:wgpu::Queue,config:wgpu::SurfaceConfiguration)->Self{
|
||||
let graphics=strafesnet_graphics::graphics::GraphicsState::new(&device,&queue,&config);
|
||||
Self{
|
||||
graphics,
|
||||
device,
|
||||
queue,
|
||||
config,
|
||||
start_offset:glam::Vec3::ZERO,
|
||||
}
|
||||
}
|
||||
pub fn change_map(&mut self,map:&strafesnet_common::map::CompleteMap){
|
||||
self.graphics.clear();
|
||||
self.graphics.generate_models(&self.device,&self.queue,map);
|
||||
let modes=map.modes.clone().denormalize();
|
||||
let mode=modes.get_mode(strafesnet_common::gameplay_modes::ModeId::MAIN).expect("Map does not have a main mode");
|
||||
let start_zone=map.models.get(mode.get_start().get() as usize).expect("Map does not have a start zone");
|
||||
self.start_offset=glam::Vec3::from_array(start_zone.transform.translation.map(|f|f.into()).to_array());
|
||||
}
|
||||
pub fn resize(&mut self,surface:&wgpu::Surface<'_>,size:glam::UVec2,fov:glam::Vec2){
|
||||
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,fov);
|
||||
}
|
||||
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+self.start_offset,angles));
|
||||
|
||||
frame.present();
|
||||
}
|
||||
}
|
||||
156
lib/src/head.rs
Normal file
156
lib/src/head.rs
Normal file
@@ -0,0 +1,156 @@
|
||||
use glam::Vec3Swizzles;
|
||||
use strafesnet_common::timer::{Scaled,Timer,TimerState};
|
||||
use strafesnet_common::session::{Time as SessionTime,TimeInner as SessionTimeInner};
|
||||
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)
|
||||
}
|
||||
|
||||
#[derive(Clone,Copy,Hash,Eq,PartialEq,Ord,PartialOrd,Debug)]
|
||||
pub enum TimeInner{}
|
||||
pub type Time=strafesnet_common::integer::Time<TimeInner>;
|
||||
|
||||
/// A playback context. Advance time and then generate a camera position to pass to the renderer.
|
||||
pub struct PlaybackHead{
|
||||
head:Head,
|
||||
timer:Timer<Scaled<SessionTimeInner,TimeInner>>,
|
||||
state:PlaybackState,
|
||||
}
|
||||
impl PlaybackHead{
|
||||
pub fn new(bot:&CompleteBot,time:SessionTime)->Self{
|
||||
let timer=Timer::unpaused(time,Time::ZERO);
|
||||
let head=Head::after_time(bot.timelines(),bot.time(Time::ZERO).into());
|
||||
let mut state=PlaybackState::new();
|
||||
state.process_head(bot.timelines(),&head);
|
||||
Self{
|
||||
head,
|
||||
timer,
|
||||
state,
|
||||
}
|
||||
}
|
||||
pub const fn state(&self)->&PlaybackState{
|
||||
&self.state
|
||||
}
|
||||
pub fn time(&self,time:SessionTime)->Time{
|
||||
self.timer.time(time)
|
||||
}
|
||||
pub fn timer(&self)->&Timer<Scaled<SessionTimeInner,TimeInner>>{
|
||||
&self.timer
|
||||
}
|
||||
pub fn set_paused(&mut self,time:SessionTime,paused:bool){
|
||||
_=self.timer.set_paused(time,paused);
|
||||
}
|
||||
pub fn set_time(&mut self,bot:&CompleteBot,time:SessionTime,new_time:Time){
|
||||
let new_time=new_time.rem_euclid(bot.duration().coerce());
|
||||
self.timer.set_time(time,new_time);
|
||||
// reset head
|
||||
self.head=Head::after_time(bot.timelines(),bot.time(new_time).into());
|
||||
|
||||
self.state=PlaybackState::new();
|
||||
self.state.process_head(bot.timelines(),&self.head);
|
||||
}
|
||||
pub fn get_scale(&self)->strafesnet_common::integer::Ratio64{
|
||||
self.timer.get_scale()
|
||||
}
|
||||
pub fn set_scale(&mut self,time:SessionTime,new_scale:strafesnet_common::integer::Ratio64){
|
||||
self.timer.set_scale(time,new_scale);
|
||||
}
|
||||
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.timelines(),event_type,self.head.get_event_index(event_type));
|
||||
self.head.push(event_type);
|
||||
}
|
||||
pub fn get_event_index(&self,event_type:EventType)->usize{
|
||||
self.head.get_event_index(event_type)
|
||||
}
|
||||
pub fn advance_time(&mut self,bot:&CompleteBot,time:SessionTime){
|
||||
let mut simulation_time=bot.time(self.time(time));
|
||||
let mut time_float=simulation_time.into();
|
||||
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::after_time(bot.timelines(),bot.time(Time::ZERO).into());
|
||||
self.state=PlaybackState::new();
|
||||
self.state.process_head(bot.timelines(),&self.head);
|
||||
|
||||
// hack to wind back timer offset without precise session timestamp
|
||||
let (mut state,paused)=self.timer.clone().into_state();
|
||||
let offset=state.get_offset()-bot.duration().coerce();
|
||||
state.set_offset(offset);
|
||||
self.timer=Timer::from_state(state,paused);
|
||||
|
||||
// update loop variables
|
||||
simulation_time-=bot.duration();
|
||||
time_float=simulation_time.into();
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
fn interpolate_output<'a>(&self,bot:&'a CompleteBot,time:SessionTime)->InterpolateOutput<'a>{
|
||||
let time=bot.time(self.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 t0=event0.time;
|
||||
let t1=event1.time;
|
||||
let time_float:f64=time.into();
|
||||
let t=((time_float-t0)/(t1-t0)) as f32;
|
||||
InterpolateOutput{
|
||||
event0:&event0.event,
|
||||
event1:&event1.event,
|
||||
t:t,
|
||||
}
|
||||
}
|
||||
pub fn get_position_angles(&self,bot:&CompleteBot,time:SessionTime)->(glam::Vec3,glam::Vec2){
|
||||
let interp=self.interpolate_output(bot,time);
|
||||
|
||||
let p=interp.position();
|
||||
let a=interp.angles();
|
||||
|
||||
(p-bot.world_offset()+CompleteBot::CAMERA_OFFSET,a.yx())
|
||||
}
|
||||
pub fn get_velocity(&self,bot:&CompleteBot,time:SessionTime)->glam::Vec3{
|
||||
let interp=self.interpolate_output(bot,time);
|
||||
interp.velocity()
|
||||
}
|
||||
pub fn get_angles(&self,bot:&CompleteBot,time:SessionTime)->glam::Vec3{
|
||||
let interp=self.interpolate_output(bot,time);
|
||||
interp.angles()
|
||||
}
|
||||
}
|
||||
|
||||
struct InterpolateOutput<'a>{
|
||||
event0:&'a strafesnet_roblox_bot_file::v0::OutputEvent,
|
||||
event1:&'a strafesnet_roblox_bot_file::v0::OutputEvent,
|
||||
t:f32,
|
||||
}
|
||||
impl InterpolateOutput<'_>{
|
||||
fn position(&self)->glam::Vec3{
|
||||
let p0=vector3_to_glam(&self.event0.position);
|
||||
let p1=vector3_to_glam(&self.event1.position);
|
||||
p0.lerp(p1,self.t)
|
||||
}
|
||||
fn velocity(&self)->glam::Vec3{
|
||||
let v0=vector3_to_glam(&self.event0.velocity);
|
||||
let v1=vector3_to_glam(&self.event1.velocity);
|
||||
v0.lerp(v1,self.t)
|
||||
}
|
||||
fn angles(&self)->glam::Vec3{
|
||||
let a0=vector3_to_glam(&self.event0.angles);
|
||||
let a1=vector3_to_glam(&self.event1.angles);
|
||||
a0.lerp(a1,self.t)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
pub mod bot;
|
||||
pub mod head;
|
||||
pub mod time;
|
||||
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
|
||||
// }
|
||||
|
||||
258
lib/src/state.rs
Normal file
258
lib/src/state.rs
Normal file
@@ -0,0 +1,258 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use strafesnet_common::run;
|
||||
use strafesnet_common::physics::Time as PhysicsTime;
|
||||
use strafesnet_roblox_bot_file::v0;
|
||||
|
||||
pub 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);
|
||||
}
|
||||
}
|
||||
pub fn time(&self,time:PhysicsTime)->run::Time{
|
||||
self.run.time(time)
|
||||
}
|
||||
pub fn is_invalid(&self)->bool{
|
||||
self.flag_reason.is_some()
|
||||
}
|
||||
pub fn is_in_progress(&self)->bool{
|
||||
matches!(&self.run,run::RunState::Started{..})
|
||||
}
|
||||
pub fn is_finished(&self)->bool{
|
||||
matches!(&self.run,run::RunState::Finished{..})
|
||||
}
|
||||
pub fn get_flag_reason_text(&self)->Option<&'static str>{
|
||||
Some(match self.flag_reason{
|
||||
Some(v0::FlagReason::Anticheat)=>"Passed through anticheat zone.",
|
||||
Some(v0::FlagReason::StyleChange)=>"Changed style.",
|
||||
Some(v0::FlagReason::Clock)=>"Incorrect clock. (This can be caused by internet hiccups)",
|
||||
Some(v0::FlagReason::Pause)=>"Pausing is not allowed in this style.",
|
||||
Some(v0::FlagReason::Flying)=>"Flying is not allowed in this style.",
|
||||
Some(v0::FlagReason::Gravity)=>"Gravity modification is not allowed in this style.",
|
||||
Some(v0::FlagReason::Timescale)=>"Timescale is not allowed in this style.",
|
||||
Some(v0::FlagReason::Timetravel)=>"Time travel is not allowed in this style.",
|
||||
Some(v0::FlagReason::Teleport)=>"Illegal teleport.",
|
||||
Some(v0::FlagReason::Practice)=>"Practice mode triggers invalidation.",
|
||||
None=>return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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:0.3,
|
||||
vertical_sensitivity_multipler:1.0,
|
||||
turn_speed:core::f64::consts::TAU/0.715588,
|
||||
}
|
||||
}
|
||||
pub fn get_run(&self,mode:v0::ModeID)->Option<&Run>{
|
||||
self.runs.get(&mode)
|
||||
}
|
||||
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=crate::time::from_float(event.time).unwrap();
|
||||
if let Some(run)=self.runs.get_mut(&run_event_zone.mode){
|
||||
_=run.run.start(time);
|
||||
}
|
||||
},
|
||||
v0::RunEvent::Finish(run_event_zone)=>{
|
||||
let time=crate::time::from_float(event.time).unwrap();
|
||||
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*0.5).to_radians().tan();
|
||||
},
|
||||
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_head(&mut self,block:&v0::Block,head:&v0::Head){
|
||||
// The whole point of this is to avoid running the realtime events!
|
||||
/*
|
||||
for event in &block.input_events[0..head.get_event_index(v0::EventType::Input)]{
|
||||
self.push_input(&event.event);
|
||||
}
|
||||
for event in &block.output_events[0..head.get_event_index(v0::EventType::Output)]{
|
||||
self.push_output(&event.event);
|
||||
}
|
||||
for event in &bot.sound_events[0..head.get_event_index(v0::EventType::Sound)]{
|
||||
self.push_sound(&event.event);
|
||||
}
|
||||
*/
|
||||
// for event in &bot.world_events[0..head.get_event_index(v0::EventType::World)]{
|
||||
// self.push_world(&event.event);
|
||||
// }
|
||||
for event in &block.gravity_events[0..head.get_event_index(v0::EventType::Gravity)]{
|
||||
self.push_gravity(&event.event);
|
||||
}
|
||||
for event in &block.run_events[0..head.get_event_index(v0::EventType::Run)]{
|
||||
self.push_run(event);
|
||||
}
|
||||
// for event in &bot.camera_events[0..head.get_event_index(v0::EventType::Camera)]{
|
||||
// self.push_camera(&event.event);
|
||||
// }
|
||||
for event in &block.setting_events[0..head.get_event_index(v0::EventType::Setting)]{
|
||||
self.push_setting(&event.event);
|
||||
}
|
||||
}
|
||||
pub(crate) fn process_event(&mut self,block:&v0::Block,event_type:v0::EventType,event_index:usize){
|
||||
match event_type{
|
||||
v0::EventType::Input=>self.push_input(&block.input_events[event_index].event),
|
||||
v0::EventType::Output=>self.push_output(&block.output_events[event_index].event),
|
||||
v0::EventType::Sound=>{},
|
||||
v0::EventType::World=>{},
|
||||
v0::EventType::Gravity=>self.push_gravity(&block.gravity_events[event_index].event),
|
||||
v0::EventType::Run=>self.push_run(&block.run_events[event_index]),
|
||||
v0::EventType::Camera=>{},
|
||||
v0::EventType::Setting=>self.push_setting(&block.setting_events[event_index].event),
|
||||
}
|
||||
}
|
||||
pub const fn get_fov_y(&self)->f64{
|
||||
let zoom_enabled=self.game_controls.contains(v0::GameControls::Zoom);
|
||||
if zoom_enabled{self.fov_y*0.2}else{self.fov_y}
|
||||
}
|
||||
pub const fn get_sensitivity(&self)->glam::DVec2{
|
||||
if self.absolute_sensitivity_enabled{
|
||||
glam::dvec2(self.sens_x,self.sens_x*self.vertical_sensitivity_multipler)
|
||||
}else{
|
||||
let sens_x=self.sens_x*self.get_fov_y()/128.0;
|
||||
glam::dvec2(sens_x,sens_x*self.vertical_sensitivity_multipler)
|
||||
}
|
||||
}
|
||||
pub const fn get_controls(&self)->v0::GameControls{
|
||||
self.game_controls
|
||||
}
|
||||
pub const fn get_jump_count(&self)->u32{
|
||||
self.jump_count
|
||||
}
|
||||
pub const fn get_gravity(&self)->v0::Vector3{
|
||||
self.gravity
|
||||
}
|
||||
}
|
||||
2
lib/src/surface.rs
Normal file
2
lib/src/surface.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
/// A render surface configuration, containing information such as resolution and pixel format
|
||||
pub struct Surface{}
|
||||
32
lib/src/time.rs
Normal file
32
lib/src/time.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
use strafesnet_common::integer::Time;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error{
|
||||
Underflow,
|
||||
Overflow,
|
||||
Nan,
|
||||
}
|
||||
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 fn from_float<T>(time:f64)->Result<Time<T>,Error>{
|
||||
match time.classify(){
|
||||
core::num::FpCategory::Nan=>Err(Error::Nan),
|
||||
core::num::FpCategory::Zero=>Ok(Time::ZERO),
|
||||
core::num::FpCategory::Infinite
|
||||
|core::num::FpCategory::Subnormal
|
||||
|core::num::FpCategory::Normal=>{
|
||||
if time<Time::<T>::MIN.get() as f64{
|
||||
return Err(Error::Underflow);
|
||||
}
|
||||
if (Time::<T>::MAX.get() as f64)<time{
|
||||
return Err(Error::Overflow);
|
||||
}
|
||||
Ok(Time::raw((time*Time::<T>::ONE_SECOND.get() as f64) as i64))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,4 +4,12 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
glam.workspace = true
|
||||
pollster = "0.4.0"
|
||||
wgpu = "28.0.0"
|
||||
winit = "0.30.12"
|
||||
strafesnet_roblox_bot_player = { version = "0.1.0", path = "../lib" }
|
||||
strafesnet_common.workspace = true
|
||||
strafesnet_graphics.workspace = true
|
||||
strafesnet_roblox_bot_file.workspace = true
|
||||
strafesnet_snf.workspace = true
|
||||
|
||||
68
native-player/src/app.rs
Normal file
68
native-player/src/app.rs
Normal 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));
|
||||
}
|
||||
}
|
||||
68
native-player/src/file.rs
Normal file
68
native-player/src/file.rs
Normal file
@@ -0,0 +1,68 @@
|
||||
use std::io::Read;
|
||||
|
||||
#[expect(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub enum ReadError{
|
||||
StrafesNET(strafesnet_snf::Error),
|
||||
StrafesNETMap(strafesnet_snf::map::Error),
|
||||
RobloxBot(strafesnet_roblox_bot_file::v0::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{
|
||||
SNFM(strafesnet_common::map::CompleteMap),
|
||||
QBOT(strafesnet_roblox_bot_file::v0::Block),
|
||||
}
|
||||
|
||||
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(){
|
||||
b"SNFM"=>Ok(ReadFormat::SNFM(
|
||||
strafesnet_snf::read_map(cursor).map_err(ReadError::StrafesNET)?
|
||||
.into_complete_map().map_err(ReadError::StrafesNETMap)?
|
||||
)),
|
||||
b"qbot"=>Ok(ReadFormat::QBOT(
|
||||
strafesnet_roblox_bot_file::v0::read_all_to_block(cursor).map_err(ReadError::RobloxBot)?
|
||||
)),
|
||||
_=>Err(ReadError::UnknownFileFormat),
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub enum LoadError{
|
||||
ReadError(ReadError),
|
||||
File(std::io::Error),
|
||||
}
|
||||
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{
|
||||
Map(strafesnet_common::map::CompleteMap),
|
||||
Bot(strafesnet_roblox_bot_file::v0::Block),
|
||||
}
|
||||
|
||||
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)?{
|
||||
ReadFormat::QBOT(bot)=>Ok(LoadFormat::Bot(bot)),
|
||||
ReadFormat::SNFM(map)=>Ok(LoadFormat::Map(map)),
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
101
native-player/src/player.rs
Normal file
101
native-player/src/player.rs
Normal file
@@ -0,0 +1,101 @@
|
||||
use strafesnet_common::instruction::TimedInstruction;
|
||||
use strafesnet_common::session::Time as SessionTime;
|
||||
use strafesnet_common::timer::TimerState;
|
||||
use strafesnet_roblox_bot_player::{bot::CompleteBot,graphics::Graphics,head::{PlaybackHead,Time as PlaybackTime}};
|
||||
|
||||
pub enum SessionControlInstruction{
|
||||
SetPaused(bool),
|
||||
Restart,
|
||||
SkipForward,
|
||||
SkipBack,
|
||||
DecreaseTimescale,
|
||||
IncreaseTimescale,
|
||||
}
|
||||
|
||||
pub enum Instruction{
|
||||
SessionControl(SessionControlInstruction),
|
||||
Render,
|
||||
Resize(winit::dpi::PhysicalSize<u32>),
|
||||
ChangeMap(strafesnet_common::map::CompleteMap),
|
||||
LoadReplay(strafesnet_roblox_bot_file::v0::Block),
|
||||
}
|
||||
|
||||
fn speed_ratio(speed:i8)->strafesnet_common::integer::Ratio64{
|
||||
if speed.is_negative(){
|
||||
strafesnet_common::integer::Ratio64::new(4i64.pow(-speed as u32),5u64.pow(-speed as u32)).unwrap()
|
||||
}else{
|
||||
strafesnet_common::integer::Ratio64::new(5i64.pow(speed as u32),4u64.pow(speed as u32)).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
struct Playback{
|
||||
bot:CompleteBot,
|
||||
playback_head:PlaybackHead,
|
||||
playback_speed:i8,
|
||||
}
|
||||
|
||||
pub struct PlayerWorker<'a>{
|
||||
surface:wgpu::Surface<'a>,
|
||||
graphics_thread:Graphics,
|
||||
playback:Option<Playback>,
|
||||
}
|
||||
impl<'a> PlayerWorker<'a>{
|
||||
pub fn new(
|
||||
surface:wgpu::Surface<'a>,
|
||||
graphics_thread:Graphics,
|
||||
)->Self{
|
||||
Self{
|
||||
surface,
|
||||
graphics_thread,
|
||||
playback:None,
|
||||
}
|
||||
}
|
||||
pub fn send(&mut self,ins:TimedInstruction<Instruction,SessionTime>){
|
||||
match ins.instruction{
|
||||
Instruction::SessionControl(SessionControlInstruction::SetPaused(paused))=>if let Some(playback)=&mut self.playback{
|
||||
playback.playback_head.set_paused(ins.time,paused);
|
||||
},
|
||||
Instruction::SessionControl(SessionControlInstruction::Restart)=>if let Some(playback)=&mut self.playback{
|
||||
playback.playback_head.set_time(&playback.bot,ins.time,PlaybackTime::ZERO);
|
||||
},
|
||||
Instruction::SessionControl(SessionControlInstruction::SkipForward)=>if let Some(playback)=&mut self.playback{
|
||||
let head_time=playback.playback_head.timer().clone().into_state().0.get_time(ins.time+SessionTime::from_secs(2));
|
||||
playback.playback_head.set_time(&playback.bot,ins.time,head_time);
|
||||
},
|
||||
Instruction::SessionControl(SessionControlInstruction::SkipBack)=>if let Some(playback)=&mut self.playback{
|
||||
let head_time=playback.playback_head.timer().clone().into_state().0.get_time(ins.time-SessionTime::from_secs(2));
|
||||
playback.playback_head.set_time(&playback.bot,ins.time,head_time);
|
||||
},
|
||||
Instruction::SessionControl(SessionControlInstruction::DecreaseTimescale)=>if let Some(playback)=&mut self.playback{
|
||||
playback.playback_speed=playback.playback_speed.saturating_sub(1).max(-27);
|
||||
playback.playback_head.set_scale(ins.time,speed_ratio(playback.playback_speed));
|
||||
},
|
||||
Instruction::SessionControl(SessionControlInstruction::IncreaseTimescale)=>if let Some(playback)=&mut self.playback{
|
||||
playback.playback_speed=playback.playback_speed.saturating_add(1).min(27);
|
||||
playback.playback_head.set_scale(ins.time,speed_ratio(playback.playback_speed));
|
||||
},
|
||||
Instruction::Render=>if let Some(playback)=&mut self.playback{
|
||||
playback.playback_head.advance_time(&playback.bot,ins.time);
|
||||
let (pos,angles)=playback.playback_head.get_position_angles(&playback.bot,ins.time);
|
||||
self.graphics_thread.render(&self.surface,pos,angles);
|
||||
},
|
||||
Instruction::Resize(physical_size)=>if let Some(playback)=&self.playback{
|
||||
let fov_y=playback.playback_head.state().get_fov_y();
|
||||
let fov_x=fov_y*physical_size.width as f64/physical_size.height as f64;
|
||||
self.graphics_thread.resize(&self.surface,glam::uvec2(physical_size.width,physical_size.height),glam::vec2(fov_x as f32,fov_y as f32));
|
||||
},
|
||||
Instruction::ChangeMap(complete_map)=>{
|
||||
self.graphics_thread.change_map(&complete_map);
|
||||
},
|
||||
Instruction::LoadReplay(bot)=>{
|
||||
let bot=CompleteBot::new(bot);
|
||||
let playback_head=PlaybackHead::new(&bot,SessionTime::ZERO);
|
||||
self.playback=Some(Playback{
|
||||
bot,
|
||||
playback_head,
|
||||
playback_speed:0,
|
||||
});
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
51
native-player/src/setup.rs
Normal file
51
native-player/src/setup.rs
Normal 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.unwrap();
|
||||
|
||||
let size=window.inner_size();
|
||||
let config=setup::step5::configure_surface(&adapter,&device,&surface,(size.width,size.height)).unwrap();
|
||||
|
||||
//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();
|
||||
}
|
||||
137
native-player/src/window.rs
Normal file
137
native-player/src/window.rs
Normal file
@@ -0,0 +1,137 @@
|
||||
use strafesnet_common::instruction::TimedInstruction;
|
||||
use strafesnet_common::session::Time as SessionTime;
|
||||
use crate::file::LoadFormat;
|
||||
use crate::player::{PlayerWorker,Instruction as PhysicsWorkerInstruction,SessionControlInstruction};
|
||||
|
||||
pub enum Instruction{
|
||||
WindowEvent(winit::event::WindowEvent),
|
||||
DeviceEvent(winit::event::DeviceEvent),
|
||||
}
|
||||
|
||||
//holds thread handles to dispatch to
|
||||
pub struct WindowContext<'a>{
|
||||
simulation_paused:bool,
|
||||
window:&'a winit::window::Window,
|
||||
physics_thread:PlayerWorker<'a>,
|
||||
}
|
||||
|
||||
impl WindowContext<'_>{
|
||||
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::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)));
|
||||
}
|
||||
},
|
||||
(keycode,state)=>{
|
||||
let s=state.is_pressed();
|
||||
|
||||
macro_rules! session_ctrl{
|
||||
($variant:ident,$state:expr)=>{
|
||||
s.then_some(PhysicsWorkerInstruction::SessionControl(SessionControlInstruction::$variant))
|
||||
};
|
||||
}
|
||||
|
||||
if let Some(instruction)=match keycode{
|
||||
winit::keyboard::Key::Named(winit::keyboard::NamedKey::Space)=>if s{
|
||||
let paused=!self.simulation_paused;
|
||||
self.simulation_paused=paused;
|
||||
Some(PhysicsWorkerInstruction::SessionControl(SessionControlInstruction::SetPaused(paused)))
|
||||
}else{None},
|
||||
winit::keyboard::Key::Named(winit::keyboard::NamedKey::ArrowUp)=>session_ctrl!(IncreaseTimescale,s),
|
||||
winit::keyboard::Key::Named(winit::keyboard::NamedKey::ArrowDown)=>session_ctrl!(DecreaseTimescale,s),
|
||||
winit::keyboard::Key::Named(winit::keyboard::NamedKey::ArrowLeft)=>session_ctrl!(SkipBack,s),
|
||||
winit::keyboard::Key::Named(winit::keyboard::NamedKey::ArrowRight)=>session_ctrl!(SkipForward,s),
|
||||
winit::keyboard::Key::Character(key)=>match key.as_str(){
|
||||
"R"|"r"=>session_ctrl!(Restart,s),
|
||||
_=>None,
|
||||
},
|
||||
_=>None,
|
||||
}{
|
||||
self.physics_thread.send(TimedInstruction{
|
||||
time,
|
||||
instruction,
|
||||
});
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
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 graphics=strafesnet_roblox_bot_player::graphics::Graphics::new(device,queue,config);
|
||||
WindowContext{
|
||||
simulation_paused:false,
|
||||
window,
|
||||
physics_thread:crate::player::PlayerWorker::new(
|
||||
surface,
|
||||
graphics,
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,24 @@ name = "strafesnet_roblox_bot_player_wasm_module"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[features]
|
||||
default = []
|
||||
webgl = ["wgpu/webgl"]
|
||||
|
||||
[dependencies]
|
||||
glam.workspace = true
|
||||
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 = { version = "28.0.0" }
|
||||
|
||||
[package.metadata.wasm-pack.profile.release]
|
||||
wasm-opt = ["-Oz", "--enable-bulk-memory","--enable-nontrapping-float-to-int"]
|
||||
|
||||
121
wasm-module/src/event.rs
Normal file
121
wasm-module/src/event.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
use strafesnet_roblox_bot_file::v0;
|
||||
use strafesnet_roblox_bot_file::v0::{EventType,Timed};
|
||||
use strafesnet_roblox_bot_player::bot;
|
||||
|
||||
/// A timeline event that has not been processed yet.
|
||||
#[wasm_bindgen]
|
||||
pub struct Event{
|
||||
time:f64,
|
||||
event:TimelineEvent,
|
||||
}
|
||||
impl Event{
|
||||
pub(crate) fn event_type(&self)->EventType{
|
||||
match &self.event{
|
||||
TimelineEvent::Input(..)=>EventType::Input,
|
||||
TimelineEvent::Output(..)=>EventType::Output,
|
||||
TimelineEvent::Sound(..)=>EventType::Sound,
|
||||
TimelineEvent::World(..)=>EventType::World,
|
||||
TimelineEvent::Gravity(..)=>EventType::Gravity,
|
||||
TimelineEvent::Run(..)=>EventType::Run,
|
||||
TimelineEvent::Camera(..)=>EventType::Camera,
|
||||
TimelineEvent::Setting(..)=>EventType::Setting,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum TimelineEvent{
|
||||
Input(v0::InputEvent),
|
||||
Output(v0::OutputEvent),
|
||||
Sound(v0::SoundEvent),
|
||||
World(v0::WorldEvent),
|
||||
Gravity(v0::GravityEvent),
|
||||
Run(v0::RunEvent),
|
||||
Camera(v0::CameraEvent),
|
||||
Setting(v0::SettingEvent),
|
||||
}
|
||||
|
||||
// helper macro for converting v0::Timed<v0::InputEvent> into Event
|
||||
// (used in Event::new)
|
||||
macro_rules! impl_into_event{
|
||||
($event:path,$variant:ident)=>{
|
||||
impl From<Timed<$event>> for Event{
|
||||
fn from(Timed{time,event}:Timed<$event>)->Self{
|
||||
Self{time,event:TimelineEvent::$variant(event)}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
impl_into_event!(v0::InputEvent,Input);
|
||||
impl_into_event!(v0::OutputEvent,Output);
|
||||
impl_into_event!(v0::SoundEvent,Sound);
|
||||
impl_into_event!(v0::WorldEvent,World);
|
||||
impl_into_event!(v0::GravityEvent,Gravity);
|
||||
impl_into_event!(v0::RunEvent,Run);
|
||||
impl_into_event!(v0::CameraEvent,Camera);
|
||||
impl_into_event!(v0::SettingEvent,Setting);
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl Event{
|
||||
pub(crate) fn new(bot:&bot::CompleteBot,event:v0::EventType,event_index:usize)->Self{
|
||||
let mut event:Self=match event{
|
||||
EventType::Input=>bot.timelines().input_events[event_index].clone().into(),
|
||||
EventType::Output=>bot.timelines().output_events[event_index].clone().into(),
|
||||
EventType::Sound=>bot.timelines().sound_events[event_index].clone().into(),
|
||||
EventType::World=>bot.timelines().world_events[event_index].clone().into(),
|
||||
EventType::Gravity=>bot.timelines().gravity_events[event_index].clone().into(),
|
||||
EventType::Run=>bot.timelines().run_events[event_index].clone().into(),
|
||||
EventType::Camera=>bot.timelines().camera_events[event_index].clone().into(),
|
||||
EventType::Setting=>bot.timelines().setting_events[event_index].clone().into(),
|
||||
};
|
||||
event.time-=bot.timelines().output_events.first().unwrap().time;
|
||||
event
|
||||
}
|
||||
#[wasm_bindgen]
|
||||
pub fn time(&self)->f64{
|
||||
self.time
|
||||
}
|
||||
#[wasm_bindgen]
|
||||
pub fn type_id(&self)->u32{
|
||||
self.event_type() as u32
|
||||
}
|
||||
#[wasm_bindgen]
|
||||
pub fn into_inner(self)->wasm_bindgen::JsValue{
|
||||
match self.event{
|
||||
TimelineEvent::Input(input_event)=>InputEvent(input_event).into(),
|
||||
TimelineEvent::Output(output_event)=>OutputEvent(output_event).into(),
|
||||
TimelineEvent::Sound(sound_event)=>SoundEvent(sound_event).into(),
|
||||
TimelineEvent::World(world_event)=>WorldEvent(world_event).into(),
|
||||
TimelineEvent::Gravity(gravity_event)=>GravityEvent(gravity_event).into(),
|
||||
TimelineEvent::Run(run_event)=>RunEvent(run_event).into(),
|
||||
TimelineEvent::Camera(camera_event)=>CameraEvent(camera_event).into(),
|
||||
TimelineEvent::Setting(setting_event)=>SettingEvent(setting_event).into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub struct InputEvent(v0::InputEvent);
|
||||
#[wasm_bindgen]
|
||||
pub struct OutputEvent(v0::OutputEvent);
|
||||
#[wasm_bindgen]
|
||||
pub struct SoundEvent(v0::SoundEvent);
|
||||
impl SoundEvent{
|
||||
pub fn material(&self)->u32{
|
||||
self.0.material
|
||||
}
|
||||
pub fn sound_type(&self)->u32{
|
||||
self.0.sound_type as u32
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub struct WorldEvent(v0::WorldEvent);
|
||||
#[wasm_bindgen]
|
||||
pub struct GravityEvent(v0::GravityEvent);
|
||||
#[wasm_bindgen]
|
||||
pub struct RunEvent(v0::RunEvent);
|
||||
#[wasm_bindgen]
|
||||
pub struct CameraEvent(v0::CameraEvent);
|
||||
#[wasm_bindgen]
|
||||
pub struct SettingEvent(v0::SettingEvent);
|
||||
@@ -0,0 +1,209 @@
|
||||
use wasm_bindgen::prelude::wasm_bindgen;
|
||||
use wasm_bindgen::JsError;
|
||||
use strafesnet_roblox_bot_file::v0;
|
||||
use strafesnet_roblox_bot_player::{bot,head,time,graphics};
|
||||
use strafesnet_graphics::setup;
|
||||
|
||||
mod event;
|
||||
pub use event::*;
|
||||
|
||||
// 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)->Result<Graphics,JsError>{
|
||||
let size=(canvas.width(),canvas.height());
|
||||
|
||||
let instance_desc=wgpu::InstanceDescriptor::from_env_or_default();
|
||||
let instance=wgpu::util::new_instance_with_webgpu_detection(&instance_desc).await;
|
||||
let surface=setup::step2::create_surface(&instance,ToSurfaceTarget(canvas)).map_err(|e|JsError::new(&e.to_string()))?;
|
||||
let adapter=instance.request_adapter(&wgpu::RequestAdapterOptions{
|
||||
power_preference:wgpu::PowerPreference::HighPerformance,
|
||||
force_fallback_adapter:false,
|
||||
compatible_surface:Some(&surface),
|
||||
}).await.map_err(|e|JsError::new(&e.to_string()))?;
|
||||
let (device,queue)=setup::step4::request_device(&adapter).await.map_err(|e|JsError::new(&e.to_string()))?;
|
||||
let config=setup::step5::configure_surface(&adapter,&device,&surface,size).map_err(|e|JsError::new(&e.to_string()))?;
|
||||
Ok(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){
|
||||
let time=time::from_float(time).unwrap();
|
||||
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,fov_slope_x:f32,fov_slope_y:f32){
|
||||
self.graphics.resize(&self.surface,[width,height].into(),[fov_slope_x as f32,fov_slope_y as f32].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,JsError>{
|
||||
let timelines=v0::read_all_to_block(std::io::Cursor::new(data)).map_err(|e|JsError::new(&e.to_string()))?;
|
||||
Ok(Self{
|
||||
bot:bot::CompleteBot::new(timelines),
|
||||
})
|
||||
}
|
||||
#[wasm_bindgen]
|
||||
pub fn duration(&self)->f64{
|
||||
self.bot.duration().into()
|
||||
}
|
||||
#[wasm_bindgen]
|
||||
pub fn run_duration(&self,mode_id:u32)->Option<f64>{
|
||||
let mode=v0::ModeID(mode_id);
|
||||
Some(self.bot.run_duration(mode)?.into())
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub struct CompleteMap{
|
||||
map:strafesnet_common::map::CompleteMap,
|
||||
}
|
||||
#[wasm_bindgen]
|
||||
impl CompleteMap{
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(data:&[u8])->Result<Self,JsError>{
|
||||
let map=strafesnet_snf::read_map(std::io::Cursor::new(data))
|
||||
.map_err(|e|JsError::new(&e.to_string()))?
|
||||
.into_complete_map()
|
||||
.map_err(|e|JsError::new(&e.to_string()))?;
|
||||
Ok(Self{
|
||||
map,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub struct PlaybackHead{
|
||||
head:head::PlaybackHead,
|
||||
}
|
||||
#[wasm_bindgen]
|
||||
impl PlaybackHead{
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(bot:&CompleteBot,time:f64)->Self{
|
||||
let time=time::from_float(time).unwrap();
|
||||
Self{
|
||||
head:head::PlaybackHead::new(&bot.bot,time),
|
||||
}
|
||||
}
|
||||
/// Simple api: call advance_time and then graphics.render()
|
||||
#[wasm_bindgen]
|
||||
pub fn advance_time(&mut self,bot:&CompleteBot,time:f64){
|
||||
let time=time::from_float(time).unwrap();
|
||||
self.head.advance_time(&bot.bot,time);
|
||||
}
|
||||
/// Advanced api: In a loop, call next_event and pass the result to process_event to advance the playback head.
|
||||
#[wasm_bindgen]
|
||||
pub fn next_event(&mut self,bot:&CompleteBot)->Option<Event>{
|
||||
let next_event=self.head.next_event(&bot.bot)?;
|
||||
let event_index=self.head.get_event_index(next_event.event);
|
||||
Some(Event::new(&bot.bot,next_event.event,event_index))
|
||||
}
|
||||
/// Advanced api: In a loop, call next_event and pass the result to process_event to advance the playback head.
|
||||
#[wasm_bindgen]
|
||||
pub fn process_event(&mut self,bot:&CompleteBot,event:Event){
|
||||
self.head.process_event(&bot.bot,event.event_type());
|
||||
}
|
||||
#[wasm_bindgen]
|
||||
pub fn set_paused(&mut self,time:f64,paused:bool){
|
||||
let time=time::from_float(time).unwrap();
|
||||
self.head.set_paused(time,paused);
|
||||
}
|
||||
#[wasm_bindgen]
|
||||
pub fn get_scale(&mut self)->f64{
|
||||
let scale=self.head.get_scale();
|
||||
scale.num() as f64/scale.den() as f64
|
||||
}
|
||||
#[wasm_bindgen]
|
||||
pub fn set_scale(&mut self,time:f64,scale:f64){
|
||||
let time=time::from_float(time).unwrap();
|
||||
self.head.set_scale(time,scale.try_into().unwrap());
|
||||
}
|
||||
#[wasm_bindgen]
|
||||
pub fn get_head_time(&self,time:f64)->f64{
|
||||
let time=time::from_float(time).unwrap();
|
||||
let time=self.head.time(time);
|
||||
time.into()
|
||||
}
|
||||
/// Set the playback head position to new_time.
|
||||
#[wasm_bindgen]
|
||||
pub fn set_head_time(&mut self,bot:&CompleteBot,time:f64,new_time:f64){
|
||||
let time=time::from_float(time).unwrap();
|
||||
let new_time=time::from_float(new_time).unwrap();
|
||||
self.head.set_time(&bot.bot,time,new_time);
|
||||
}
|
||||
#[wasm_bindgen]
|
||||
pub fn get_run_time(&self,bot:&CompleteBot,time:f64,mode_id:u32)->Option<f64>{
|
||||
let time=time::from_float(time).unwrap();
|
||||
let time=bot.bot.time(self.head.time(time));
|
||||
let mode=v0::ModeID(mode_id);
|
||||
let run_time=self.head.state().get_run(mode)?.time(time);
|
||||
Some(run_time.into())
|
||||
}
|
||||
#[wasm_bindgen]
|
||||
pub fn is_run_in_progress(&self,mode_id:u32)->Option<bool>{
|
||||
let mode=v0::ModeID(mode_id);
|
||||
Some(self.head.state().get_run(mode)?.is_in_progress())
|
||||
}
|
||||
#[wasm_bindgen]
|
||||
pub fn is_run_finished(&self,mode_id:u32)->Option<bool>{
|
||||
let mode=v0::ModeID(mode_id);
|
||||
Some(self.head.state().get_run(mode)?.is_finished())
|
||||
}
|
||||
#[wasm_bindgen]
|
||||
pub fn get_fov_slope_y(&self)->f64{
|
||||
self.head.state().get_fov_y()
|
||||
}
|
||||
#[wasm_bindgen]
|
||||
pub fn get_speed(&self,bot:&CompleteBot,time:f64)->f32{
|
||||
let time=time::from_float(time).unwrap();
|
||||
let velocity=self.head.get_velocity(&bot.bot,time);
|
||||
|
||||
use glam::Vec3Swizzles;
|
||||
velocity.xz().length()
|
||||
}
|
||||
#[wasm_bindgen]
|
||||
pub fn get_game_controls(&self)->u32{
|
||||
self.head.state().get_controls().bits()
|
||||
}
|
||||
/// Returns an array of [pitch, yaw, roll] in radians. Yaw is not restricted to any particular range.
|
||||
#[wasm_bindgen]
|
||||
pub fn get_angles(&self,bot:&CompleteBot,time:f64)->Vec<f32>{
|
||||
let time=time::from_float(time).unwrap();
|
||||
let angles=self.head.get_angles(&bot.bot,time);
|
||||
angles.to_array().to_vec()
|
||||
}
|
||||
}
|
||||
|
||||
2
web-demo/.gitattributes
vendored
Normal file
2
web-demo/.gitattributes
vendored
Normal 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
|
||||
BIN
web-demo/bhop_marble_5692093612.snfm
LFS
Normal file
BIN
web-demo/bhop_marble_5692093612.snfm
LFS
Normal file
Binary file not shown.
BIN
web-demo/bhop_marble_7cf33a64-7120-4514-b9fa-4fe29d9523d.qbot
LFS
Normal file
BIN
web-demo/bhop_marble_7cf33a64-7120-4514-b9fa-4fe29d9523d.qbot
LFS
Normal file
Binary file not shown.
13
web-demo/iframe-helper.js
Normal file
13
web-demo/iframe-helper.js
Normal 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);
|
||||
}
|
||||
72
web-demo/index.html
Normal file
72
web-demo/index.html
Normal file
@@ -0,0 +1,72 @@
|
||||
<!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%;
|
||||
}
|
||||
.hud {
|
||||
position: fixed;
|
||||
bottom: 10px;
|
||||
left: 10px;
|
||||
display: flex;
|
||||
flex-direction: column; /* stack vertically */
|
||||
gap: 4px; /* space between timers */
|
||||
}
|
||||
|
||||
.timer {
|
||||
background: #000;
|
||||
color: #fff;
|
||||
padding: 4px 8px;
|
||||
font-family: sans-serif;
|
||||
font-size: 14px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.controls {
|
||||
position: fixed;
|
||||
bottom: 10px;
|
||||
left: 120px;
|
||||
display: flex;
|
||||
flex-direction: row; /* stack horizontally */
|
||||
gap: 4px; /* space between timers */
|
||||
}
|
||||
</style>
|
||||
<script defer src="player.js" type="module"></script>
|
||||
<script defer type="module" src="iframe-helper.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="viewport"> </canvas>
|
||||
<div class="hud">
|
||||
<div id="hud_duration" class="timer">00:00:00</div>
|
||||
<div id="hud_timer" class="timer">00:00:00</div>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<button id="control_reset">↪️</button>
|
||||
<button id="control_pause">⏯</button>
|
||||
<button id="control_backward">⬅️</button>
|
||||
<button id="control_forward">➡️</button>
|
||||
<button id="control_slower">⏪</button>
|
||||
<input type="text" id="control_speed" value="1.00x"></>
|
||||
<button id="control_faster">⏩</button>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
131
web-demo/player.js
Normal file
131
web-demo/player.js
Normal file
@@ -0,0 +1,131 @@
|
||||
import init, {
|
||||
setup_graphics,
|
||||
CompleteBot,
|
||||
CompleteMap,
|
||||
PlaybackHead,
|
||||
} from "./pkg/strafesnet_roblox_bot_player_wasm_module.js";
|
||||
|
||||
// Loading
|
||||
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.getElementById("viewport");
|
||||
|
||||
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(bot, 0);
|
||||
|
||||
graphics.change_map(map);
|
||||
|
||||
// HUD
|
||||
const hud_timer = document.getElementById("hud_timer");
|
||||
const hud_duration = document.getElementById("hud_duration");
|
||||
const MODE_MAIN = 0;
|
||||
|
||||
function timer_text(t) {
|
||||
const h = Math.floor(t / 3600);
|
||||
const m = Math.floor((t % 3600) / 60);
|
||||
const s = Math.floor(t % 60);
|
||||
const ms = Math.floor((t % 1) * 1000);
|
||||
return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}.${String(ms).padStart(3, "0")}`;
|
||||
}
|
||||
|
||||
hud_duration.textContent = timer_text(bot.run_duration(MODE_MAIN));
|
||||
|
||||
// Stuff
|
||||
const startTime = document.timeline.currentTime;
|
||||
function elapsed() {
|
||||
return (document.timeline.currentTime - startTime) / 1000;
|
||||
}
|
||||
|
||||
const control_speed = document.getElementById("control_speed");
|
||||
|
||||
var paused = false;
|
||||
var scale = 1;
|
||||
function set_scale(new_scale) {
|
||||
scale = new_scale;
|
||||
playback.set_scale(elapsed(), scale);
|
||||
control_speed.value = `${scale.toPrecision(3)}x`;
|
||||
}
|
||||
|
||||
const SEEK_DURATION = 1.0;
|
||||
|
||||
// Controls
|
||||
document.getElementById("control_reset").addEventListener("click", (e) => {
|
||||
playback.set_head_time(bot, elapsed(), 0.0);
|
||||
});
|
||||
document.getElementById("control_pause").addEventListener("click", (e) => {
|
||||
paused = !paused;
|
||||
playback.set_paused(elapsed(), paused);
|
||||
});
|
||||
document.getElementById("control_forward").addEventListener("click", (e) => {
|
||||
const time_now = elapsed();
|
||||
const playback_time = playback.get_head_time(time_now);
|
||||
const time_offset = playback.get_scale() * SEEK_DURATION;
|
||||
playback.set_head_time(bot, time_now, playback_time + time_offset);
|
||||
});
|
||||
document.getElementById("control_backward").addEventListener("click", (e) => {
|
||||
const time_now = elapsed();
|
||||
const playback_time = playback.get_head_time(time_now);
|
||||
const time_offset = playback.get_scale() * SEEK_DURATION;
|
||||
playback.set_head_time(bot, time_now, playback_time - time_offset);
|
||||
});
|
||||
document.getElementById("control_slower").addEventListener("click", (e) => {
|
||||
set_scale((scale * 4) / 5);
|
||||
});
|
||||
const regex = new RegExp("^([^x]*)x?$");
|
||||
control_speed.addEventListener("change", (e) => {
|
||||
const parsed = regex.exec(e.target.value);
|
||||
if (!parsed) {
|
||||
set_scale(1);
|
||||
return;
|
||||
}
|
||||
const input = Number(parsed.at(1));
|
||||
if (Number.isNaN(input)) {
|
||||
set_scale(1);
|
||||
return;
|
||||
}
|
||||
set_scale(input);
|
||||
});
|
||||
document.getElementById("control_faster").addEventListener("click", (e) => {
|
||||
set_scale((scale * 5) / 4);
|
||||
});
|
||||
|
||||
// Rendering
|
||||
function animate(now) {
|
||||
const elapsedMs = now - startTime;
|
||||
const elapsedSec = elapsedMs / 1000; // wasm expects seconds
|
||||
|
||||
// Advance the playback head to the current time
|
||||
var event = playback.next_event(bot);
|
||||
while (event && event.time() < elapsedSec) {
|
||||
playback.process_event(bot, event);
|
||||
event = playback.next_event(bot);
|
||||
}
|
||||
|
||||
// update the timer text
|
||||
const time = playback.get_run_time(bot, elapsedSec, MODE_MAIN);
|
||||
hud_timer.textContent = timer_text(time);
|
||||
|
||||
// Render the frame that the bot is at that time
|
||||
graphics.render(bot, playback, elapsedSec);
|
||||
|
||||
// Keep the loop going
|
||||
requestAnimationFrame(animate);
|
||||
}
|
||||
|
||||
requestAnimationFrame(animate);
|
||||
|
||||
// Resizing
|
||||
function resize() {
|
||||
canvas.width = canvas.clientWidth;
|
||||
canvas.height = canvas.clientHeight;
|
||||
const fov_y = playback.get_fov_slope_y();
|
||||
const fov_x = (fov_y * canvas.width) / canvas.height;
|
||||
graphics.resize(canvas.width, canvas.height, fov_x, fov_y);
|
||||
}
|
||||
window.addEventListener("resize", resize);
|
||||
resize();
|
||||
Reference in New Issue
Block a user