Files
cs/src/math.rs
T
rong 00d63ba736 feat: CS 枪火对决 —— Rust 权威服务端 + 手写 WebGL 前端的第一人称 1v1 对枪
- 服务端 60Hz 固定步长模拟:重力/摩擦/轴分离碰撞/上台阶,客户端预测回滚
- 命中裁决:射线打墙打人(身体 + 头部盒),射速/弹匣/换弹/伤害/比分全在服务端
- 回合制:3 秒准备、先到 8 分、100 秒平局;观战自由视角
- 机器人陪练:视线检测 + 反应延迟 + 点射偏差,能单人开练
- 前端零依赖:手写 WebGL(程序化贴图、地图合批、粒子、曳光弹、假投影、黄昏天空)
- 2D Canvas 枪模 + WebAudio 合成音效,无任何图片/音频/CDN 资源
- 地图 level.json 前后端同源,tools/gen_level.py 四分镜像生成,绝对对称
- 测试:14 组规则单测 + 6 组联机 e2e
2026-10-22 21:53:45 +08:00

126 lines
2.5 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 三维向量与角度工具(不用第三方数学库,保持依赖精简)
use serde::Deserialize;
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct V3 {
pub x: f32,
pub y: f32,
pub z: f32,
}
#[inline]
pub const fn v3(x: f32, y: f32, z: f32) -> V3 {
V3 { x, y, z }
}
impl V3 {
pub const ZERO: V3 = v3(0.0, 0.0, 0.0);
#[inline]
pub fn add(self, o: V3) -> V3 {
v3(self.x + o.x, self.y + o.y, self.z + o.z)
}
#[inline]
pub fn sub(self, o: V3) -> V3 {
v3(self.x - o.x, self.y - o.y, self.z - o.z)
}
#[inline]
pub fn scale(self, k: f32) -> V3 {
v3(self.x * k, self.y * k, self.z * k)
}
#[inline]
pub fn dot(self, o: V3) -> f32 {
self.x * o.x + self.y * o.y + self.z * o.z
}
#[inline]
pub fn len(self) -> f32 {
self.dot(self).sqrt()
}
#[inline]
pub fn flat_len(self) -> f32 {
(self.x * self.x + self.z * self.z).sqrt()
}
#[inline]
pub fn norm(self) -> V3 {
let l = self.len();
if l < 1e-8 {
V3::ZERO
} else {
self.scale(1.0 / l)
}
}
#[inline]
pub fn arr(self) -> [f32; 3] {
[self.x, self.y, self.z]
}
#[inline]
pub fn axis(self, i: usize) -> f32 {
match i {
0 => self.x,
1 => self.y,
_ => self.z,
}
}
#[inline]
pub fn set_axis(&mut self, i: usize, v: f32) {
match i {
0 => self.x = v,
1 => self.y = v,
_ => self.z = v,
}
}
}
impl From<[f32; 3]> for V3 {
fn from(a: [f32; 3]) -> V3 {
v3(a[0], a[1], a[2])
}
}
/// 视线方向:yaw=0 看向 -z,yaw 增大向右转(+x),pitch 上正下负
pub fn forward(yaw: f32, pitch: f32) -> V3 {
let cp = pitch.cos();
v3(cp * yaw.sin(), pitch.sin(), -cp * yaw.cos())
}
/// 水平前方(移动用)
pub fn flat_forward(yaw: f32) -> V3 {
v3(yaw.sin(), 0.0, -yaw.cos())
}
/// 水平右方
pub fn right(yaw: f32) -> V3 {
v3(yaw.cos(), 0.0, yaw.sin())
}
/// 把角度收进 [-PI, PI]
pub fn wrap_angle(mut a: f32) -> f32 {
use std::f32::consts::PI;
while a > PI {
a -= 2.0 * PI;
}
while a < -PI {
a += 2.0 * PI;
}
a
}
/// 反序列化辅助:JSON 里的 [x,y,z]
pub fn de_arr<'de, D>(d: D) -> Result<V3, D::Error>
where
D: serde::Deserializer<'de>,
{
let a = <[f32; 3]>::deserialize(d)?;
Ok(V3::from(a))
}