commit 00d63ba736787d75eb5bd4bf4327d69af03a9be5 Author: rong Date: Thu Oct 22 21:53:45 2026 +0800 feat: CS 枪火对决 —— Rust 权威服务端 + 手写 WebGL 前端的第一人称 1v1 对枪 - 服务端 60Hz 固定步长模拟:重力/摩擦/轴分离碰撞/上台阶,客户端预测回滚 - 命中裁决:射线打墙打人(身体 + 头部盒),射速/弹匣/换弹/伤害/比分全在服务端 - 回合制:3 秒准备、先到 8 分、100 秒平局;观战自由视角 - 机器人陪练:视线检测 + 反应延迟 + 点射偏差,能单人开练 - 前端零依赖:手写 WebGL(程序化贴图、地图合批、粒子、曳光弹、假投影、黄昏天空) - 2D Canvas 枪模 + WebAudio 合成音效,无任何图片/音频/CDN 资源 - 地图 level.json 前后端同源,tools/gen_level.py 四分镜像生成,绝对对称 - 测试:14 组规则单测 + 6 组联机 e2e diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bdb35f8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +# 构建产物留在项目里,target/ 不进仓库(编译中间物不外移,见 dev-cache-layout) +/target/ + +# 系统 / 本地杂项 +.DS_Store +*.log +.env + +# 本机 agent 工作记录,不入库 +.workbuddy/ + +# 验证脚本产生的截图 +/screenshots/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..6f5c91c --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,753 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "base64", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sha1", + "sync_wrapper", + "tokio", + "tokio-tungstenite", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "cs" +version = "1.0.0" +dependencies = [ + "axum", + "futures-util", + "serde", + "serde_json", + "tokio", + "tokio-tungstenite", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-macro", + "futures-sink", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand", + "sha1", + "thiserror", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..bfe6e0c --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "cs" +version = "1.0.0" +edition = "2021" +description = "CS · 枪火对决:第一人称 1v1 对枪(Rust 权威服务端 + 纯静态 WebGL 前端)" +license = "MIT" + +[dependencies] +axum = { version = "0.8", features = ["ws"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "sync"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +futures-util = "0.3" + +[dev-dependencies] +# 跟 axum 内部用的 tungstenite 同版本,省一次重复编译 +tokio-tungstenite = "0.29" + +[profile.release] +lto = "thin" +codegen-units = 1 +strip = true diff --git a/README.md b/README.md new file mode 100644 index 0000000..bb9f0ca --- /dev/null +++ b/README.md @@ -0,0 +1,196 @@ +# CS · 枪火对决 + +第一人称 1v1 对枪。**Rust 权威服务端 + 纯静态 WebGL 前端**,打开网页就能打,不装客户端、不注册账号、前端零构建、零外部资源。 + +![大厅](docs/shot-lobby.png) + +``` +浏览器 A ──┐ ┌── 60Hz 权威模拟(移动 / 命中 / 伤害 / 回合) + ├── WebSocket ───────┤ +浏览器 B ──┘ └── 房间状态(比分 / 回合 / 观战席) + └── 观战者 + +Rust(axum + tokio) public/ 里的 html/css/js 由同一个进程托管 +``` + +| 画面 | 说明 | +| --- | --- | +| ![战斗](docs/shot-game.png) | 第一人称视角、枪模、后坐力、准星、血量与弹药 | +| ![地图](docs/shot-map.png) | 48×48m 对称地图「沙漠据点」,中央高台 + 两侧小屋 + 掩体 | + +## 跑起来 + +需要 Rust 工具链(`cargo` 1.75+)。 + +```bash +cargo run --release # 或 cargo run 走 debug,编译更快 +``` + +打开 ,点「练习模式」就能和机器人对枪。 + +首次编译约 3~5 分钟(拉依赖 + 编 axum/tokio),之后增量编译几秒。 + +## 两个人怎么玩 + +**同一个 Wi-Fi(最简单)** + +1. 你在电脑上打开 `http://localhost:3000`,点「创建房间」,屏幕上会出现 4 位房号。 +2. 终端启动时会顺便打印局域网地址,比如 `http://192.168.1.8:3000`。 +3. 对方在另一台设备上打开这个地址,输入房号点「加入」。 +4. 双方各占一个出生点,斜对角开局。 + +**不在同一个 Wi-Fi** + +把编译出的单文件二进制丢到有公网 IP 的服务器上(见下一节),`PORT=8080 ./cs`。用 Nginx/Caddy 反代时记得放行 WebSocket 的 `Upgrade` 头: + +```nginx +location / { + proxy_pass http://127.0.0.1:8080; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header Host $host; +} +``` + +**旁观** + +大厅里填房号点「观战」,就进入自由视角:WASD 飞、Shift 加速、鼠标转头。 +两个座位都有人时,点「加入」也会自动变成观战。 + +## 操作 + +| 按键 | 作用 | +| --- | --- | +| `W` `A` `S` `D` | 移动 | +| `Shift` | 静步(更慢、更稳、没脚步声) | +| `空格` | 跳跃(能跳上 1 米矮台) | +| 鼠标左键 | 开火(步枪按住连发,手枪单发) | +| `R` | 换弹 | +| `1` / `2` | 切步枪 / 手枪 | +| `Tab` | 记分板 | +| `Esc` | 解锁鼠标(暂停菜单,可调灵敏度) | + +## 打起来是什么样 + +- 每回合双方**满血 100、满弹**,在固定出生点复活,3 秒准备时间后开打。 +- 命中身体 / 头部伤害不同:AK 一枪头 108(秒杀),沙漠之鹰 166;打身体分别 27 / 52。 +- 谁先倒下,对方得 1 分,**先到 8 分**赢下整场。回合间隔 3.5 秒自动重开。 +- 单回合 100 秒打不完算平局,双方都不加分。 +- 步枪 30 发 / 备用 90,手枪 7 发 / 备用 35;换弹有 2 秒多空窗,别在对手冲脸时换。 +- 移动、腾空会放大散布;后坐力会抬枪口,需要自己压枪。 +- 爆头、击杀、被击杀都有独立音效和画面反馈(命中标记、受击红晕、击杀播报)。 + +## 代码结构 + +``` +src/math.rs 三维向量 / 角度 +src/level.rs 地图(AABB 方块)+ 射线求交 +src/physics.rs 移动物理:重力、加速、摩擦、轴分离碰撞、上台阶 +src/weapons.rs 武器表(伤害 / 射速 / 弹匣 / 散布) +src/game.rs 房间状态机:回合、命中裁决、伤害、机器人 AI +src/protocol.rs WebSocket 消息契约 +src/server.rs 房间管理 + 60Hz 模拟 + 30Hz 快照 + 静态资源 +build.rs 把 public/ 压成资源表编进二进制 + +public/index.html 页面骨架(大厅 + HUD) +public/style.css 深色科技风样式 +public/level.json 地图数据(前后端同一份) +public/js/client/main.js 连接 / 输入 / 预测回滚 / 射击 / 回合 UI +public/js/client/renderer.js 手写 WebGL:贴图生成、地图合批、玩家模型、粒子、天空 +public/js/client/viewmodel.js 第一人称枪模(2D Canvas 矢量绘制) +public/js/client/movement.js 物理的 JS 镜像(客户端预测用) +public/js/client/weapons.js 武器表的 JS 镜像(只做表现) +public/js/client/sound.js WebAudio 现场合成(枪声 / 脚步 / 命中 / 换弹,无音频文件) +public/js/client/hud.js HUD 更新 +tools/gen_level.py 地图生成脚本(只写四分之一,镜像出整张图) +tools/verify.cjs 无头浏览器截图 + 控制台检查 +``` + +## 关键设计 + +**服务端说了算** + +服务端 60Hz 固定步长跑物理,客户端只发「按键位 + 视角」,不直接发坐标。 +命中用射线:先打墙,再打人(身体盒 + 头部盒),取最近的那个。射速、弹匣、换弹、伤害、比分全在服务端算, +客户端改不了血量,也改不了子弹。 + +**客户端预测 + 回滚** + +本地用 `movement.js`(`physics.rs` 的镜像)先跑一遍,手感没有延迟; +每张快照带 `ack`(已处理到第几号输入),客户端把没被确认的输入重放一遍,再把「渲染位置 - 预测位置」的残差做指数衰减,肉眼看不到拉扯。 + +**30Hz 快照 + 插值** + +服务端 30Hz 广播全场状态,远端玩家位置在客户端做指数平滑,50ms 的网络抖动不会变成抽搐。 + +**地图只有一份** + +`public/level.json` 由 `tools/gen_level.py` 生成(只写 x≤0、z≤0 的四分之一,程序镜像), +服务端 `include_str!` 编进二进制解析,前端 `fetch` 同一份文件。地图尺寸、出生点、碰撞、渲染不可能对不上。 + +**零外部资源** + +贴图全部用 Canvas 现场生成(混凝土 / 木箱 / 金属 / 地砖 + 噪声污渍), +天空、粒子、曳光弹、枪模都是代码画的,音效是 WebAudio 合成的。 +整个前端没有一张图片、一个字体、一个 CDN 请求,断网也能跑。 + +## 编译成单文件程序 + +```bash +cargo build --release +``` + +产物:`target/release/cs`,**约 1.5 MB**(自带 HTTP/WS 服务 + 内嵌前端资源,不依赖任何运行时)。 + +```bash +PORT=3000 ./cs +``` + +`build.rs` 会把 `public/` 整个目录编译进二进制,拷到没装任何东西的电脑 / NAS 上直接跑; +`/health` 里能看到 `"engine":"rust"`、`"tick":60`、`"snapshot":30`、`"map":"沙漠据点"`。 + +- 默认只编「当前系统 + 当前架构」。要给 Linux x86_64 用,就在 Linux 上 `cargo build --release`。 +- 前端资源已内嵌,但**程序同目录若存在 `public/`,会优先用磁盘上的版本**,方便临时改页面。 + +## 改前端不用编译 + +`public/` 里的文件就是最终产物,浏览器直接加载 ES module: + +```bash +cargo run # 起服务 +# 改 public/index.html、style.css、js/client/*.js,存盘刷新即可 +``` + +服务端对静态资源发 `Cache-Control: no-cache`。 + +> `movement.js` 是 `physics.rs` 的镜像、`weapons.js` 是 `weapons.rs` 的镜像: +> 改移动常数或武器数值要**两边一起改**,服务端才是权威,前端那份只负责「看起来跟手」。 + +## 测试 + +```bash +cargo test +``` + +- `game::tests` —— 14 组规则断言:出生点不卡墙、射线挡墙、冻结 3 秒、前进/摩擦、命中盒分头身、射速限制、击杀加分与回合重开、8 分结束、弹匣打空、换弹、机器人会动、观战占位、中离暂停、输入队列防加速。 +- `tests/e2e.rs` —— 6 组联机断言:建房→加入→冻结→开打→移动生效、观战者看得到但动不了、机器人会出门、狂发 200 帧输入不会瞬移、未知房号报错、`/health` 与静态资源。 + +单跑某一组:`cargo test --test e2e` / `cargo test 击杀`。 + +## 还没做的 + +- 语音 / 文字聊天(cnchess 那套语音链路没搬过来,1v1 对枪用处也不大) +- 团队模式、经济系统、买枪、投掷物、穿墙伤害 +- 地图只有一张,也没有编辑器(`tools/gen_level.py` 算半个) +- 房间状态在内存里,重启即清;也没做多进程横向扩展 +- 移动端只有键鼠布局,触屏操作没做 +- 反作弊:服务端已经拿走了所有裁定权,但没有做异常输入频率分析 + +## 本机编译加速 / 缓存布局 + +按 `dev-cache-layout` 技能的约定: + +- **`target/` 留在项目目录**(增量编译 + 复查用),已在 `.gitignore`,没有挪到 `~/Library/Caches` 再软链回来。 +- 包缓存实体集中在 `~/.cache`:`~/.cargo/registry -> ~/.cache/cargo/registry`、`~/.npm -> ~/.cache/npm`(本机已验证)。 +- 依赖走 USTC sparse 镜像、编译器包了 sccache,配置都在 `~/.cargo/config.toml`,仓库里不需要再放 `.cargo/config.toml`。 diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..acc5535 --- /dev/null +++ b/build.rs @@ -0,0 +1,62 @@ +//! 把 public/ 整个目录编译进二进制:`cargo build --release` 出来的是单文件, +//! 拷到别的机器上不用带 public/ 也能跑;同时运行期仍然优先读磁盘,方便改页面。 + +use std::fmt::Write as _; +use std::path::{Path, PathBuf}; +use std::{env, fs}; + +fn mime_of(name: &str) -> &'static str { + match name.rsplit('.').next().unwrap_or("").to_ascii_lowercase().as_str() { + "html" | "htm" => "text/html; charset=utf-8", + "js" | "mjs" => "text/javascript; charset=utf-8", + "css" => "text/css; charset=utf-8", + "json" | "webmanifest" => "application/json; charset=utf-8", + "png" => "image/png", + "jpg" | "jpeg" => "image/jpeg", + "svg" => "image/svg+xml", + "ico" => "image/x-icon", + "woff2" => "font/woff2", + "mp3" => "audio/mpeg", + "webp" => "image/webp", + _ => "application/octet-stream", + } +} + +fn walk(dir: &Path, out: &mut Vec) { + let Ok(rd) = fs::read_dir(dir) else { return }; + for entry in rd.flatten() { + let p = entry.path(); + if p.is_dir() { + walk(&p, out); + } else { + out.push(p); + } + } +} + +fn main() { + let manifest = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); + let public = manifest.join("public"); + println!("cargo:rerun-if-changed=public"); + + let mut files = Vec::new(); + walk(&public, &mut files); + files.sort(); + + let mut src = String::from("// 由 build.rs 生成,勿手改\npub static ASSETS: &[(&str, &str, &[u8])] = &[\n"); + for f in &files { + let rel = f.strip_prefix(&public).unwrap().to_string_lossy().replace('\\', "/"); + let key = format!("/{rel}"); + let mime = mime_of(&rel); + writeln!( + src, + " ({key:?}, {mime:?}, include_bytes!({:?})),", + f.to_string_lossy() + ) + .unwrap(); + } + src.push_str("];\n"); + + let out = PathBuf::from(env::var("OUT_DIR").unwrap()).join("assets_gen.rs"); + fs::write(out, src).unwrap(); +} diff --git a/docs/shot-enemy.png b/docs/shot-enemy.png new file mode 100644 index 0000000..8644570 Binary files /dev/null and b/docs/shot-enemy.png differ diff --git a/docs/shot-game.png b/docs/shot-game.png new file mode 100644 index 0000000..b1e5435 Binary files /dev/null and b/docs/shot-game.png differ diff --git a/docs/shot-lobby.png b/docs/shot-lobby.png new file mode 100644 index 0000000..7a7e156 Binary files /dev/null and b/docs/shot-lobby.png differ diff --git a/docs/shot-map.png b/docs/shot-map.png new file mode 100644 index 0000000..58c681b Binary files /dev/null and b/docs/shot-map.png differ diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..a1e083a --- /dev/null +++ b/public/index.html @@ -0,0 +1,219 @@ + + + + + + + CS · 枪火对决 + + + + + + + + + + + +
+
+
+
+ +
+

CS · 枪火对决

+

第一人称 · 1v1 对枪 · 服务端权威判定

+
+
+ +
+
+ 地图 + 沙漠据点 + 48 × 48m · 先到 8 分 +
+ + + +
+ + +
+ +
或者加入朋友的房间
+ +
+ + +
+ + + +
    +
  • WASD 移动 · Shift 静步 · 空格 跳跃 · 左键 开火
  • +
  • R 换弹 · 1 / 2 切枪 · Tab 记分板 · Esc 暂停
  • +
  • 每回合满血满弹,把对手打倒得 1 分,先到 8 分赢下比赛。
  • +
+ +
+ + 正在连接服务器… +
+
+ +
Rust + WebGL · 无插件 · 无外部资源
+
+
+ +
+ + + + diff --git a/public/js/client/hud.js b/public/js/client/hud.js new file mode 100644 index 0000000..63e9ef9 --- /dev/null +++ b/public/js/client/hud.js @@ -0,0 +1,196 @@ +// HUD 全部是 DOM,更新只碰必要节点;准星张开度用 CSS 变量。 + +const $ = (id) => document.getElementById(id); + +export class Hud { + constructor() { + this.root = $("hud"); + this.el = { + hud: this.root, + scoreMe: $("scoreMe"), + scoreFoe: $("scoreFoe"), + foeName: $("foeName"), + roundNo: $("roundNo"), + roundTimer: $("roundTimer"), + fps: $("fps"), + ping: $("ping"), + specBadge: $("specBadge"), + crosshair: $("crosshair"), + hitmarker: $("hitmarker"), + dmgFlash: $("dmgFlash"), + hp: $("hp"), + hpBar: $("hpBar"), + aliveText: $("aliveText"), + kda: $("kda"), + wname: $("wname"), + mag: $("mag"), + reserve: $("reserve"), + reloadTrack: $("reloadTrack"), + reloadFill: $("reloadFill"), + killfeed: $("killfeed"), + banner: $("banner"), + bannerKicker: $("bannerKicker"), + bannerTitle: $("bannerTitle"), + bannerSub: $("bannerSub"), + deathScreen: $("deathScreen"), + deathBy: $("deathBy"), + deathWeapon: $("deathWeapon"), + deathCount: $("deathCount"), + spectateBar: $("spectateBar"), + scoreboard: $("scoreboard"), + sbRows: $("sbRows"), + sbFoot: $("sbFoot"), + pauseScreen: $("pauseScreen"), + waiting: $("waiting"), + waitCode: $("waitCode"), + }; + this._bannerTimer = 0; + this._lastHp = 100; + this._lastScore = [0, 0]; + this._lastPhase = ""; + } + + show(on) { + this.root.hidden = !on; + } + + setScore(me, foe, target, foeName) { + this.el.scoreMe.textContent = me; + this.el.scoreFoe.textContent = foe; + if (foeName) this.el.foeName.textContent = foeName; + this.el.sbFoot.textContent = `先到 ${target} 分获胜`; + } + + setRound(no, leftMs) { + this.el.roundNo.textContent = `第 ${no} 回合`; + if (leftMs == null) { + this.el.roundTimer.textContent = "--:--"; + return; + } + const s = Math.max(0, Math.ceil(leftMs / 1000)); + const m = Math.floor(s / 60); + const ss = String(s % 60).padStart(2, "0"); + this.el.roundTimer.textContent = `${m}:${ss}`; + } + + setHp(hp, alive, kills, deaths) { + const v = Math.max(0, Math.round(hp)); + this.el.hp.textContent = v; + this.el.hpBar.style.width = `${v}%`; + this.el.hpBar.className = v <= 30 ? "low" : v <= 60 ? "warn" : ""; + this.el.aliveText.textContent = alive ? "存活" : "阵亡"; + this.el.kda.textContent = `${kills} / ${deaths}`; + if (v < this._lastHp) this.damageFlash(); + this._lastHp = v; + } + + setAmmo(name, mag, reserve, reloading, progress, magSize) { + this.el.wname.textContent = name; + this.el.mag.textContent = mag; + this.el.reserve.textContent = reserve; + this.el.mag.classList.toggle("empty", mag === 0 && !reloading); + if (reloading) { + this.el.reloadTrack.hidden = false; + this.el.reloadFill.style.width = `${Math.min(100, Math.max(0, progress * 100))}%`; + } else { + this.el.reloadTrack.hidden = true; + } + if (magSize) this.el.mag.title = `${mag} / ${magSize}`; + } + + setCrosshair(spread) { + const gap = 4 + spread * 26; + this.root.style.setProperty("--ch-gap", `${gap.toFixed(1)}px`); + } + + hitmarker(kill) { + const hm = this.el.hitmarker; + hm.classList.remove("on", "kill"); + void hm.offsetWidth; + hm.classList.add("on"); + if (kill) hm.classList.add("kill"); + clearTimeout(this._hmTimer); + this._hmTimer = setTimeout(() => hm.classList.remove("on", "kill"), 240); + } + + damageFlash() { + const f = this.el.dmgFlash; + f.classList.add("on"); + clearTimeout(this._dmgTimer); + this._dmgTimer = setTimeout(() => f.classList.remove("on"), 70); + } + + killfeed(byName, victimName, weapon, head, mine) { + const d = document.createElement("div"); + d.className = "kf" + (mine === "me" ? " me" : mine === "foe" ? " foe" : ""); + d.innerHTML = `${byName} + ${weapon} + ${head ? "爆头" : ""} + ${victimName}`; + this.el.killfeed.prepend(d); + while (this.el.killfeed.children.length > 5) this.el.killfeed.lastChild.remove(); + setTimeout(() => d.remove(), 6500); + } + + banner(kicker, title, sub, ms = 1600) { + clearTimeout(this._bannerTimer); + this.el.bannerKicker.textContent = kicker || ""; + this.el.bannerTitle.textContent = title || ""; + this.el.bannerSub.textContent = sub || ""; + this.el.banner.hidden = false; + this._bannerTimer = setTimeout(() => { + this.el.banner.hidden = true; + }, ms); + } + + death(killer, weapon) { + this.el.deathBy.textContent = killer; + this.el.deathWeapon.textContent = weapon; + this.el.deathScreen.hidden = false; + } + + hideDeath() { + this.el.deathScreen.hidden = true; + } + + setDeathCountdown(ms) { + this.el.deathCount.textContent = (Math.max(0, ms) / 1000).toFixed(1); + } + + scoreboard(players, selfSlot, score, target, spectating) { + const rows = []; + for (const p of players) { + const mine = p.slot === selfSlot; + rows.push(`
+ ${p.name}${p.bot ? " · BOT" : ""}${mine ? " · 你" : ""} + ${p.kills} + ${p.deaths} + ${p.alive ? "存活" : "阵亡"} +
`); + } + if (spectating) { + rows.push(`
观战中---
`); + } + this.el.sbRows.innerHTML = rows.join(""); + this.el.sbFoot.textContent = `${score[0]} : ${score[1]} · 先到 ${target} 分获胜`; + } + + setSpectate(on) { + this.el.specBadge.hidden = !on; + this.el.spectateBar.hidden = !on; + } + + waiting(on, code) { + this.el.waiting.hidden = !on; + if (code) this.el.waitCode.textContent = code; + } + + pause(on) { + this.el.pauseScreen.hidden = !on; + } + + setNet(fps, ping) { + this.el.fps.textContent = fps; + this.el.ping.textContent = ping; + } +} diff --git a/public/js/client/main.js b/public/js/client/main.js new file mode 100644 index 0000000..06ba782 --- /dev/null +++ b/public/js/client/main.js @@ -0,0 +1,1088 @@ +// 客户端主控:连接、房间、输入、预测回滚、开枪表现、回合 UI。 +// 物理与命中都以服务端为准,本地只做「看起来跟手」的预测。 + +import { Renderer } from "./renderer.js"; +import { Hud } from "./hud.js"; +import { Sound } from "./sound.js"; +import { Net } from "./net.js"; +import { WEAPONS, weaponOf } from "./weapons.js"; +import { stepBody, makeBody, K, MOVE } from "./movement.js"; +import { ViewModel } from "./viewmodel.js"; + +const $ = (id) => document.getElementById(id); +const TICK = 1 / 60; +const clamp = (v, a, b) => Math.min(b, Math.max(a, v)); + +const canvas = $("gl"); +const hud = new Hud(); +const sound = new Sound(); +const viewmodel = new ViewModel(document.getElementById("vm")); +const renderer = (() => { + try { + return new Renderer(canvas); + } catch (e) { + document.body.innerHTML = `
+

无法启动 3D 渲染

${e.message}

+

请用较新的 Chrome / Edge / Safari / Firefox 打开,并确认没有关闭硬件加速。

+
`; + throw e; + } +})(); + +const S = { + scene: "lobby", + code: null, + you: null, + spectating: false, + level: null, + players: [], + render: new Map(), + wasFiring: new Map(), + phase: "freeze", + roundNo: 0, + score: [0, 0], + target: 8, + leftMs: 0, + paused: false, + spectators: 0, + matchOver: false, + deathInfo: null, + // 本地角色 + body: null, + err: { x: 0, y: 0, z: 0 }, + yaw: 0, + pitch: 0, + hp: 100, + alive: true, + kills: 0, + deaths: 0, + weapon: 0, + mag: 30, + reserve: 90, + reloadLeft: 0, + reloadTotal: 1, + nextFire: 0, + emptyPlayed: false, + firedThisPress: false, + history: [], + seq: 0, + recoil: { pitch: 0, yaw: 0 }, + vm: { bobX: 0, bobY: 0, kick: 0, swayX: 0, swayY: 0 }, + muzzle: 0, + shake: 0, + drop: 0, + walkPhase: 0, + reloadPulse: 0, + // 观战 + spec: { pos: [0, 13, 24], yaw: 0, pitch: -0.4 }, + // 特效 + particles: [], + tracers: [], + // 其他 + fps: 60, + frames: 0, + fpsAt: performance.now(), + t: 0, + demo: /(?:\?|&)demo=1/.test(location.search), + locked: false, + sens: 1, +}; + +/* -------------------------------- 大厅 / 连接 -------------------------------- */ + +const lobby = $("lobby"); +const netDot = $("netDot"); +const netText = $("netText"); + +let net = null; +let wantRejoin = false; + +function setNet(text, ok) { + netText.textContent = text; + netDot.classList.toggle("on", ok === true); + netDot.classList.toggle("off", ok === false); +} + +function toast(text, ms = 2200) { + const t = $("toast"); + t.textContent = text; + t.classList.add("on"); + clearTimeout(t._timer); + t._timer = setTimeout(() => t.classList.remove("on"), ms); +} + +function send(obj) { + if (net) net.send(obj); +} + +function connect() { + net = new Net({ + onOpen: () => { + setNet("已连接 · 等待进入房间", true); + if (wantRejoin && S.code) { + send({ t: "join", code: S.code, spectate: S.spectating }); + } + }, + onClose: () => { + setNet("连接断开,正在重连…", false); + setTimeout(() => { + if (!net.ws) connect(); + }, 1200); + }, + onMessage: onMessage, + }); + net.connect(); +} + +/* --------------------------------- 房间入口 --------------------------------- */ + +function join(code, spectate) { + sound.ensure(); + if (!code) { + toast("先输入 4 位房号"); + return; + } + wantRejoin = true; + send({ t: "join", code: code.trim().toUpperCase(), spectate: !!spectate }); +} + +function createRoom() { + sound.ensure(); + wantRejoin = true; + send({ t: "create" }); +} + +function practice() { + sound.ensure(); + wantRejoin = true; + send({ t: "create" }); + S.pendingBot = true; +} + +function leaveToLobby() { + send({ t: "leave" }); + wantRejoin = false; + S.scene = "lobby"; + S.code = null; + S.you = null; + S.spectating = false; + S.players = []; + S.render.clear(); + S.history = []; + S.particles = []; + S.tracers = []; + S.matchOver = false; + hud.show(false); + hud.pause(false); + hud.waiting(false); + hud.setSpectate(false); + $("matchOver").hidden = true; + lobby.hidden = false; + if (document.pointerLockElement) document.exitPointerLock(); + history.replaceState(null, "", location.pathname); +} + +async function loadLevel() { + if (S.level) return S.level; + const res = await fetch("/level.json", { cache: "no-cache" }); + S.level = await res.json(); + renderer.setLevel(S.level); + return S.level; +} + +async function enterGame(msg) { + await loadLevel(); + S.scene = "game"; + S.code = msg.code; + S.you = msg.you; + S.spectating = !!msg.spectating; + S.matchOver = false; + S.deathInfo = null; + S.history = []; + S.seq = 0; + S.particles = []; + S.tracers = []; + S.players = []; + S.render.clear(); + S.wasFiring.clear(); + S.alive = true; + S.hp = 100; + S.err = { x: 0, y: 0, z: 0 }; + + lobby.hidden = true; + hud.show(true); + hud.setSpectate(S.spectating); + hud.waiting(false); + hud.hideDeath(); + $("matchOver").hidden = true; + + const spawn = (S.level.spawns || [])[S.you ?? 0] || { pos: [0, 0, 0], yaw: 0 }; + const sp = spawn.pos || [0, 0, 0]; + S.yaw = spawn.yaw ? (spawn.yaw * Math.PI) / 180 : 0; + S.pitch = 0; + S.body = makeBody(sp[0], sp[1], sp[2]); + S.err = { x: 0, y: 0, z: 0 }; + S.weapon = 0; + S.mags = WEAPONS.map((w) => w.mag); + S.reserves = WEAPONS.map((w) => w.reserve); + S.mag = S.mags[0]; + S.reserve = S.reserves[0]; + S.reloadLeft = 0; + S.nextFire = 0; + + const yaw = S.yaw; + S.spec.pos = [sp[0] - Math.sin(yaw) * 6, sp[1] + 6, sp[2] + Math.cos(yaw) * 6]; + S.spec.yaw = yaw; + S.spec.pitch = -0.3; + + if (S.pendingBot) { + S.pendingBot = false; + setTimeout(() => send({ t: "addBot" }), 120); + } + + if (!S.demo) { + toast("点击画面锁定鼠标 · WASD 移动", 2600); + try { + await canvas.requestPointerLock(); + } catch { + /* 需要用户点一下 */ + } + } + hud.banner("沙漠据点", S.spectating ? "观战" : "准备", S.spectating ? "自由视角观看" : "每回合满血满弹 · 先到 8 分", 2000); +} + +/* --------------------------------- 消息处理 --------------------------------- */ + +function onMessage(msg) { + switch (msg.t) { + case "welcome": + enterGame(msg); + break; + case "snap": + onSnap(msg); + break; + case "shot": + onShot(msg); + break; + case "kill": + onKill(msg); + break; + case "round": + onRound(msg); + break; + case "match": + onMatch(msg); + break; + case "err": + toast(msg.msg || "出错了"); + break; + case "left": + leaveToLobby(); + break; + default: + break; + } +} + +function slotName(slot) { + const p = S.players.find((x) => x.slot === slot); + if (!p) return slot === S.you ? "你" : "对手"; + if (slot === S.you) return "你"; + return p.bot ? "机器人" : p.name; +} + +function onSnap(s) { + const prevPhase = S.phase; + S.players = s.players || []; + S.phase = s.phase; + S.roundNo = s.roundNo; + S.score = s.score; + S.target = s.target; + S.leftMs = s.leftMs; + S.paused = s.paused; + S.spectators = s.spectators; + S.matchOver = s.phase === "matchOver"; + + const me = S.players.find((p) => p.slot === S.you); + if (me) { + S.hp = me.hp; + S.alive = me.alive; + S.kills = me.kills; + S.deaths = me.deaths; + S.weapon = me.weapon; + S.mag = me.mag; + S.reserve = me.reserve; + if (!S.mags) S.mags = WEAPONS.map((w) => w.mag); + if (!S.reserves) S.reserves = WEAPONS.map((w) => w.reserve); + S.mags[me.weapon] = me.mag; + S.reserves[me.weapon] = me.reserve; + S.reloadLeft = me.reloadLeft ? me.reloadLeft / 1000 : 0; + S.reloadTotal = Math.max(0.2, weaponOf(me.weapon).reload); + + if (me.alive) { + hud.hideDeath(); + S.deathInfo = null; + } + reconcile(me); + } + + // 对手离开 / 房间空着 + const needOpponent = !S.spectating && S.players.length < 2; + hud.waiting(needOpponent, S.code); + + // 远端开火 → 枪口火光 + 声音 + for (const p of S.players) { + const was = S.wasFiring.get(p.slot) || false; + if (p.firing && !was) { + const eye = [p.pos[0], p.pos[1] + MOVE.eye, p.pos[2]]; + const dir = [ + Math.sin(p.yaw) * Math.cos(p.pitch), + Math.sin(p.pitch), + -Math.cos(p.yaw) * Math.cos(p.pitch), + ]; + const muzzle = [eye[0] + dir[0] * 0.7, eye[1] + dir[1] * 0.7 - 0.1, eye[2] + dir[2] * 0.7]; + spawnFlash(muzzle, 0.34); + if (p.slot !== S.you) { + const camPos = cameraPos(); + const dx = eye[0] - camPos[0]; + const dz = eye[2] - camPos[2]; + const dist = Math.hypot(dx, dz); + const pan = clamp((Math.cos(S.yaw) * dx + Math.sin(S.yaw) * dz) / (dist || 1), -1, 1); + sound.shot(p.weapon, pan * 0.85, dist, false); + } + } + S.wasFiring.set(p.slot, p.firing); + } + + hud.setScore(S.score[0], S.score[1], S.target, S.players.find((p) => p.slot !== S.you)?.name); + hud.setRound(S.roundNo, S.phase === "matchOver" ? null : S.leftMs); + if (me) hud.setHp(S.hp, S.alive, S.kills, S.deaths); + hud.setAmmo( + weaponOf(S.weapon).name, + S.mag, + S.reserve, + S.reloadLeft > 0, + S.reloadLeft > 0 ? 1 - S.reloadLeft / S.reloadTotal : 0, + weaponOf(S.weapon).mag + ); +} + +function reconcile(me) { + if (!S.body) { + S.body = makeBody(me.pos[0], me.pos[1], me.pos[2]); + S.err = { x: 0, y: 0, z: 0 }; + } + const old = { x: S.body.pos.x + S.err.x, y: S.body.pos.y + S.err.y, z: S.body.pos.z + S.err.z }; + + const ack = me.ack || 0; + S.history = S.history.filter((h) => h.seq > ack); + + const body = makeBody(me.pos[0], me.pos[1], me.pos[2]); + body.vel = { x: me.vel[0], y: me.vel[1], z: me.vel[2] }; + body.onGround = !!me.ground; + + if (S.phase === "live" && me.alive && S.level) { + for (const h of S.history) { + stepBody(body, h.keys, h.yaw, S.level, TICK); + } + } + + const err = { x: old.x - body.pos.x, y: old.y - body.pos.y, z: old.z - body.pos.z }; + const len = Math.hypot(err.x, err.y, err.z); + if (!Number.isFinite(len) || len > 3) { + S.err = { x: 0, y: 0, z: 0 }; + } else { + S.err = { + x: clamp(err.x, -1.5, 1.5), + y: clamp(err.y, -1.5, 1.5), + z: clamp(err.z, -1.5, 1.5), + }; + } + S.body = body; +} + +function onShot(m) { + const hit = m.hit; + // 曳光弹:从枪口到命中点 + const from = [m.from[0], m.from[1] - 0.12, m.from[2]]; + S.tracers.push({ from, to: m.to, life: 0.075 }); + if (S.tracers.length > 40) S.tracers.shift(); + + if (hit) { + spawnImpact(m.to, hit.head || hit.dmg > 60); + if (hit.slot === S.you) { + S.shake = Math.min(1.2, S.shake + 0.5); + sound.hurt(); + hud.damageFlash(); + } + if (m.by === S.you) { + hud.hitmarker(hit.hp <= 0); + sound.hit(hit.head); + } + } else { + spawnImpact(m.to, false); + } +} + +function onKill(m) { + const by = m.by == null ? null : slotName(m.by); + const victim = slotName(m.victim); + const mine = m.by === S.you ? "me" : m.victim === S.you ? "foe" : ""; + hud.killfeed(by || "环境", victim, m.weapon, m.head, mine); + if (m.victim === S.you) { + S.deathInfo = m; + hud.death(by || "对手", m.weapon); + sound.death(); + } else if (m.by === S.you) { + sound.kill(); + } +} + +function onRound(r) { + if (r.phase === "freeze") { + hud.hideDeath(); + S.deathInfo = null; + S.drop = 0; + S.recoil = { pitch: 0, yaw: 0 }; + S.reloadLeft = 0; + S.mag = WEAPONS[0].mag; + S.reserve = WEAPONS[0].reserve; + S.weapon = 0; + hud.banner(`第 ${r.roundNo} 回合`, "准备", `${r.score[0]} : ${r.score[1]} · 3 秒后开打`, 2200); + sound.roundStart(); + } else if (r.phase === "live") { + hud.banner("", "开始", "", 850); + } else if (r.phase === "over") { + const win = r.winner === S.you; + hud.banner(win ? "本回合胜利" : "本回合失败", r.reason || "", `${r.score[0]} : ${r.score[1]}`, 2400); + sound.roundEnd(win); + } +} + +function onMatch(m) { + S.matchOver = true; + const win = m.winner === S.you; + $("matchTitle").textContent = win ? "胜利" : "失败"; + $("matchTitle").classList.toggle("lose", !win); + const meScore = S.you == null ? m.score[0] : m.score[S.you]; + const foeScore = S.you == null ? m.score[1] : m.score[1 - S.you]; + $("matchMe").textContent = meScore; + $("matchFoe").textContent = foeScore; + $("matchSub").textContent = win ? "干得漂亮,全场的枪都听你的" : "再来一场,把分追回来"; + $("matchOver").hidden = false; + hud.banner("", win ? "比赛胜利" : "比赛失败", "", 2000); + sound.roundEnd(win); + if (document.pointerLockElement) document.exitPointerLock(); +} + +/* ----------------------------------- 输入 ----------------------------------- */ + +const keys = { fwd: false, back: false, left: false, right: false, jump: false, walk: false }; +const mouse = { left: false }; + +function keyMask() { + let k = 0; + if (keys.fwd) k |= K.FWD; + if (keys.back) k |= K.BACK; + if (keys.left) k |= K.LEFT; + if (keys.right) k |= K.RIGHT; + if (keys.jump) k |= K.JUMP; + if (keys.walk) k |= K.WALK; + return k; +} + +window.addEventListener("keydown", (e) => { + if (e.code === "Tab") { + e.preventDefault(); + if (S.scene === "game") { + hud.scoreboard(S.players, S.you, S.score, S.target, S.spectating); + hud.el.scoreboard.hidden = false; + } + return; + } + if (S.scene !== "game") { + if (e.code === "Enter") $("createBtn").click(); + return; + } + switch (e.code) { + case "KeyW": + keys.fwd = true; + break; + case "KeyS": + keys.back = true; + break; + case "KeyA": + keys.left = true; + break; + case "KeyD": + keys.right = true; + break; + case "Space": + e.preventDefault(); + keys.jump = true; + break; + case "ShiftLeft": + case "ShiftRight": + keys.walk = true; + break; + case "KeyR": + startReload(); + break; + case "Digit1": + switchWeapon(0); + break; + case "Digit2": + switchWeapon(1); + break; + default: + break; + } +}); + +window.addEventListener("keyup", (e) => { + switch (e.code) { + case "Tab": + hud.el.scoreboard.hidden = true; + break; + case "KeyW": + keys.fwd = false; + break; + case "KeyS": + keys.back = false; + break; + case "KeyA": + keys.left = false; + break; + case "KeyD": + keys.right = false; + break; + case "Space": + keys.jump = false; + break; + case "ShiftLeft": + case "ShiftRight": + keys.walk = false; + break; + default: + break; + } +}); + +canvas.addEventListener("mousedown", (e) => { + if (S.scene !== "game") return; + sound.ensure(); + if (!document.pointerLockElement && !S.demo) { + canvas.requestPointerLock()?.catch?.(() => {}); + return; + } + if (e.button === 0) { + mouse.left = true; + S.firedThisPress = false; + } +}); + +window.addEventListener("mouseup", (e) => { + if (e.button === 0) { + mouse.left = false; + S.firedThisPress = false; + } +}); + +document.addEventListener("mousemove", (e) => { + if (S.scene !== "game") return; + if (!S.locked) return; + const k = 0.0021 * S.sens; + if (S.spectating) { + S.spec.yaw += e.movementX * k; + S.spec.pitch = clamp(S.spec.pitch - e.movementY * k, -1.5, 1.5); + } else { + S.yaw += e.movementX * k; + S.pitch = clamp(S.pitch - e.movementY * k, -1.53, 1.53); + } +}); + +document.addEventListener("pointerlockchange", () => { + S.locked = document.pointerLockElement === canvas; + if (S.scene !== "game") return; + if (!S.locked && !S.demo && !S.matchOver) hud.pause(true); + if (S.locked) hud.pause(false); +}); + +document.addEventListener("pointerlockerror", () => { + if (S.scene === "game" && !S.demo) toast("浏览器拒绝了鼠标锁定,点一下画面再试"); +}); + +canvas.addEventListener("click", () => { + if (S.scene === "game" && !S.locked && !S.demo) { + canvas.requestPointerLock()?.catch?.(() => {}); + } +}); + +function switchWeapon(id) { + if (S.spectating || S.weapon === id) return; + S.weapon = id; + S.reloadLeft = 0; + S.mag = S.mags ? S.mags[id] : weaponOf(id).mag; + S.reserve = S.reserves ? S.reserves[id] : weaponOf(id).reserve; + S.nextFire = performance.now() / 1000 + 0.2; + sound.reload(1); +} + +function startReload() { + if (S.spectating) return; + const w = weaponOf(S.weapon); + if (S.reloadLeft > 0 || S.mag >= w.mag || S.reserve <= 0) return; + S.reloadLeft = w.reload; + S.reloadTotal = w.reload; + S.reloadPulse = 0.18; + sound.reload(0); + setTimeout(() => sound.reload(1), w.reload * 500); +} + +/* ----------------------------------- 射击 ----------------------------------- */ + +function tryFire() { + if (S.spectating || !S.alive || S.phase !== "live" || !S.body) return; + const w = weaponOf(S.weapon); + const now = performance.now() / 1000; + if (S.reloadLeft > 0 || now < S.nextFire) return; + if (!mouse.left) return; + if (!w.auto && S.firedThisPress) return; + + if (S.mag <= 0) { + if (!S.emptyPlayed) { + sound.empty(); + S.emptyPlayed = true; + startReload(); + } + return; + } + S.emptyPlayed = false; + S.firedThisPress = true; + S.mag--; + S.nextFire = now + w.interval; + sound.shot(S.weapon, 0, 0, true); + S.recoil.pitch += w.kick; + S.recoil.yaw += (Math.random() - 0.5) * w.kick * 0.45; + S.vm.kick = Math.min(1.6, S.vm.kick + 1); + S.muzzle = 0.06; + S.shake = Math.min(1, S.shake + 0.22); +} + +/* ----------------------------------- 特效 ----------------------------------- */ + +function spawnFlash(pos, size) { + S.particles.push({ + pos: pos.slice(), + vel: [0, 0, 0], + size, + color: [1.0, 0.7, 0.28], + alpha: 0.95, + life: 0.055, + max: 0.055, + drag: 0, + }); +} + +function spawnImpact(pos, blood) { + const n = blood ? 12 : 8; + for (let i = 0; i < n; i++) { + const a = Math.random() * Math.PI * 2; + const up = Math.random() * 2.4; + const sp = 1.5 + Math.random() * 3.2; + S.particles.push({ + pos: [pos[0], pos[1], pos[2]], + vel: [Math.cos(a) * sp, up, Math.sin(a) * sp], + size: blood ? 0.09 + Math.random() * 0.08 : 0.05 + Math.random() * 0.05, + color: blood ? [0.62, 0.06, 0.06] : [1.0, 0.78, 0.35], + alpha: 0.95, + life: blood ? 0.5 : 0.3, + max: blood ? 0.5 : 0.3, + drag: 3.5, + gravity: 9, + }); + } +} + +function updateFx(dt) { + for (let i = S.particles.length - 1; i >= 0; i--) { + const p = S.particles[i]; + p.life -= dt; + if (p.life <= 0) { + S.particles.splice(i, 1); + continue; + } + if (p.drag) { + const k = Math.max(0, 1 - p.drag * dt); + p.vel[0] *= k; + p.vel[1] *= k; + p.vel[2] *= k; + } + if (p.gravity) p.vel[1] -= p.gravity * dt; + p.pos[0] += p.vel[0] * dt; + p.pos[1] += p.vel[1] * dt; + p.pos[2] += p.vel[2] * dt; + p.alpha = Math.max(0, p.life / p.max) * 0.95; + } + for (let i = S.tracers.length - 1; i >= 0; i--) { + S.tracers[i].life -= dt; + if (S.tracers[i].life <= 0) S.tracers.splice(i, 1); + } + if (S.particles.length > 420) S.particles.splice(0, S.particles.length - 420); +} + +/* ----------------------------------- 主循环 ----------------------------------- */ + +let acc = 0; +let last = performance.now(); + +function frame(now) { + const dt = Math.min(0.08, (now - last) / 1000); + last = now; + S.t += dt; + + S.frames++; + if (now - S.fpsAt > 500) { + S.fps = Math.round((S.frames * 1000) / (now - S.fpsAt)); + S.frames = 0; + S.fpsAt = now; + hud.setNet(S.fps, net ? net.rtt : 0); + } + + if (S.scene === "game") { + updateGame(dt); + drawGame(); + } else { + drawLobbyCam(); + viewmodel.clear(); + } + requestAnimationFrame(frame); +} + +function updateGame(dt) { + // 预测修正残差衰减 + const decay = Math.exp(-12 * dt); + S.err.x *= decay; + S.err.y *= decay; + S.err.z *= decay; + + if (S.spectating) { + updateSpectator(dt); + } else if (S.body) { + updatePlayer(dt); + } + + smoothRemote(dt); + updateFx(dt); + S.muzzle = Math.max(0, S.muzzle - dt); + S.shake = Math.max(0, S.shake - dt * 2.4); + S.reloadLeft = Math.max(0, S.reloadLeft - dt); + S.reloadPulse = Math.max(0, S.reloadPulse - dt); + if (!mouse.left) S.firedThisPress = false; + // 死亡镜头下沉 + if (!S.alive && !S.spectating) S.drop = Math.min(1, S.drop + dt * 3.2); + else if (S.alive) S.drop = Math.max(0, S.drop - dt * 6); + + // 换弹进度条 + if (S.reloadLeft > 0) { + hud.setAmmo( + weaponOf(S.weapon).name, + S.mag, + S.reserve, + true, + 1 - S.reloadLeft / S.reloadTotal, + weaponOf(S.weapon).mag + ); + } + if (S.deathInfo && !S.alive) { + hud.setDeathCountdown(S.leftMs); + } + if (S.players.length < 2 && !S.spectating) { + hud.waiting(true, S.code); + } +} + +function updatePlayer(dt) { + const live = S.phase === "live" && S.alive; + const keysNow = live ? keyMask() : 0; + + acc += dt; + let steps = 0; + while (acc >= TICK && steps < 3) { + acc -= TICK; + steps++; + S.seq++; + if (live && S.level) { + stepBody(S.body, keysNow, S.yaw, S.level, TICK); + } + S.history.push({ seq: S.seq, keys: keysNow, yaw: S.yaw }); + if (S.history.length > 240) S.history.shift(); + tryFire(); + } + if (steps >= 3) acc = 0; + + if (steps > 0) { + net.send({ + t: "input", + seq: S.seq, + keys: keysNow, + yaw: S.yaw, + pitch: S.pitch, + fire: mouse.left && live, + reload: S.reloadPulse > 0, + weapon: S.weapon, + }); + } + + // 后坐力回正 + const rk = Math.exp(-7 * dt); + S.recoil.pitch *= rk; + S.recoil.yaw *= rk; + + // 枪模摆动 + const speed = Math.hypot(S.body.vel.x, S.body.vel.z); + if (S.body.onGround && speed > 0.4) { + S.walkPhase += dt * (6 + speed * 1.4); + } else { + S.walkPhase += dt * 1.2; + } + const bobAmt = S.body.onGround ? Math.min(1, speed / MOVE.run) : 0.2; + S.vm.bobX = Math.sin(S.walkPhase) * 0.011 * bobAmt; + S.vm.bobY = -Math.abs(Math.cos(S.walkPhase)) * 0.009 * bobAmt; + S.vm.kick = Math.max(0, S.vm.kick - dt * 9); + S.vm.swayX = Math.sin(S.walkPhase * 0.5) * 0.004; + + // 打空自动换弹 + if (S.mag === 0 && S.reloadLeft <= 0 && S.reserve > 0) startReload(); + + // 脚步声 + if (live && S.body.onGround && speed > 1.2) { + S.stepTimer = (S.stepTimer || 0) - dt * speed; + if (S.stepTimer <= 0) { + S.stepTimer = 3.4; + if (!keys.walk) sound.step(); + } + } +} + +function updateSpectator(dt) { + const k = keyMask(); + const yaw = S.spec.yaw; + const pitch = S.spec.pitch; + const cp = Math.cos(pitch); + const fwd = [Math.sin(yaw) * cp, Math.sin(pitch), -Math.cos(yaw) * cp]; + const right = [Math.cos(yaw), 0, Math.sin(yaw)]; + const speed = (k & K.WALK ? 26 : 10) * dt; + const pos = S.spec.pos; + if (k & K.FWD) { + pos[0] += fwd[0] * speed; + pos[1] += fwd[1] * speed; + pos[2] += fwd[2] * speed; + } + if (k & K.BACK) { + pos[0] -= fwd[0] * speed; + pos[1] -= fwd[1] * speed; + pos[2] -= fwd[2] * speed; + } + if (k & K.RIGHT) { + pos[0] += right[0] * speed; + pos[2] += right[2] * speed; + } + if (k & K.LEFT) { + pos[0] -= right[0] * speed; + pos[2] -= right[2] * speed; + } + pos[1] = clamp(pos[1], 0.4, 60); + S.spec.pos = pos; +} + +function cameraPos() { + if (S.spectating) return S.spec.pos; + if (!S.body) return [0, 2, 0]; + if (!Number.isFinite(S.body.pos.x + S.err.x)) return [0, 2, 0]; + return [ + S.body.pos.x + S.err.x, + S.body.pos.y + MOVE.eye + S.err.y - S.drop * 1.15, + S.body.pos.z + S.err.z, + ]; +} + +function smoothRemote(dt) { + const k = 1 - Math.exp(-14 * dt); + const ky = 1 - Math.exp(-18 * dt); + for (const p of S.players) { + let r = S.render.get(p.slot); + if (!r) { + r = { pos: [p.pos[0], p.pos[1], p.pos[2]], yaw: p.yaw }; + S.render.set(p.slot, r); + } + r.pos[0] += (p.pos[0] - r.pos[0]) * k; + r.pos[1] += (p.pos[1] - r.pos[1]) * k; + r.pos[2] += (p.pos[2] - r.pos[2]) * k; + let d = ((p.yaw - r.yaw + Math.PI * 3) % (Math.PI * 2)) - Math.PI; + r.yaw += d * ky; + } +} + +function drawGame() { + const pos = cameraPos(); + const yaw = S.spectating ? S.spec.yaw : S.yaw + S.recoil.yaw + (Math.random() - 0.5) * S.shake * 0.006; + const pitch = S.spectating ? S.spec.pitch : S.pitch + S.recoil.pitch + (Math.random() - 0.5) * S.shake * 0.006; + + const players = S.players.map((p) => { + const r = S.render.get(p.slot); + return { + slot: p.slot, + pos: r ? r.pos : p.pos, + yaw: r ? r.yaw : p.yaw, + alive: p.alive, + bot: p.bot, + hp: p.hp, + }; + }); + + renderer.render({ + pos, + yaw, + pitch, + fov: 78, + players, + selfSlot: S.you, + spectating: S.spectating, + weaponDef: WEAPONS[S.weapon], + vm: S.vm, + muzzle: S.muzzle, + particles: S.particles, + tracers: S.tracers, + }); + + // 准星张合:移动 / 腾空 / 后坐力 + const speed = S.body ? Math.hypot(S.body.vel.x, S.body.vel.z) : 0; + const air = S.body && !S.body.onGround ? 1 : 0; + const spread = weaponOf(S.weapon).spread * 6 + speed * 0.12 + air * 0.5 + Math.abs(S.recoil.pitch) * 6; + hud.setCrosshair(spread); + + if (S.spectating || S.scene !== "game") { + viewmodel.clear(); + } else { + viewmodel.render({ + weapon: S.weapon, + bobX: S.vm.bobX, + bobY: S.vm.bobY, + kick: S.vm.kick, + swayX: S.vm.swayX, + muzzle: S.muzzle, + alive: S.alive && !S.matchOver, + }); + } +} + +// 大厅背景:围着地图慢慢转,顺便确认渲染正常 +function drawLobbyCam() { + if (!S.level) return; + const t = S.t * 0.09; + const pos = [Math.cos(t) * 27, 12 + Math.sin(t * 1.7) * 1.4, Math.sin(t) * 27]; + const dx = 0 - pos[0]; + const dy = 2.2 - pos[1]; + const dz = 0 - pos[2]; + const yaw = Math.atan2(dx, -dz); + const pitch = Math.atan2(dy, Math.hypot(dx, dz)); + renderer.render({ + pos, + yaw, + pitch, + fov: 62, + players: [], + selfSlot: null, + spectating: true, + weaponDef: null, + vm: {}, + muzzle: 0, + particles: [], + tracers: [], + }); +} + +/* ----------------------------------- UI 绑定 ----------------------------------- */ + +$("createBtn").addEventListener("click", createRoom); +$("practiceBtn").addEventListener("click", practice); +$("joinBtn").addEventListener("click", () => { + const code = $("codeInput").value.trim().toUpperCase(); + if (!code) return toast("先输入房号"); + join(code, false); +}); +$("specBtn").addEventListener("click", () => { + const code = $("codeInput").value.trim().toUpperCase(); + if (!code) return toast("先输入要观战的房号"); + join(code, true); +}); +$("codeInput").addEventListener("keydown", (e) => { + if (e.key === "Enter") $("joinBtn").click(); +}); +$("resumeBtn").addEventListener("click", () => { + hud.pause(false); + canvas.requestPointerLock()?.catch?.(() => {}); +}); +$("quitBtn").addEventListener("click", leaveToLobby); +$("specLeave").addEventListener("click", leaveToLobby); +$("matchQuit").addEventListener("click", leaveToLobby); +$("rematchBtn").addEventListener("click", () => { + $("matchOver").hidden = true; + send({ t: "rematch" }); + canvas.requestPointerLock()?.catch?.(() => {}); +}); +$("waitBot").addEventListener("click", () => send({ t: "addBot" })); +$("joinBtn").addEventListener("click", () => sound.ensure()); +$("practiceBtn").addEventListener("click", () => sound.ensure()); + +const savedSens = parseFloat(localStorage.getItem("cs_sens") || "1"); +S.sens = clamp(savedSens || 1, 0.2, 3); +for (const [input, label] of [ + ["sensLobby", "sensValLobby"], + ["sens", "sensVal"], +]) { + const el = $(input); + const lb = $(label); + el.value = String(S.sens); + lb.textContent = S.sens.toFixed(2); + el.addEventListener("input", () => { + S.sens = parseFloat(el.value); + lb.textContent = S.sens.toFixed(2); + localStorage.setItem("cs_sens", String(S.sens)); + for (const other of ["sensLobby", "sens"]) $(other).value = String(S.sens); + for (const other of ["sensValLobby", "sensVal"]) $(other).textContent = S.sens.toFixed(2); + }); +} + +// 邀请链接 #房号 +const hash = location.hash.replace("#", "").trim().toUpperCase(); +if (hash.length === 4) $("codeInput").value = hash; + +// 调试 / 自动化验证用(不影响游戏逻辑) +window.__CS = S; +window.__R = renderer; + +connect(); +loadLevel().then(() => { + requestAnimationFrame(frame); +}); + +/* ----------------------------------- 演示模式 ----------------------------------- */ +// ?demo=1:自动建房 + 机器人,镜头慢慢扫,用来做无人工验证 / 截图 +if (S.demo) { + S.sens = 1; + setTimeout(() => { + createRoom(); + S.pendingBot = true; + }, 350); + let demoT = 0; + setInterval(() => { + if (!S.demo || S.scene !== "game" || !S.body) return; + demoT += 0.1; + const spawnYaw = (S.level.spawns[S.you ?? 0]?.[3] || 0) * Math.PI / 180; + S.yaw = spawnYaw + Math.sin(demoT * 0.28) * 0.75; + S.pitch = -0.03 + Math.sin(demoT * 0.19) * 0.05; + mouse.left = demoT % 3.2 < 0.6; + }, 100); +} diff --git a/public/js/client/movement.js b/public/js/client/movement.js new file mode 100644 index 0000000..40f2b10 --- /dev/null +++ b/public/js/client/movement.js @@ -0,0 +1,199 @@ +// 角色移动物理 —— src/physics.rs 的 JS 镜像。 +// 客户端预测与服务端用同一套常数和同样的积分顺序,服务端快照才是权威。 + +export const MOVE = { + gravity: 18, + jump: 6.2, + run: 5.6, + walk: 2.7, + accelGround: 11, + accelAir: 2.2, + friction: 8, + radius: 0.36, + height: 1.75, + eye: 1.62, + stepUp: 0.55, + maxFall: 55, +}; + +export const K = { FWD: 1, BACK: 2, LEFT: 4, RIGHT: 8, JUMP: 16, WALK: 32 }; + +export function makeBody(x, y, z) { + return { pos: { x, y, z }, vel: { x: 0, y: 0, z: 0 }, onGround: false }; +} + +export function eyeOf(pos) { + return { x: pos.x, y: pos.y + MOVE.eye, z: pos.z }; +} + +function blockerAt(level, pos) { + const R = MOVE.radius; + const minx = pos.x - R; + const maxx = pos.x + R; + const miny = pos.y; + const maxy = pos.y + MOVE.height; + const minz = pos.z - R; + const maxz = pos.z + R; + const boxes = level.boxes; + for (let i = 0; i < boxes.length; i++) { + const b = boxes[i]; + if ( + b.min[0] < maxx && + b.max[0] > minx && + b.min[1] < maxy && + b.max[1] > miny && + b.min[2] < maxz && + b.max[2] > minz + ) { + return b; + } + } + return null; +} + +function moveAxis(body, axis, delta, level) { + if (Math.abs(delta) < 1e-6) return; + const steps = Math.max(1, Math.ceil(Math.abs(delta) / 0.2)); + const d = delta / steps; + for (let i = 0; i < steps; i++) { + if (axis === 0) body.pos.x += d; + else if (axis === 2) body.pos.z += d; + else body.pos.y += d; + + const b = blockerAt(level, body.pos); + if (!b) continue; + + // 水平撞到矮台面:抬腿上台阶 + if (axis !== 1 && b.max[1] > body.pos.y && b.max[1] - body.pos.y <= MOVE.stepUp) { + const saved = { ...body.pos }; + body.pos.y = b.max[1] + 1e-3; + if (!blockerAt(level, body.pos)) continue; + body.pos = saved; + } + + if (axis === 0) { + body.pos.x = d > 0 ? b.min[0] - MOVE.radius - 1e-3 : b.max[0] + MOVE.radius + 1e-3; + body.vel.x = 0; + } else if (axis === 2) { + body.pos.z = d > 0 ? b.min[2] - MOVE.radius - 1e-3 : b.max[2] + MOVE.radius + 1e-3; + body.vel.z = 0; + } else { + if (d <= 0) { + body.pos.y = b.max[1]; + body.onGround = true; + } else { + body.pos.y = b.min[1] - MOVE.height - 1e-3; + } + body.vel.y = 0; + } + return; + } +} + +export function stepBody(body, keys, yaw, level, dt) { + const sy = Math.sin(yaw); + const cy = Math.cos(yaw); + + let wx = 0; + let wz = 0; + if (keys & K.FWD) { + wx += sy; + wz -= cy; + } + if (keys & K.BACK) { + wx -= sy; + wz += cy; + } + if (keys & K.RIGHT) { + wx += cy; + wz += sy; + } + if (keys & K.LEFT) { + wx -= cy; + wz -= sy; + } + + const wishLen = Math.hypot(wx, wz); + const maxSpeed = keys & K.WALK ? MOVE.walk : MOVE.run; + + if (wishLen > 1e-4) { + const nx = wx / wishLen; + const nz = wz / wishLen; + const accel = body.onGround ? MOVE.accelGround : MOVE.accelAir; + const current = body.vel.x * nx + body.vel.z * nz; + const add = Math.max(0, Math.min(accel * maxSpeed * dt, maxSpeed - current)); + body.vel.x += nx * add; + body.vel.z += nz * add; + } else if (body.onGround) { + const speed = Math.hypot(body.vel.x, body.vel.z); + if (speed > 0.02) { + const k = Math.max(0, (speed - MOVE.friction * dt) / speed); + body.vel.x *= k; + body.vel.z *= k; + } else { + body.vel.x = 0; + body.vel.z = 0; + } + } + + if (keys & K.JUMP && body.onGround) { + body.vel.y = MOVE.jump; + body.onGround = false; + } + + body.vel.y = Math.max(body.vel.y - MOVE.gravity * dt, -MOVE.maxFall); + + moveAxis(body, 0, body.vel.x * dt, level); + moveAxis(body, 2, body.vel.z * dt, level); + + body.onGround = false; + moveAxis(body, 1, body.vel.y * dt, level); + + let guard = 0; + while (blockerAt(level, body.pos) && guard < 40) { + body.pos.y += 0.1; + guard++; + } + return body; +} + +// 视线检测(调试 / 观战提示用) +export function hasLineOfSight(level, from, to) { + const dx = to.x - from.x; + const dy = to.y - from.y; + const dz = to.z - from.z; + const len = Math.hypot(dx, dy, dz); + if (len < 1e-4) return true; + const nx = dx / len; + const ny = dy / len; + const nz = dz / len; + const maxT = Math.max(0, len - 0.2); + for (const b of level.boxes) { + let t0 = 0; + let t1 = maxT; + let ok = true; + const o = [from.x, from.y, from.z]; + const d = [nx, ny, nz]; + for (let i = 0; i < 3; i++) { + if (Math.abs(d[i]) < 1e-8) { + if (o[i] < b.min[i] || o[i] > b.max[i]) { + ok = false; + break; + } + } else { + const inv = 1 / d[i]; + let ta = (b.min[i] - o[i]) * inv; + let tb = (b.max[i] - o[i]) * inv; + if (ta > tb) [ta, tb] = [tb, ta]; + t0 = Math.max(t0, ta); + t1 = Math.min(t1, tb); + if (t0 > t1) { + ok = false; + break; + } + } + } + if (ok) return false; + } + return true; +} diff --git a/public/js/client/net.js b/public/js/client/net.js new file mode 100644 index 0000000..99e1d44 --- /dev/null +++ b/public/js/client/net.js @@ -0,0 +1,93 @@ +// WebSocket 连接:断线重连交给上层,这里只管收发和 RTT。 + +export class Net { + constructor({ onOpen, onClose, onMessage }) { + this.onOpen = onOpen; + this.onClose = onClose; + this.onMessage = onMessage; + this.ws = null; + this.pingId = 0; + this.pingAt = 0; + this.rtt = 0; + this.retry = 0; + this.closedByUs = false; + this.outbox = []; + } + + url() { + const proto = location.protocol === "https:" ? "wss:" : "ws:"; + return `${proto}//${location.host}/ws`; + } + + connect() { + if (this.ws && (this.ws.readyState === 0 || this.ws.readyState === 1)) return; + this.closedByUs = false; + let ws; + try { + ws = new WebSocket(this.url()); + } catch { + this.onClose?.(); + return; + } + this.ws = ws; + + ws.onopen = () => { + this.retry = 0; + this.startPing(); + const pending = this.outbox.splice(0, this.outbox.length); + for (const m of pending) ws.send(JSON.stringify(m)); + this.onOpen?.(); + }; + ws.onmessage = (ev) => { + let msg; + try { + msg = JSON.parse(ev.data); + } catch { + return; + } + if (msg.t === "pong") { + this.rtt = Math.max(0, Math.round(performance.now() - this.pingAt)); + return; + } + this.onMessage?.(msg); + }; + ws.onclose = () => { + this.stopPing(); + if (!this.closedByUs) this.onClose?.(); + }; + ws.onerror = () => { + /* onclose 会跟上 */ + }; + } + + send(obj) { + if (this.ws && this.ws.readyState === 1) { + this.ws.send(JSON.stringify(obj)); + return true; + } + // 还没连上:排队,连上后补发(只留最近 20 条,避免积压) + this.outbox.push(obj); + if (this.outbox.length > 20) this.outbox.shift(); + return false; + } + + startPing() { + this.stopPing(); + this.pingTimer = setInterval(() => { + this.pingId++; + this.pingAt = performance.now(); + this.send({ t: "ping", id: this.pingId }); + }, 1500); + } + + stopPing() { + clearInterval(this.pingTimer); + } + + close() { + this.closedByUs = true; + this.stopPing(); + if (this.ws) this.ws.close(); + this.ws = null; + } +} diff --git a/public/js/client/renderer.js b/public/js/client/renderer.js new file mode 100644 index 0000000..8b995ac --- /dev/null +++ b/public/js/client/renderer.js @@ -0,0 +1,911 @@ +// 手写 WebGL 渲染器:地图(按材质合批)、玩家模型、第一人称枪模型、 +// 曳光弹、粒子、假投影、黄昏天空。不引第三方库,贴图全部现场生成。 + +const TILE = 2.0; // 一个贴图平铺多少米 + +/* ------------------------------ 矩阵工具(列主序) ------------------------------ */ + +export function mat4() { + const m = new Float32Array(16); + m[0] = m[5] = m[10] = m[15] = 1; + return m; +} + +export function mul(a, b) { + const o = new Float32Array(16); + for (let c = 0; c < 4; c++) { + for (let r = 0; r < 4; r++) { + o[c * 4 + r] = + a[r] * b[c * 4] + + a[4 + r] * b[c * 4 + 1] + + a[8 + r] * b[c * 4 + 2] + + a[12 + r] * b[c * 4 + 3]; + } + } + return o; +} + +export function translate(x, y, z) { + const m = mat4(); + m[12] = x; + m[13] = y; + m[14] = z; + return m; +} + +export function scale(x, y, z) { + const m = mat4(); + m[0] = x; + m[5] = y; + m[10] = z; + return m; +} + +export function rotX(a) { + const m = mat4(); + const c = Math.cos(a); + const s = Math.sin(a); + m[5] = c; + m[6] = s; + m[9] = -s; + m[10] = c; + return m; +} + +export function rotY(a) { + const m = mat4(); + const c = Math.cos(a); + const s = Math.sin(a); + m[0] = c; + m[2] = -s; + m[8] = s; + m[10] = c; + return m; +} + +export function perspective(fovy, aspect, near, far) { + const m = new Float32Array(16); + const f = 1 / Math.tan(fovy / 2); + const nf = 1 / (near - far); + m[0] = f / aspect; + m[5] = f; + m[10] = (far + near) * nf; + m[11] = -1; + m[14] = 2 * far * near * nf; + return m; +} + +export function rotZ(a) { + const m = mat4(); + const c = Math.cos(a); + const s = Math.sin(a); + m[0] = c; + m[1] = s; + m[4] = -s; + m[5] = c; + return m; +} + +function mat3Identity() { + return new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]); +} + +/** 只带偏航的旋转法线矩阵(模型都是绕 Y 转的方块) */ +function yawNormalMat(yaw) { + const c = Math.cos(-yaw); + const s = Math.sin(-yaw); + return new Float32Array([c, 0, -s, 0, 1, 0, s, 0, c]); +} + +function hexToRgb(hex) { + const n = parseInt(hex.slice(1), 16); + return [(n >> 16) & 255, (n >> 8) & 255, n & 255]; +} + +/* --------------------------------- 贴图生成 --------------------------------- */ + +function canvasTex(size) { + const c = document.createElement("canvas"); + c.width = c.height = size; + return c; +} + +function noiseFill(g, size, base, spread) { + const img = g.getImageData(0, 0, size, size); + const d = img.data; + for (let i = 0; i < d.length; i += 4) { + const n = (Math.random() - 0.5) * spread; + d[i] = Math.max(0, Math.min(255, base[0] + n)); + d[i + 1] = Math.max(0, Math.min(255, base[1] + n)); + d[i + 2] = Math.max(0, Math.min(255, base[2] + n)); + d[i + 3] = 255; + } + g.putImageData(img, 0, 0); +} + +function paintConcrete(g, s) { + noiseFill(g, s, [140, 133, 118], 24); + g.globalAlpha = 0.42; + g.strokeStyle = "#5d5648"; + g.lineWidth = 2; + for (let y = 0; y <= s; y += 64) { + g.beginPath(); + g.moveTo(0, y); + g.lineTo(s, y); + g.stroke(); + } + for (let y = 0; y < s; y += 64) { + const off = (y / 64) % 2 ? 64 : 32; + for (let x = 0; x <= s; x += 128) { + g.beginPath(); + g.moveTo(x + off, y); + g.lineTo(x + off, y + 64); + g.stroke(); + } + } + g.globalAlpha = 0.1; + for (let i = 0; i < 14; i++) { + const x = Math.random() * s; + const y = Math.random() * s; + const r = 10 + Math.random() * 34; + const grd = g.createRadialGradient(x, y, 0, x, y, r); + grd.addColorStop(0, "#3b3427"); + grd.addColorStop(1, "rgba(59,52,39,0)"); + g.fillStyle = grd; + g.fillRect(0, 0, s, s); + } + g.globalAlpha = 1; +} + +function paintWood(g, s) { + noiseFill(g, s, [126, 92, 58], 16); + const plank = 42; + for (let y = 0; y < s; y += plank) { + g.globalAlpha = 0.34; + g.fillStyle = "#4d351f"; + g.fillRect(0, y, s, 2); + g.globalAlpha = 0.12; + g.fillStyle = "#e0b483"; + g.fillRect(0, y + 3, s, 2); + g.globalAlpha = 0.14; + g.strokeStyle = "#3a2513"; + g.lineWidth = 1; + for (let k = 0; k < 7; k++) { + const yy = y + 5 + Math.random() * (plank - 10); + g.beginPath(); + g.moveTo(0, yy); + for (let x = 0; x <= s; x += 24) { + g.lineTo(x, yy + Math.sin(x * 0.07 + k) * 1.6); + } + g.stroke(); + } + } + g.globalAlpha = 0.5; + g.fillStyle = "#2e2a24"; + for (let y = 12; y < s; y += plank) { + for (let x = 14; x < s; x += 96) { + g.beginPath(); + g.arc(x, y, 2, 0, Math.PI * 2); + g.fill(); + } + } + g.globalAlpha = 1; +} + +function paintMetal(g, s) { + noiseFill(g, s, [76, 86, 98], 12); + g.globalAlpha = 0.26; + g.strokeStyle = "#2a323b"; + g.lineWidth = 3; + for (let x = 0; x <= s; x += 85) { + g.beginPath(); + g.moveTo(x, 0); + g.lineTo(x, s); + g.stroke(); + } + g.globalAlpha = 0.5; + for (let y = 16; y < s; y += 42) { + for (let x = 16; x < s; x += 42) { + g.fillStyle = "#9fb0c0"; + g.beginPath(); + g.arc(x, y, 2.2, 0, Math.PI * 2); + g.fill(); + } + } + g.globalAlpha = 0.14; + for (let i = 0; i < 16; i++) { + g.fillStyle = "#7a4a26"; + g.fillRect(Math.random() * s, Math.random() * s, 2 + Math.random() * 4, 20 + Math.random() * 60); + } + g.globalAlpha = 1; +} + +function paintFloor(g, s) { + noiseFill(g, s, [106, 102, 92], 18); + g.globalAlpha = 0.42; + g.strokeStyle = "#57534a"; + g.lineWidth = 3; + for (let i = 0; i <= s; i += 64) { + g.beginPath(); + g.moveTo(i, 0); + g.lineTo(i, s); + g.stroke(); + g.beginPath(); + g.moveTo(0, i); + g.lineTo(s, i); + g.stroke(); + } + g.globalAlpha = 0.1; + for (let i = 0; i < 26; i++) { + g.fillStyle = "#c8c2b0"; + g.fillRect(Math.random() * s, Math.random() * s, 3 + Math.random() * 9, 1 + Math.random() * 3); + } + g.globalAlpha = 1; +} + +function radialShadow(g, s) { + const grd = g.createRadialGradient(s / 2, s / 2, 0, s / 2, s / 2, s / 2); + grd.addColorStop(0, "rgba(0,0,0,0.9)"); + grd.addColorStop(0.5, "rgba(0,0,0,0.55)"); + grd.addColorStop(1, "rgba(0,0,0,0)"); + g.fillStyle = grd; + g.fillRect(0, 0, s, s); +} + +/* --------------------------------- 着色器 --------------------------------- */ + +const WORLD_VS = ` +attribute vec3 aPos; +attribute vec3 aNormal; +attribute vec2 aUV; +uniform mat4 uProj, uView, uModel; +uniform mat3 uNormalMat; +varying vec3 vNormal; +varying vec2 vUV; +varying vec3 vWorld; +void main() { + vec4 wp = uModel * vec4(aPos, 1.0); + vWorld = wp.xyz; + vNormal = uNormalMat * aNormal; + vUV = aUV; + gl_Position = uProj * uView * wp; +}`; + +const WORLD_FS = ` +precision mediump float; +uniform sampler2D uTex; +uniform vec3 uTint; +uniform vec3 uLightDir; +uniform vec3 uLightColor; +uniform vec3 uFillDir; +uniform vec3 uFillColor; +uniform vec3 uAmbient; +uniform vec3 uFogColor; +uniform vec3 uCamPos; +uniform float uFogNear, uFogFar; +uniform float uEmissive; +varying vec3 vNormal; +varying vec2 vUV; +varying vec3 vWorld; +void main() { + vec3 base = texture2D(uTex, vUV).rgb * uTint; + vec3 n = normalize(vNormal); + float diff = max(dot(n, uLightDir), 0.0); + float fill = max(dot(n, uFillDir), 0.0); + float hemi = 0.55 + 0.45 * n.y; + vec3 light = uAmbient * hemi + uLightColor * diff + uFillColor * fill; + vec3 col = base * (light + uEmissive); + float f = smoothstep(uFogNear, uFogFar, length(vWorld - uCamPos)); + gl_FragColor = vec4(mix(col, uFogColor, f), 1.0); +}`; + +const SKY_VS = ` +attribute vec3 aPos; +uniform mat4 uProj, uView; +uniform vec3 uCam; +varying vec3 vDir; +void main() { + vDir = aPos; + gl_Position = uProj * uView * vec4(aPos * 400.0 + uCam, 1.0); +}`; + +const SKY_FS = ` +precision mediump float; +uniform vec3 uHorizon, uZenith, uSunColor, uSunDir; +varying vec3 vDir; +void main() { + vec3 d = normalize(vDir); + float h = clamp(d.y * 0.5 + 0.5, 0.0, 1.0); + vec3 col = mix(uHorizon, uZenith, smoothstep(0.42, 0.95, h)); + float sun = pow(max(dot(d, uSunDir), 0.0), 24.0); + col += uSunColor * sun * 0.5; + gl_FragColor = vec4(col, 1.0); +}`; + +const FLAT_VS = ` +attribute vec3 aPos; +attribute vec2 aUV; +uniform mat4 uProj, uView, uModel; +varying vec2 vUV; +void main() { + vUV = aUV; + gl_Position = uProj * uView * uModel * vec4(aPos, 1.0); +}`; + +const FLAT_FS = ` +precision mediump float; +uniform sampler2D uTex; +uniform vec3 uTint; +uniform float uAlpha; +varying vec2 vUV; +void main() { + float a = texture2D(uTex, vUV).a * uAlpha; + if (a < 0.004) discard; + gl_FragColor = vec4(uTint, a); +}`; + +const PARTICLE_VS = ` +attribute vec3 aPos; +attribute float aSize; +attribute vec4 aColor; +uniform mat4 uProj, uView; +uniform float uScale; +varying vec4 vColor; +void main() { + vec4 vp = uView * vec4(aPos, 1.0); + gl_Position = uProj * vp; + gl_PointSize = clamp(aSize * uScale / max(-vp.z, 0.15), 1.0, 80.0); + vColor = aColor; +}`; + +const PARTICLE_FS = ` +precision mediump float; +varying vec4 vColor; +void main() { + vec2 c = gl_PointCoord - 0.5; + float d = length(c); + if (d > 0.5) discard; + gl_FragColor = vec4(vColor.rgb, vColor.a * smoothstep(0.5, 0.06, d)); +}`; + +const LINE_VS = ` +attribute vec3 aPos; +uniform mat4 uProj, uView; +void main() { + gl_Position = uProj * uView * vec4(aPos, 1.0); +}`; + +const LINE_FS = ` +precision mediump float; +uniform vec3 uColor; +uniform float uAlpha; +void main() { + gl_FragColor = vec4(uColor, uAlpha); +}`; + +/* --------------------------------- 几何 --------------------------------- */ + +const FACES = [ + [0, 1], + [0, -1], + [1, 1], + [1, -1], + [2, 1], + [2, -1], +]; + +function buildCube() { + const pos = []; + const nor = []; + const uv = []; + const idx = []; + let n = 0; + for (const [axis, sign] of FACES) { + const u = (axis + 1) % 3; + const v = (axis + 2) % 3; + const corners = [ + [0, 0], + [1, 0], + [1, 1], + [0, 1], + ]; + for (const [cu, cv] of corners) { + const p = [0, 0, 0]; + p[axis] = sign > 0 ? 0.5 : -0.5; + p[u] = cu - 0.5; + p[v] = cv - 0.5; + pos.push(p[0], p[1], p[2]); + const nn = [0, 0, 0]; + nn[axis] = sign; + nor.push(nn[0], nn[1], nn[2]); + uv.push(cu, cv); + } + if (sign > 0) idx.push(n, n + 1, n + 2, n, n + 2, n + 3); + else idx.push(n, n + 2, n + 1, n, n + 3, n + 2); + n += 4; + } + return { + positions: new Float32Array(pos), + normals: new Float32Array(nor), + uvs: new Float32Array(uv), + indices: new Uint16Array(idx), + count: idx.length, + }; +} + +/* --------------------------------- 渲染器 --------------------------------- */ + +export class Renderer { + constructor(canvas) { + this.canvas = canvas; + const opts = { antialias: true, alpha: false, depth: true, powerPreference: "high-performance" }; + this.gl = canvas.getContext("webgl2", opts) || canvas.getContext("webgl", opts); + if (!this.gl) throw new Error("这台设备不支持 WebGL"); + const gl = this.gl; + + this.level = null; + this.matBuffers = []; + this.shadowQuads = []; + this.cube = buildCube(); + this.dpr = Math.min(window.devicePixelRatio || 1, 2); + + this.progWorld = this.program(WORLD_VS, WORLD_FS); + this.progSky = this.program(SKY_VS, SKY_FS); + this.progFlat = this.program(FLAT_VS, FLAT_FS); + this.progParticle = this.program(PARTICLE_VS, PARTICLE_FS); + this.progLine = this.program(LINE_VS, LINE_FS); + + this.world = this.locations(this.progWorld, [ + "aPos", "aNormal", "aUV", "uProj", "uView", "uModel", "uNormalMat", + "uTex", "uTint", "uLightDir", "uLightColor", "uFillDir", "uFillColor", "uAmbient", "uFogColor", + "uCamPos", "uFogNear", "uFogFar", "uEmissive", + ]); + this.sky = this.locations(this.progSky, ["aPos", "uProj", "uView", "uCam", "uHorizon", "uZenith", "uSunColor", "uSunDir"]); + this.flat = this.locations(this.progFlat, ["aPos", "aUV", "uProj", "uView", "uModel", "uTex", "uTint", "uAlpha"]); + this.particle = this.locations(this.progParticle, ["aPos", "aSize", "aColor", "uProj", "uView", "uScale"]); + this.line = this.locations(this.progLine, ["aPos", "uProj", "uView", "uColor", "uAlpha"]); + + this.textures = [ + this.canvasTexture(paintConcrete), + this.canvasTexture(paintWood), + this.canvasTexture(paintMetal), + this.canvasTexture(paintFloor), + ]; + this.white = this.solidTexture([255, 255, 255, 255]); + this.shadowTex = this.canvasTexture(radialShadow, 128); + + // 立方体(模型 / 阴影共用):顶点交错成 pos+normal+uv,跟地图格式一致 + const cn = this.cube.positions.length / 3; + const cdata = new Float32Array(cn * 8); + for (let i = 0; i < cn; i++) { + cdata[i * 8] = this.cube.positions[i * 3]; + cdata[i * 8 + 1] = this.cube.positions[i * 3 + 1]; + cdata[i * 8 + 2] = this.cube.positions[i * 3 + 2]; + cdata[i * 8 + 3] = this.cube.normals[i * 3]; + cdata[i * 8 + 4] = this.cube.normals[i * 3 + 1]; + cdata[i * 8 + 5] = this.cube.normals[i * 3 + 2]; + cdata[i * 8 + 6] = this.cube.uvs[i * 2]; + cdata[i * 8 + 7] = this.cube.uvs[i * 2 + 1]; + } + this.cubeVbo = this.buffer(cdata); + this.cubeIbo = this.elementBuffer(this.cube.indices); + this.cubeMesh = { vbo: this.cubeVbo, ibo: this.cubeIbo, count: this.cube.count }; + + this.skyVbo = this.buffer(this.cube.positions); + this.skyCount = this.cube.count; + + this.particleBuf = gl.createBuffer(); + this.lineBuf = gl.createBuffer(); + this.particleData = new Float32Array(4096 * 8); + this.lineData = new Float32Array(4096 * 3); + + this.lightDir = normalize3([-0.42, 0.72, 0.55]); + this.lightColor = [1.0, 0.88, 0.68]; + this.fillDir = normalize3([0.55, 0.22, -0.62]); + this.fillColor = [0.22, 0.27, 0.35]; + this.ambient = [0.3, 0.37, 0.47]; + this.fogColor = [0.115, 0.16, 0.215]; + this.sunDir = normalize3([-0.5, 0.34, 0.62]); + this.skyHorizon = [0.24, 0.29, 0.35]; + this.skyZenith = [0.05, 0.08, 0.13]; + this.sunColor = [1.0, 0.55, 0.25]; + + gl.enable(gl.DEPTH_TEST); + gl.depthFunc(gl.LEQUAL); + gl.enable(gl.CULL_FACE); + gl.cullFace(gl.BACK); + gl.clearColor(this.fogColor[0], this.fogColor[1], this.fogColor[2], 1); + this.resize(); + } + + /* ------------------------------ GL 小工具 ------------------------------ */ + + program(vs, fs) { + const gl = this.gl; + const compile = (type, src) => { + const s = gl.createShader(type); + gl.shaderSource(s, src); + gl.compileShader(s); + if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) { + throw new Error("shader: " + gl.getShaderInfoLog(s)); + } + return s; + }; + const p = gl.createProgram(); + gl.attachShader(p, compile(gl.VERTEX_SHADER, vs)); + gl.attachShader(p, compile(gl.FRAGMENT_SHADER, fs)); + gl.linkProgram(p); + if (!gl.getProgramParameter(p, gl.LINK_STATUS)) { + throw new Error("link: " + gl.getProgramInfoLog(p)); + } + return p; + } + + locations(prog, names) { + const out = {}; + for (const n of names) { + out[n] = n.startsWith("u") + ? this.gl.getUniformLocation(prog, n) + : this.gl.getAttribLocation(prog, n); + } + return out; + } + + buffer(data) { + const gl = this.gl; + const b = gl.createBuffer(); + gl.bindBuffer(gl.ARRAY_BUFFER, b); + gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW); + return b; + } + + elementBuffer(data) { + const gl = this.gl; + const b = gl.createBuffer(); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, b); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, data, gl.STATIC_DRAW); + return b; + } + + /** 只启用本次绘制用到的顶点属性,避免不同 program 的属性串味 */ + useAttribs(indices) { + const gl = this.gl; + for (let i = 0; i < 8; i++) { + if (indices.includes(i)) gl.enableVertexAttribArray(i); + else gl.disableVertexAttribArray(i); + } + } + + canvasTexture(paint, size = 256) { + const gl = this.gl; + const c = canvasTex(size); + const g = c.getContext("2d"); + paint(g, size); + const tex = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, tex); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, c); + gl.generateMipmap(gl.TEXTURE_2D); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + return tex; + } + + solidTexture(rgba) { + const gl = this.gl; + const tex = gl.createTexture(); + gl.bindTexture(gl.TEXTURE_2D, tex); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(rgba)); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + return tex; + } + + /* -------------------------------- 地图 -------------------------------- */ + + setLevel(level) { + const gl = this.gl; + this.level = level; + const meshes = [0, 1, 2, 3].map(() => ({ v: [], i: [], n: 0 })); + const tiles = [1.5, 1.7, 2.6, 2.1]; + + for (const b of level.boxes) { + const m = meshes[b.mat] || meshes[0]; + for (const [axis, sign] of FACES) { + const u = (axis + 1) % 3; + const v = (axis + 2) % 3; + const corners = [ + [0, 0], + [1, 0], + [1, 1], + [0, 1], + ]; + const base = m.n; + const nn = [0, 0, 0]; + nn[axis] = sign; + for (const [cu, cv] of corners) { + const p = [0, 0, 0]; + p[axis] = sign > 0 ? b.max[axis] : b.min[axis]; + p[u] = cu ? b.max[u] : b.min[u]; + p[v] = cv ? b.max[v] : b.min[v]; + const tile = tiles[b.mat] || TILE; + m.v.push(p[0], p[1], p[2], nn[0], nn[1], nn[2], p[u] / tile, p[v] / tile); + m.n++; + } + if (sign > 0) m.i.push(base, base + 1, base + 2, base, base + 2, base + 3); + else m.i.push(base, base + 2, base + 1, base, base + 3, base + 2); + } + } + + this.matBuffers = meshes.map((m) => { + if (!m.n) return null; + return { + vbo: this.buffer(new Float32Array(m.v)), + ibo: this.elementBuffer(new Uint16Array(m.i)), + count: m.i.length, + }; + }); + + this.shadowQuads = []; + for (const b of level.boxes) { + if (b.min[1] <= 0.05 && b.max[1] > 0.4 && b.mat !== 3) { + this.shadowQuads.push({ min: [b.min[0], b.min[2]], max: [b.max[0], b.max[2]] }); + } + } + } + + resize() { + const w = Math.max(1, Math.round(this.canvas.clientWidth * this.dpr)); + const h = Math.max(1, Math.round(this.canvas.clientHeight * this.dpr)); + if (this.canvas.width !== w || this.canvas.height !== h) { + this.canvas.width = w; + this.canvas.height = h; + } + this.gl.viewport(0, 0, w, h); + } + + /* -------------------------------- 渲染 -------------------------------- */ + + render(s) { + const gl = this.gl; + this.aspect = this.canvas.width / Math.max(1, this.canvas.height); + this.fov = s.fov || 78; + this.proj = perspective((this.fov * Math.PI) / 180, this.aspect, 0.045, 320); + this.view = mul(mul(rotX(-s.pitch), rotY(s.yaw)), translate(-s.pos[0], -s.pos[1], -s.pos[2])); + this.eye = s.pos; + + gl.clearColor(this.fogColor[0], this.fogColor[1], this.fogColor[2], 1); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); + + this.drawSky(s); + this.drawWorld(); + this.drawShadows(s); + this.drawPlayers(s); + this.drawParticles(s); + this.drawTracers(s); + } + + drawMesh(buf, tex, tint, model, normalMat, emissive = 0) { + const gl = this.gl; + const w = this.world; + gl.bindBuffer(gl.ARRAY_BUFFER, buf.vbo); + gl.vertexAttribPointer(w.aPos, 3, gl.FLOAT, false, 32, 0); + gl.vertexAttribPointer(w.aNormal, 3, gl.FLOAT, false, 32, 12); + gl.vertexAttribPointer(w.aUV, 2, gl.FLOAT, false, 32, 24); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buf.ibo); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, tex); + gl.uniform1i(w.uTex, 0); + gl.uniform3fv(w.uTint, tint); + gl.uniformMatrix4fv(w.uModel, false, model); + gl.uniformMatrix3fv(w.uNormalMat, false, normalMat); + gl.uniform1f(w.uEmissive, emissive); + gl.drawElements(gl.TRIANGLES, buf.count, gl.UNSIGNED_SHORT, 0); + } + + drawSky(s) { + const gl = this.gl; + const p = this.sky; + gl.useProgram(this.progSky); + this.useAttribs([p.aPos]); + gl.disable(gl.DEPTH_TEST); + gl.depthMask(false); + gl.disable(gl.CULL_FACE); + gl.bindBuffer(gl.ARRAY_BUFFER, this.skyVbo); + gl.vertexAttribPointer(p.aPos, 3, gl.FLOAT, false, 0, 0); + gl.uniformMatrix4fv(p.uProj, false, this.proj); + gl.uniformMatrix4fv(p.uView, false, this.view); + gl.uniform3fv(p.uCam, s.pos); + gl.uniform3fv(p.uHorizon, this.skyHorizon); + gl.uniform3fv(p.uZenith, this.skyZenith); + gl.uniform3fv(p.uSunColor, this.sunColor); + gl.uniform3fv(p.uSunDir, this.sunDir); + gl.drawArrays(gl.TRIANGLES, 0, this.skyCount); + gl.enable(gl.DEPTH_TEST); + gl.depthMask(true); + gl.enable(gl.CULL_FACE); + } + + beginWorld() { + const gl = this.gl; + const w = this.world; + gl.useProgram(this.progWorld); + this.useAttribs([w.aPos, w.aNormal, w.aUV]); + gl.uniformMatrix4fv(w.uProj, false, this.proj); + gl.uniformMatrix4fv(w.uView, false, this.view); + gl.uniform3fv(w.uLightDir, this.lightDir); + gl.uniform3fv(w.uLightColor, this.lightColor); + gl.uniform3fv(w.uFillDir, this.fillDir); + gl.uniform3fv(w.uFillColor, this.fillColor); + gl.uniform3fv(w.uAmbient, this.ambient); + gl.uniform3fv(w.uFogColor, this.fogColor); + gl.uniform3fv(w.uCamPos, this.eye); + gl.uniform1f(w.uFogNear, 26); + gl.uniform1f(w.uFogFar, 95); + gl.uniform1f(w.uEmissive, 0); + } + + drawWorld() { + const gl = this.gl; + this.beginWorld(); + const I = mat4(); + const tints = [ + [1, 1, 1], + [1, 0.96, 0.9], + [0.94, 0.98, 1], + [1, 0.99, 0.96], + ]; + for (let i = 0; i < this.matBuffers.length; i++) { + const buf = this.matBuffers[i]; + if (!buf) continue; + this.drawMesh(buf, this.textures[i], tints[i], I, mat3Identity(), 0); + } + void gl; + } + + drawShadows(s) { + const gl = this.gl; + const f = this.flat; + gl.useProgram(this.progFlat); + this.useAttribs([f.aPos]); + // UV 用一个常量,贴图是径向渐变 + gl.disableVertexAttribArray(f.aUV); + gl.vertexAttrib2f(f.aUV, 0.5, 0.5); + gl.enable(gl.BLEND); + gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); + gl.depthMask(false); + gl.disable(gl.CULL_FACE); + gl.bindBuffer(gl.ARRAY_BUFFER, this.cubeVbo); + gl.vertexAttribPointer(f.aPos, 3, gl.FLOAT, false, 32, 0); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.cubeIbo); + gl.uniformMatrix4fv(f.uProj, false, this.proj); + gl.uniformMatrix4fv(f.uView, false, this.view); + gl.uniform1i(f.uTex, 0); + gl.activeTexture(gl.TEXTURE0); + gl.bindTexture(gl.TEXTURE_2D, this.shadowTex); + gl.uniform3f(f.uTint, 0, 0, 0); + + const quad = (cx, cz, sx, sz, alpha) => { + gl.uniform1f(f.uAlpha, alpha); + const m = mul(translate(cx, 0.022, cz), mul(rotX(-Math.PI / 2), scale(sx, sz, 0.002))); + gl.uniformMatrix4fv(f.uModel, false, m); + gl.drawElements(gl.TRIANGLES, this.cube.count, gl.UNSIGNED_SHORT, 0); + }; + + for (const q of this.shadowQuads) { + quad((q.min[0] + q.max[0]) / 2, (q.min[1] + q.max[1]) / 2, q.max[0] - q.min[0] + 0.6, q.max[1] - q.min[1] + 0.6, 0.3); + } + for (const p of s.players) { + if (!p.alive) continue; + quad(p.pos[0], p.pos[2], 1.15, 1.15, 0.42); + } + + gl.depthMask(true); + gl.disable(gl.BLEND); + gl.enable(gl.CULL_FACE); + } + + drawPlayers(s) { + this.beginWorld(); + const box = this.cubeMesh; + for (const p of s.players) { + if (!p.alive) continue; + if (p.slot === s.selfSlot && !s.spectating) continue; + const base = mul(translate(p.pos[0], p.pos[1], p.pos[2]), rotY(-p.yaw)); + const nm = yawNormalMat(p.yaw); + const leg = [0.2, 0.22, 0.26]; + const team = p.bot ? [0.8, 0.4, 0.2] : [0.86, 0.33, 0.16]; + const head = [0.76, 0.64, 0.53]; + const part = (local, size, color, emissive) => { + const m = mul(base, mul(translate(local[0], local[1], local[2]), scale(size[0], size[1], size[2]))); + this.drawMesh(box, this.white, color, m, nm, emissive); + }; + part([-0.16, 0.42, 0], [0.22, 0.84, 0.3], leg, 0.04); + part([0.16, 0.42, 0], [0.22, 0.84, 0.3], leg, 0.04); + part([0, 1.14, 0], [0.6, 0.62, 0.36], team, 0.12); + part([0, 1.63, -0.02], [0.32, 0.3, 0.32], head, 0.08); + part([0.14, 1.16, -0.4], [0.1, 0.13, 0.62], [0.13, 0.14, 0.16], 0.04); + // 头顶一个小小的队伍色标记,远距离更好认 + part([0, 1.84, 0], [0.13, 0.045, 0.13], team, 0.9); + } + } + + drawParticles(s) { + const gl = this.gl; + const list = s.particles; + if (!list || !list.length) return; + const p = this.particle; + let n = 0; + const arr = this.particleData; + for (const q of list) { + if (n >= 4096) break; + const o = n * 8; + arr[o] = q.pos[0]; + arr[o + 1] = q.pos[1]; + arr[o + 2] = q.pos[2]; + arr[o + 3] = q.size; + arr[o + 4] = q.color[0]; + arr[o + 5] = q.color[1]; + arr[o + 6] = q.color[2]; + arr[o + 7] = q.alpha; + n++; + } + gl.useProgram(this.progParticle); + this.useAttribs([p.aPos, p.aSize, p.aColor]); + gl.bindBuffer(gl.ARRAY_BUFFER, this.particleBuf); + gl.bufferData(gl.ARRAY_BUFFER, arr.subarray(0, n * 8), gl.DYNAMIC_DRAW); + gl.vertexAttribPointer(p.aPos, 3, gl.FLOAT, false, 32, 0); + gl.vertexAttribPointer(p.aSize, 1, gl.FLOAT, false, 32, 12); + gl.vertexAttribPointer(p.aColor, 4, gl.FLOAT, false, 32, 16); + gl.uniformMatrix4fv(p.uProj, false, this.proj); + gl.uniformMatrix4fv(p.uView, false, this.view); + gl.uniform1f(p.uScale, this.canvas.height / (2 * Math.tan((this.fov * Math.PI) / 360))); + gl.enable(gl.BLEND); + gl.blendFunc(gl.SRC_ALPHA, gl.ONE); + gl.depthMask(false); + gl.drawArrays(gl.POINTS, 0, n); + gl.depthMask(true); + gl.disable(gl.BLEND); + } + + drawTracers(s) { + const gl = this.gl; + const list = s.tracers; + if (!list || !list.length) return; + const p = this.line; + let n = 0; + for (const t of list) { + if (n + 2 > 4096) break; + this.lineData[n * 3] = t.from[0]; + this.lineData[n * 3 + 1] = t.from[1]; + this.lineData[n * 3 + 2] = t.from[2]; + n++; + this.lineData[n * 3] = t.to[0]; + this.lineData[n * 3 + 1] = t.to[1]; + this.lineData[n * 3 + 2] = t.to[2]; + n++; + } + gl.useProgram(this.progLine); + this.useAttribs([p.aPos]); + gl.bindBuffer(gl.ARRAY_BUFFER, this.lineBuf); + gl.bufferData(gl.ARRAY_BUFFER, this.lineData.subarray(0, n * 3), gl.DYNAMIC_DRAW); + gl.vertexAttribPointer(p.aPos, 3, gl.FLOAT, false, 0, 0); + gl.uniformMatrix4fv(p.uProj, false, this.proj); + gl.uniformMatrix4fv(p.uView, false, this.view); + gl.uniform3f(p.uColor, 1.0, 0.8, 0.4); + gl.uniform1f(p.uAlpha, 0.75); + gl.enable(gl.BLEND); + gl.blendFunc(gl.SRC_ALPHA, gl.ONE); + gl.depthMask(false); + gl.drawArrays(gl.LINES, 0, n); + gl.depthMask(true); + gl.disable(gl.BLEND); + } + +} + +function normalize3(v) { + const l = Math.hypot(v[0], v[1], v[2]) || 1; + return [v[0] / l, v[1] / l, v[2] / l]; +} diff --git a/public/js/client/sound.js b/public/js/client/sound.js new file mode 100644 index 0000000..2bcfc10 --- /dev/null +++ b/public/js/client/sound.js @@ -0,0 +1,205 @@ +// 全部音效都是 WebAudio 现场合成,不带任何音频文件。 + +export class Sound { + constructor() { + this.ctx = null; + this.master = null; + this.noise = null; + this.volume = 0.6; + this.enabled = true; + } + + ensure() { + if (!this.enabled) return false; + if (!this.ctx) { + const AC = window.AudioContext || window.webkitAudioContext; + if (!AC) { + this.enabled = false; + return false; + } + this.ctx = new AC(); + this.master = this.ctx.createGain(); + this.master.gain.value = this.volume; + this.master.connect(this.ctx.destination); + // 1 秒白噪声,枪声/脚步都从它切 + const len = Math.floor(this.ctx.sampleRate * 1.0); + const buf = this.ctx.createBuffer(1, len, this.ctx.sampleRate); + const d = buf.getChannelData(0); + for (let i = 0; i < len; i++) d[i] = Math.random() * 2 - 1; + this.noise = buf; + } + if (this.ctx.state === "suspended") { + const now = performance.now(); + if (!this._resumeAt || now - this._resumeAt > 2000) { + this._resumeAt = now; + this.ctx.resume().catch(() => {}); + } + } + return true; + } + + setVolume(v) { + this.volume = v; + if (this.master) this.master.gain.value = v; + } + + chain(pan) { + const ctx = this.ctx; + const out = ctx.createGain(); + if (ctx.createStereoPanner) { + const p = ctx.createStereoPanner(); + p.pan.value = Math.max(-1, Math.min(1, pan || 0)); + out.connect(p); + p.connect(this.master); + } else { + out.connect(this.master); + } + return out; + } + + /** 枪声:噪声爆 + 低频冲击。pan 用于判断敌人从哪边开枪 */ + shot(weaponId, pan = 0, dist = 0, own = true) { + if (!this.ensure()) return; + const ctx = this.ctx; + const t = ctx.currentTime; + const far = Math.min(1, dist / 45); + const gain = (own ? 0.85 : 0.9) * (1 - far * 0.75); + const dur = weaponId === 1 ? 0.16 : 0.26; + const out = this.chain(pan); + + const src = ctx.createBufferSource(); + src.buffer = this.noise; + src.playbackRate.value = 0.9 + Math.random() * 0.2; + const lp = ctx.createBiquadFilter(); + lp.type = "lowpass"; + lp.frequency.setValueAtTime(4200 - far * 2600, t); + lp.frequency.exponentialRampToValueAtTime(380, t + dur * 0.8); + const g = ctx.createGain(); + g.gain.setValueAtTime(gain, t); + g.gain.exponentialRampToValueAtTime(0.0008, t + dur); + src.connect(lp); + lp.connect(g); + g.connect(out); + src.start(t); + src.stop(t + dur + 0.02); + + const osc = ctx.createOscillator(); + osc.type = "sine"; + osc.frequency.setValueAtTime(weaponId === 1 ? 150 : 120, t); + osc.frequency.exponentialRampToValueAtTime(42, t + 0.12); + const og = ctx.createGain(); + og.gain.setValueAtTime(gain * 0.7, t); + og.gain.exponentialRampToValueAtTime(0.001, t + 0.13); + osc.connect(og); + og.connect(out); + osc.start(t); + osc.stop(t + 0.14); + } + + blip(freq, dur = 0.06, type = "square", gain = 0.14) { + if (!this.ensure()) return; + const ctx = this.ctx; + const t = ctx.currentTime; + const o = ctx.createOscillator(); + o.type = type; + o.frequency.setValueAtTime(freq, t); + const g = ctx.createGain(); + g.gain.setValueAtTime(gain, t); + g.gain.exponentialRampToValueAtTime(0.0006, t + dur); + o.connect(g); + g.connect(this.master); + o.start(t); + o.stop(t + dur + 0.01); + } + + hit(head) { + this.blip(head ? 1600 : 1150, head ? 0.1 : 0.05, "square", head ? 0.16 : 0.1); + if (head) setTimeout(() => this.blip(2100, 0.09, "sine", 0.14), 45); + } + + kill() { + this.blip(760, 0.09, "sawtooth", 0.14); + setTimeout(() => this.blip(520, 0.14, "sawtooth", 0.12), 70); + } + + hurt() { + if (!this.ensure()) return; + const ctx = this.ctx; + const t = ctx.currentTime; + const src = ctx.createBufferSource(); + src.buffer = this.noise; + src.playbackRate.value = 0.6; + const lp = ctx.createBiquadFilter(); + lp.type = "lowpass"; + lp.frequency.value = 900; + const g = ctx.createGain(); + g.gain.setValueAtTime(0.35, t); + g.gain.exponentialRampToValueAtTime(0.001, t + 0.18); + src.connect(lp); + lp.connect(g); + g.connect(this.master); + src.start(t); + src.stop(t + 0.2); + } + + reload(stage) { + this.blip(stage === 0 ? 520 : 380, 0.045, "square", 0.09); + } + + empty() { + this.blip(260, 0.04, "square", 0.1); + } + + step() { + if (!this.ensure()) return; + const ctx = this.ctx; + const t = ctx.currentTime; + const src = ctx.createBufferSource(); + src.buffer = this.noise; + src.playbackRate.value = 0.35 + Math.random() * 0.2; + const bp = ctx.createBiquadFilter(); + bp.type = "bandpass"; + bp.frequency.value = 260 + Math.random() * 120; + bp.Q.value = 0.9; + const g = ctx.createGain(); + g.gain.setValueAtTime(0.16, t); + g.gain.exponentialRampToValueAtTime(0.0008, t + 0.1); + src.connect(bp); + bp.connect(g); + g.connect(this.master); + src.start(t); + src.stop(t + 0.12); + } + + roundStart() { + this.blip(880, 0.09, "sine", 0.13); + setTimeout(() => this.blip(1320, 0.12, "sine", 0.13), 130); + } + + roundEnd(win) { + if (win) { + this.blip(660, 0.1, "sine", 0.14); + setTimeout(() => this.blip(990, 0.16, "sine", 0.14), 110); + } else { + this.blip(300, 0.16, "sine", 0.12); + setTimeout(() => this.blip(200, 0.22, "sine", 0.12), 120); + } + } + + death() { + if (!this.ensure()) return; + const ctx = this.ctx; + const t = ctx.currentTime; + const o = ctx.createOscillator(); + o.type = "sine"; + o.frequency.setValueAtTime(180, t); + o.frequency.exponentialRampToValueAtTime(50, t + 0.6); + const g = ctx.createGain(); + g.gain.setValueAtTime(0.28, t); + g.gain.exponentialRampToValueAtTime(0.001, t + 0.65); + o.connect(g); + g.connect(this.master); + o.start(t); + o.stop(t + 0.7); + } +} diff --git a/public/js/client/viewmodel.js b/public/js/client/viewmodel.js new file mode 100644 index 0000000..eb2a980 --- /dev/null +++ b/public/js/client/viewmodel.js @@ -0,0 +1,265 @@ +// 第一人称枪模:用 2D Canvas 矢量绘制,比一堆方块更可控也更好看。 +// 只负责表现(后坐力回弹、走位摆动、枪口火光),命中判定全在服务端。 + +const SKIN = "#c99a72"; +const SKIN_DARK = "#a87b55"; + +export class ViewModel { + constructor(canvas) { + this.canvas = canvas; + this.g = canvas.getContext("2d"); + this.dpr = Math.min(window.devicePixelRatio || 1, 2); + this.resize(); + this.last = 0; + } + + resize() { + const w = Math.max(1, Math.round(window.innerWidth * this.dpr)); + const h = Math.max(1, Math.round(window.innerHeight * this.dpr)); + if (this.canvas.width !== w || this.canvas.height !== h) { + this.canvas.width = w; + this.canvas.height = h; + } + } + + clear() { + this.g.setTransform(1, 0, 0, 1, 0, 0); + this.g.clearRect(0, 0, this.canvas.width, this.canvas.height); + } + + /** s = {weapon: 0|1, bobX, bobY, kick, muzzle, swayX, alive} */ + render(s) { + this.resize(); + const g = this.g; + this.clear(); + if (!s || s.alive === false) return; + + const W = this.canvas.width; + const H = this.canvas.height; + const scale = (H / 720) * 1.04; + // 锚点:枪口大致在画面偏中下,枪身向右下角延伸 + const ax = W * 0.53; + const ay = H * 0.585; + const kick = s.kick || 0; + + g.save(); + g.translate(ax + (s.bobX || 0) * 700 + (s.swayX || 0) * 400 + kick * 26, ay + (s.bobY || 0) * 700 + kick * 10); + g.rotate(0.115 + kick * 0.02); + g.scale(scale, scale); + g.lineJoin = "round"; + + // 枪身投影 + g.save(); + g.globalAlpha = 0.28; + g.filter = "blur(10px)"; + g.fillStyle = "#000"; + g.fillRect(20, 110, 560, 180); + g.restore(); + + if (s.weapon === 1) this.drawPistol(g); + else this.drawRifle(g); + + // 枪口火光 + if (s.muzzle > 0) this.drawFlash(g, s.weapon === 1 ? [16, 96] : [14, 96], Math.min(1, s.muzzle * 16)); + + g.restore(); + } + + /* ------------------------------- 步枪 AK ------------------------------- */ + + drawRifle(g) { + // 枪管 + this.box(g, 26, 88, 236, 20, "#2b3037", "#3b4249"); + // 消焰器 + this.box(g, 2, 78, 42, 40, "#22262c", "#33383f"); + // 导气管 + this.box(g, 176, 58, 122, 14, "#343b43", "#454d56"); + // 下护木 + this.wood(g, 146, 70, 116, 66); + // 上护木 + this.wood(g, 150, 52, 108, 26); + // 准星 + this.box(g, 122, 28, 24, 46, "#2b3037", "#3b4249"); + // 机匣 + this.box(g, 248, 62, 194, 88, "#3d444d", "#4d5560"); + // 上机匣盖 + this.box(g, 250, 54, 186, 30, "#4a525c", "#5a626d"); + // 照门 + this.box(g, 388, 30, 44, 26, "#2b3037", "#3b4249"); + // 枪托 + this.poly( + g, + [ + [430, 76], + [566, 100], + [604, 178], + [430, 148], + ], + "#33383e", + "#41474f" + ); + // 握把 + this.poly( + g, + [ + [418, 146], + [470, 146], + [488, 258], + [442, 266], + ], + "#2f2a26", + "#3a342e" + ); + // 弹匣(两段拼出弧度) + this.poly( + g, + [ + [302, 146], + [366, 146], + [374, 214], + [310, 222], + ], + "#4a3524", + "#5a412c" + ); + this.poly( + g, + [ + [310, 218], + [374, 210], + [392, 286], + [330, 296], + ], + "#402d1e", + "#4e3826" + ); + // 手 + this.hand(g, 236, 128, -0.5); + this.hand(g, 452, 196, 0.25); + } + + /* ------------------------------- 手枪 ------------------------------- */ + + drawPistol(g) { + this.box(g, 40, 62, 250, 36, "#8f99a3", "#aab4bf"); + this.box(g, 18, 72, 26, 18, "#cfd8e0", "#e6edf3"); + this.box(g, 34, 96, 210, 16, "#7c858f", "#9aa3ad"); + this.poly( + g, + [ + [230, 92], + [290, 92], + [308, 224], + [252, 236], + ], + "#2f3339", + "#3c4147" + ); + this.hand(g, 300, 150, 0.15); + } + + /* ------------------------------- 绘制件 ------------------------------- */ + + box(g, x, y, w, h, fill, edge) { + g.fillStyle = fill; + g.fillRect(x, y, w, h); + if (edge) { + g.fillStyle = edge; + g.globalAlpha = 0.55; + g.fillRect(x, y, w, Math.max(2, h * 0.16)); + g.globalAlpha = 1; + } + g.strokeStyle = "rgba(0,0,0,0.35)"; + g.lineWidth = 2; + g.strokeRect(x + 1, y + 1, w - 2, h - 2); + } + + wood(g, x, y, w, h) { + const grd = g.createLinearGradient(x, y, x, y + h); + grd.addColorStop(0, "#b57f45"); + grd.addColorStop(0.55, "#9c6c39"); + grd.addColorStop(1, "#7b5229"); + g.fillStyle = grd; + g.fillRect(x, y, w, h); + g.strokeStyle = "rgba(60,32,10,0.35)"; + g.lineWidth = 1.5; + for (let i = 1; i < 4; i++) { + g.beginPath(); + g.moveTo(x + 4, y + (h / 4) * i); + g.bezierCurveTo(x + w * 0.35, y + (h / 4) * i - 3, x + w * 0.65, y + (h / 4) * i + 3, x + w - 4, y + (h / 4) * i); + g.stroke(); + } + g.strokeStyle = "rgba(0,0,0,0.4)"; + g.lineWidth = 2; + g.strokeRect(x + 1, y + 1, w - 2, h - 2); + } + + poly(g, pts, fill, edge) { + const grd = g.createLinearGradient(pts[0][0], pts[0][1], pts[0][0], pts[pts.length - 1][1] + 60); + grd.addColorStop(0, edge || fill); + grd.addColorStop(1, fill); + g.fillStyle = grd; + g.beginPath(); + pts.forEach(([x, y], i) => (i ? g.lineTo(x, y) : g.moveTo(x, y))); + g.closePath(); + g.fill(); + g.strokeStyle = "rgba(0,0,0,0.38)"; + g.lineWidth = 2; + g.stroke(); + } + + hand(g, x, y, rot) { + g.save(); + g.translate(x, y); + g.rotate(rot); + const grd = g.createLinearGradient(0, -30, 0, 40); + grd.addColorStop(0, SKIN); + grd.addColorStop(1, SKIN_DARK); + g.fillStyle = grd; + g.beginPath(); + g.moveTo(-34, -26); + g.quadraticCurveTo(6, -38, 30, -10); + g.quadraticCurveTo(44, 14, 20, 32); + g.quadraticCurveTo(-14, 42, -34, 16); + g.quadraticCurveTo(-44, -6, -34, -26); + g.fill(); + g.strokeStyle = "rgba(70,40,20,0.55)"; + g.lineWidth = 2; + g.stroke(); + // 指缝 + g.strokeStyle = "rgba(90,55,30,0.45)"; + g.lineWidth = 2; + for (let i = 0; i < 3; i++) { + g.beginPath(); + g.moveTo(-26 + i * 15, -14); + g.quadraticCurveTo(-18 + i * 15, 4, -24 + i * 15, 20); + g.stroke(); + } + g.restore(); + } + + drawFlash(g, at, a) { + g.save(); + g.translate(at[0], at[1]); + g.globalCompositeOperation = "lighter"; + const r = 90 * (0.6 + a * 0.7); + const grd = g.createRadialGradient(0, 0, 0, 0, 0, r); + grd.addColorStop(0, `rgba(255,246,214,${0.95 * a})`); + grd.addColorStop(0.35, `rgba(255,190,90,${0.7 * a})`); + grd.addColorStop(1, "rgba(255,120,20,0)"); + g.fillStyle = grd; + g.beginPath(); + g.arc(0, 0, r, 0, Math.PI * 2); + g.fill(); + // 十字星芒 + g.strokeStyle = `rgba(255,225,160,${0.85 * a})`; + g.lineWidth = 5; + g.beginPath(); + g.moveTo(-r * 0.9, 0); + g.lineTo(r * 0.6, 0); + g.moveTo(0, -r * 0.55); + g.lineTo(0, r * 0.55); + g.stroke(); + g.restore(); + } +} diff --git a/public/js/client/weapons.js b/public/js/client/weapons.js new file mode 100644 index 0000000..20f48a7 --- /dev/null +++ b/public/js/client/weapons.js @@ -0,0 +1,34 @@ +// 武器表 —— src/weapons.rs 的镜像,只用于本地表现(枪模型、音效、后坐力)。 +// 伤害、射速、弹匣、换弹时间都以服务端为准。 + +export const RIFLE = 0; +export const PISTOL = 1; + +export const WEAPONS = [ + { + id: RIFLE, + name: "AK-47", + auto: true, + interval: 0.1, + mag: 30, + reserve: 90, + reload: 2.4, + spread: 0.0075, + kick: 0.014, + }, + { + id: PISTOL, + name: "沙漠之鹰", + auto: false, + interval: 0.32, + mag: 7, + reserve: 35, + reload: 2.1, + spread: 0.0045, + kick: 0.028, + }, +]; + +export function weaponOf(id) { + return WEAPONS[id] || WEAPONS[0]; +} diff --git a/public/level.json b/public/level.json new file mode 100644 index 0000000..d307148 --- /dev/null +++ b/public/level.json @@ -0,0 +1 @@ +{"name":"沙漠据点","size":48,"spawns":[{"pos":[-18.5,0.0,-18.5],"yaw":135.0},{"pos":[18.5,0.0,18.5],"yaw":-45.0}],"boxes":[{"min":[-24,-0.6,-24],"max":[24,0.0,24],"mat":3},{"min":[-24,0.0,-24],"max":[-23,5.2,24],"mat":0},{"min":[23,0.0,-24],"max":[24,5.2,24],"mat":0},{"min":[-24,0.0,-24],"max":[24,5.2,-23],"mat":0},{"min":[-24,0.0,23],"max":[24,5.2,24],"mat":0},{"min":[-4.2,0.0,-4.2],"max":[4.2,2.0,4.2],"mat":0},{"min":[-1.4,2.0,-1.4],"max":[1.4,3.2,1.4],"mat":1},{"min":[-4.2,0.0,-6.3],"max":[4.2,0.65,-5.2],"mat":1},{"min":[-4.2,0.0,5.2],"max":[4.2,0.65,6.3],"mat":1},{"min":[-4.2,0.0,-5.2],"max":[4.2,1.3,-4.2],"mat":1},{"min":[-4.2,0.0,4.2],"max":[4.2,1.3,5.2],"mat":1},{"min":[-22.2,0.0,-21.6],"max":[-21.2,3.0,-15.4],"mat":0},{"min":[21.2,0.0,-21.6],"max":[22.2,3.0,-15.4],"mat":0},{"min":[-22.2,0.0,15.4],"max":[-21.2,3.0,21.6],"mat":0},{"min":[21.2,0.0,15.4],"max":[22.2,3.0,21.6],"mat":0},{"min":[-17.4,0.0,-21.8],"max":[-15.2,1.1,-19.6],"mat":1},{"min":[15.2,0.0,-21.8],"max":[17.4,1.1,-19.6],"mat":1},{"min":[-17.4,0.0,19.6],"max":[-15.2,1.1,21.8],"mat":1},{"min":[15.2,0.0,19.6],"max":[17.4,1.1,21.8],"mat":1},{"min":[-21.4,0.0,-13.4],"max":[-18.6,2.4,-10.6],"mat":2},{"min":[18.6,0.0,-13.4],"max":[21.4,2.4,-10.6],"mat":2},{"min":[-21.4,0.0,10.6],"max":[-18.6,2.4,13.4],"mat":2},{"min":[18.6,0.0,10.6],"max":[21.4,2.4,13.4],"mat":2},{"min":[-13.2,0.0,-21.8],"max":[-10.4,0.9,-20.0],"mat":0},{"min":[10.4,0.0,-21.8],"max":[13.2,0.9,-20.0],"mat":0},{"min":[-13.2,0.0,20.0],"max":[-10.4,0.9,21.8],"mat":0},{"min":[10.4,0.0,20.0],"max":[13.2,0.9,21.8],"mat":0},{"min":[-14.2,0.0,-14.4],"max":[-13.2,3.6,-8.0],"mat":0},{"min":[13.2,0.0,-14.4],"max":[14.2,3.6,-8.0],"mat":0},{"min":[-14.2,0.0,8.0],"max":[-13.2,3.6,14.4],"mat":0},{"min":[13.2,0.0,8.0],"max":[14.2,3.6,14.4],"mat":0},{"min":[-13.2,0.0,-14.4],"max":[-8.0,3.6,-13.4],"mat":0},{"min":[8.0,0.0,-14.4],"max":[13.2,3.6,-13.4],"mat":0},{"min":[-13.2,0.0,13.4],"max":[-8.0,3.6,14.4],"mat":0},{"min":[8.0,0.0,13.4],"max":[13.2,3.6,14.4],"mat":0},{"min":[-11.8,0.0,-13.4],"max":[-8.0,3.6,-12.6],"mat":0},{"min":[8.0,0.0,-13.4],"max":[11.8,3.6,-12.6],"mat":0},{"min":[-11.8,0.0,12.6],"max":[-8.0,3.6,13.4],"mat":0},{"min":[8.0,0.0,12.6],"max":[11.8,3.6,13.4],"mat":0},{"min":[-12.4,0.0,-11.6],"max":[-10.4,1.4,-9.6],"mat":1},{"min":[10.4,0.0,-11.6],"max":[12.4,1.4,-9.6],"mat":1},{"min":[-12.4,0.0,9.6],"max":[-10.4,1.4,11.6],"mat":1},{"min":[10.4,0.0,9.6],"max":[12.4,1.4,11.6],"mat":1},{"min":[-8.0,2.6,-13.4],"max":[-7.2,3.0,-12.6],"mat":1},{"min":[7.2,2.6,-13.4],"max":[8.0,3.0,-12.6],"mat":1},{"min":[-8.0,2.6,12.6],"max":[-7.2,3.0,13.4],"mat":1},{"min":[7.2,2.6,12.6],"max":[8.0,3.0,13.4],"mat":1},{"min":[-8.2,0.0,-10.2],"max":[-2.4,1.1,-9.2],"mat":1},{"min":[2.4,0.0,-10.2],"max":[8.2,1.1,-9.2],"mat":1},{"min":[-8.2,0.0,9.2],"max":[-2.4,1.1,10.2],"mat":1},{"min":[2.4,0.0,9.2],"max":[8.2,1.1,10.2],"mat":1},{"min":[-6.6,0.0,-5.4],"max":[-5.6,5.0,-4.4],"mat":2},{"min":[5.6,0.0,-5.4],"max":[6.6,5.0,-4.4],"mat":2},{"min":[-6.6,0.0,4.4],"max":[-5.6,5.0,5.4],"mat":2},{"min":[5.6,0.0,4.4],"max":[6.6,5.0,5.4],"mat":2},{"min":[-12.6,0.0,-4.6],"max":[-11.0,2.0,-3.0],"mat":1},{"min":[11.0,0.0,-4.6],"max":[12.6,2.0,-3.0],"mat":1},{"min":[-12.6,0.0,3.0],"max":[-11.0,2.0,4.6],"mat":1},{"min":[11.0,0.0,3.0],"max":[12.6,2.0,4.6],"mat":1},{"min":[-6.4,0.0,-6.4],"max":[-2.6,0.9,-5.5],"mat":0},{"min":[2.6,0.0,-6.4],"max":[6.4,0.9,-5.5],"mat":0},{"min":[-6.4,0.0,5.5],"max":[-2.6,0.9,6.4],"mat":0},{"min":[2.6,0.0,5.5],"max":[6.4,0.9,6.4],"mat":0},{"min":[-9.8,0.0,-1.9],"max":[-8.2,1.5,-0.4],"mat":1},{"min":[8.2,0.0,-1.9],"max":[9.8,1.5,-0.4],"mat":1},{"min":[-9.8,0.0,0.4],"max":[-8.2,1.5,1.9],"mat":1},{"min":[8.2,0.0,0.4],"max":[9.8,1.5,1.9],"mat":1},{"min":[-23.0,0.0,-23.0],"max":[-8.4,1.0,-21.2],"mat":2},{"min":[8.4,0.0,-23.0],"max":[23.0,1.0,-21.2],"mat":2},{"min":[-23.0,0.0,21.2],"max":[-8.4,1.0,23.0],"mat":2},{"min":[8.4,0.0,21.2],"max":[23.0,1.0,23.0],"mat":2},{"min":[-11.0,0.0,-21.2],"max":[-9.6,0.5,-20.2],"mat":2},{"min":[9.6,0.0,-21.2],"max":[11.0,0.5,-20.2],"mat":2},{"min":[-11.0,0.0,20.2],"max":[-9.6,0.5,21.2],"mat":2},{"min":[9.6,0.0,20.2],"max":[11.0,0.5,21.2],"mat":2}]} diff --git a/public/style.css b/public/style.css new file mode 100644 index 0000000..b2e3063 --- /dev/null +++ b/public/style.css @@ -0,0 +1,1317 @@ +/* ========================================================================== + CS · 枪火对决 —— 深色科技风 UI + ========================================================================== */ + +:root { + --bg: #060a10; + --bg2: #0a1119; + --panel: rgba(10, 17, 25, 0.92); + --panel-solid: #0b131c; + --line: rgba(96, 141, 176, 0.2); + --line-bright: rgba(86, 202, 237, 0.45); + --txt: #e2ecf6; + --dim: #7b91a6; + --dim2: #4f6579; + --cyan: #38e1ff; + --cyan-deep: #1497ba; + --orange: #ff8a3d; + --red: #ff4a5c; + --green: #46e08a; + --mono: ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace; + --sans: -apple-system, BlinkMacSystemFont, "PingFang SC", "Segoe UI", "Microsoft YaHei", sans-serif; +} + +* { + box-sizing: border-box; +} + +html, +body { + margin: 0; + height: 100%; + background: var(--bg); + color: var(--txt); + font-family: var(--sans); + overflow: hidden; + -webkit-font-smoothing: antialiased; +} + +body { + user-select: none; +} + +#gl { + position: fixed; + inset: 0; + width: 100%; + height: 100%; + display: block; + background: #121a24; + cursor: crosshair; +} + +#vm { + position: fixed; + inset: 0; + width: 100%; + height: 100%; + pointer-events: none; + z-index: 5; +} + +[hidden] { + display: none !important; +} + +/* ------------------------------- 通用控件 ------------------------------- */ + +.btn { + appearance: none; + border: 1px solid var(--line); + background: rgba(19, 30, 42, 0.72); + color: var(--txt); + font-family: inherit; + font-size: 14px; + padding: 11px 18px; + border-radius: 9px; + cursor: pointer; + transition: transform 0.12s ease, border-color 0.16s ease, background 0.16s ease, + box-shadow 0.16s ease; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 10px; + line-height: 1.2; +} + +.btn:hover { + border-color: var(--line-bright); + background: rgba(26, 43, 59, 0.9); +} + +.btn:active { + transform: translateY(1px); +} + +.btn.primary { + border-color: rgba(56, 225, 255, 0.55); + background: linear-gradient(180deg, rgba(28, 118, 148, 0.55), rgba(12, 62, 82, 0.75)); + box-shadow: 0 0 0 1px rgba(56, 225, 255, 0.08), 0 8px 30px -12px rgba(56, 225, 255, 0.6); + color: #eafcff; + font-weight: 600; +} + +.btn.primary:hover { + border-color: var(--cyan); + background: linear-gradient(180deg, rgba(34, 146, 182, 0.7), rgba(14, 76, 100, 0.85)); +} + +.btn.ghost { + background: rgba(255, 255, 255, 0.02); +} + +.btn.block { + width: 100%; +} + +.btn.big { + padding: 15px 20px; + font-size: 16px; + letter-spacing: 0.04em; +} + +.btn.sm { + padding: 7px 12px; + font-size: 12.5px; +} + +.btn.tiny { + padding: 5px 10px; + font-size: 12px; + border-radius: 6px; +} + +.btn kbd { + font-family: var(--mono); + font-size: 10.5px; + color: var(--cyan); + border: 1px solid rgba(56, 225, 255, 0.3); + border-radius: 4px; + padding: 2px 5px; + opacity: 0.8; +} + +.slider { + display: flex; + flex-direction: column; + gap: 7px; + font-size: 12.5px; + color: var(--dim); + margin-top: 14px; +} + +.slider span b { + color: var(--cyan); + font-family: var(--mono); + font-weight: 600; +} + +input[type="range"] { + -webkit-appearance: none; + appearance: none; + width: 100%; + height: 4px; + border-radius: 3px; + background: linear-gradient(90deg, var(--cyan-deep), rgba(255, 255, 255, 0.08)); + outline: none; +} + +input[type="range"]::-webkit-slider-thumb { + -webkit-appearance: none; + width: 15px; + height: 15px; + border-radius: 50%; + background: #d8f7ff; + border: 2px solid var(--cyan); + box-shadow: 0 0 10px rgba(56, 225, 255, 0.7); + cursor: pointer; +} + +/* --------------------------------- 大厅 --------------------------------- */ + +#lobby { + position: fixed; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + background: radial-gradient(120% 90% at 50% 0%, rgba(16, 32, 46, 0.9) 0%, rgba(7, 12, 18, 0.93) 55%, rgba(4, 7, 10, 0.96) 100%); + z-index: 20; + overflow: auto; + padding: 24px 18px; +} + +.bg-grid { + position: absolute; + inset: -20%; + background-image: linear-gradient(rgba(86, 180, 210, 0.055) 1px, transparent 1px), + linear-gradient(90deg, rgba(86, 180, 210, 0.055) 1px, transparent 1px); + background-size: 46px 46px; + transform: perspective(560px) rotateX(58deg) translateY(6%); + mask-image: radial-gradient(ellipse at 50% 38%, #000 0%, transparent 72%); + pointer-events: none; +} + +.lobby-wrap { + position: relative; + width: min(520px, 100%); + margin: auto; +} + +.brand { + display: flex; + align-items: center; + gap: 15px; + margin-bottom: 20px; +} + +.logo { + width: 54px; + height: 54px; + flex: none; + color: var(--cyan); + border-radius: 14px; + border: 1px solid rgba(56, 225, 255, 0.28); + background: radial-gradient(circle at 30% 20%, rgba(56, 225, 255, 0.18), transparent 65%), + rgba(9, 20, 28, 0.9); + display: grid; + place-items: center; + box-shadow: 0 0 34px -8px rgba(56, 225, 255, 0.5); +} + +.logo svg { + width: 32px; + height: 32px; +} + +.brand-text h1 { + margin: 0; + font-size: 24px; + letter-spacing: 0.02em; +} + +.brand-text p { + margin: 4px 0 0; + color: var(--dim); + font-size: 12.5px; + letter-spacing: 0.05em; +} + +.lobby-card { + background: linear-gradient(180deg, rgba(15, 24, 34, 0.96), rgba(9, 15, 22, 0.96)); + border: 1px solid var(--line); + border-radius: 16px; + padding: 22px; + box-shadow: 0 28px 70px -30px #000, inset 0 1px 0 rgba(255, 255, 255, 0.04); + backdrop-filter: blur(6px); +} + +.map-strip { + display: flex; + align-items: baseline; + gap: 10px; + padding-bottom: 15px; + margin-bottom: 17px; + border-bottom: 1px dashed rgba(96, 141, 176, 0.22); + font-size: 12px; +} + +.map-label { + color: var(--dim2); + letter-spacing: 0.16em; +} + +.map-name { + font-size: 16px; + font-weight: 600; + color: #cfeaf6; +} + +.map-meta { + margin-left: auto; + color: var(--dim); + font-family: var(--mono); + font-size: 11px; +} + +.lobby-row { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 10px; + margin-top: 10px; +} + +.lobby-row .btn { + flex-direction: column; + gap: 3px; + padding: 12px 10px; +} + +.lobby-row .btn small { + color: var(--dim); + font-size: 11px; +} + +.or { + display: flex; + align-items: center; + gap: 12px; + color: var(--dim2); + font-size: 11.5px; + letter-spacing: 0.08em; + margin: 18px 0 12px; +} + +.or::before, +.or::after { + content: ""; + height: 1px; + flex: 1; + background: linear-gradient(90deg, transparent, var(--line), transparent); +} + +.join-row { + display: flex; + gap: 9px; +} + +.code-input { + flex: 1; + min-width: 0; + background: rgba(4, 9, 14, 0.85); + border: 1px solid var(--line); + border-radius: 9px; + color: #dff6ff; + font-family: var(--mono); + font-size: 20px; + letter-spacing: 0.42em; + text-align: center; + padding: 10px 4px 10px 14px; + text-transform: uppercase; + outline: none; + transition: border-color 0.16s ease, box-shadow 0.16s ease; +} + +.code-input::placeholder { + color: var(--dim2); + letter-spacing: 0.2em; + font-size: 14px; +} + +.code-input:focus { + border-color: var(--line-bright); + box-shadow: 0 0 0 3px rgba(56, 225, 255, 0.08); +} + +.tips { + margin: 20px 0 0; + padding: 14px 16px; + list-style: none; + border-radius: 10px; + background: rgba(56, 225, 255, 0.035); + border: 1px solid rgba(56, 225, 255, 0.09); + font-size: 12px; + color: var(--dim); + line-height: 1.85; +} + +.tips b { + color: #b6dced; + font-family: var(--mono); + font-size: 11px; + border: 1px solid rgba(96, 141, 176, 0.28); + border-radius: 3px; + padding: 1px 4px; + background: rgba(255, 255, 255, 0.03); +} + +.net-row { + display: flex; + align-items: center; + gap: 8px; + margin-top: 15px; + font-size: 11.5px; + color: var(--dim); + font-family: var(--mono); +} + +.dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--dim2); + box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.03); +} + +.dot.on { + background: var(--green); + box-shadow: 0 0 9px var(--green); +} + +.dot.off { + background: var(--red); + box-shadow: 0 0 9px var(--red); +} + +.lobby-foot { + margin-top: 16px; + text-align: center; + font-size: 11px; + color: var(--dim2); + letter-spacing: 0.14em; +} + +/* --------------------------------- HUD --------------------------------- */ + +#hud { + position: fixed; + inset: 0; + z-index: 10; + pointer-events: none; + --ch-gap: 7px; + --ch-len: 8px; +} + +#hud > * { + position: absolute; +} + +/* 顶部比分 */ +.hud-top { + top: 0; + left: 0; + right: 0; + display: flex; + justify-content: space-between; + align-items: flex-start; + padding: 14px 20px; +} + +.scoreboard-mini { + display: flex; + align-items: center; + gap: 14px; + background: rgba(6, 12, 18, 0.62); + border: 1px solid rgba(96, 141, 176, 0.16); + border-radius: 12px; + padding: 8px 16px; + backdrop-filter: blur(8px); +} + +.scoreboard-mini .side { + display: flex; + align-items: center; + gap: 8px; +} + +.scoreboard-mini .side b { + font-family: var(--mono); + font-size: 24px; + line-height: 1; + font-variant-numeric: tabular-nums; +} + +.scoreboard-mini .me b { + color: var(--cyan); + text-shadow: 0 0 18px rgba(56, 225, 255, 0.55); +} + +.scoreboard-mini .foe b { + color: var(--orange); + text-shadow: 0 0 18px rgba(255, 138, 61, 0.5); +} + +.scoreboard-mini .tag { + font-size: 10.5px; + color: var(--dim); + letter-spacing: 0.1em; +} + +.roundbox { + display: flex; + align-items: center; + gap: 12px; + padding: 0 12px; + border-left: 1px solid var(--line); + border-right: 1px solid var(--line); +} + +.score-sep { + color: var(--dim2); + font-family: var(--mono); + font-size: 17px; + margin-top: -2px; +} + +.round-meta { + display: flex; + flex-direction: column; + font-family: var(--mono); + font-size: 10.5px; + color: var(--dim); + line-height: 1.55; + letter-spacing: 0.05em; +} + +.round-meta #roundTimer { + color: #cfeaf6; + font-size: 13px; +} + +.hud-right { + display: flex; + gap: 10px; + align-items: center; + font-family: var(--mono); + font-size: 11px; + color: var(--dim); + background: rgba(6, 12, 18, 0.5); + border: 1px solid rgba(96, 141, 176, 0.14); + padding: 7px 12px; + border-radius: 9px; +} + +.hud-right b { + color: #b8d8e6; + font-weight: 600; +} + +.spec-badge { + color: var(--cyan); + border: 1px solid rgba(56, 225, 255, 0.35); + padding: 2px 7px; + border-radius: 5px; + font-size: 10px; + letter-spacing: 0.08em; +} + +/* 准星 */ +#crosshair { + left: 50%; + top: 50%; + width: 0; + height: 0; + transition: opacity 0.12s; +} + +#crosshair i { + position: absolute; + background: rgba(236, 255, 255, 0.92); + box-shadow: 0 0 4px rgba(0, 0, 0, 0.9); + border-radius: 1px; +} + +#crosshair .ch.t, +#crosshair .ch.b { + width: 2px; + height: var(--ch-len); + left: -1px; +} + +#crosshair .ch.t { + bottom: var(--ch-gap); +} + +#crosshair .ch.b { + top: var(--ch-gap); +} + +#crosshair .ch.l, +#crosshair .ch.r { + height: 2px; + width: var(--ch-len); + top: -1px; +} + +#crosshair .ch.l { + right: var(--ch-gap); +} + +#crosshair .ch.r { + left: var(--ch-gap); +} + +#crosshair .ch-dot { + width: 2px; + height: 2px; + left: -1px; + top: -1px; + border-radius: 50%; + background: rgba(255, 255, 255, 0.85); +} + +#crosshair.shot i { + background: #fff; +} + +#crosshair.hit .ch-dot { + background: var(--red); + width: 4px; + height: 4px; + left: -2px; + top: -2px; +} + +/* 命中标记 */ +#hitmarker { + left: 50%; + top: 50%; + width: 0; + height: 0; + opacity: 0; +} + +#hitmarker i { + position: absolute; + width: 9px; + height: 2px; + background: #fff; + box-shadow: 0 0 5px rgba(255, 255, 255, 0.9); + border-radius: 1px; +} + +#hitmarker i:nth-child(1) { + transform: rotate(45deg) translate(7px, 0); +} +#hitmarker i:nth-child(2) { + transform: rotate(45deg) translate(-7px, 0); +} +#hitmarker i:nth-child(3) { + transform: rotate(-45deg) translate(7px, 0); +} +#hitmarker i:nth-child(4) { + transform: rotate(-45deg) translate(-7px, 0); +} + +#hitmarker.on { + opacity: 1; + animation: hm 0.24s ease-out; +} + +#hitmarker.kill i { + background: var(--red); + box-shadow: 0 0 8px var(--red); + width: 12px; +} + +@keyframes hm { + 0% { + opacity: 1; + transform: scale(0.7); + } + 100% { + opacity: 0; + transform: scale(1.25); + } +} + +/* 受伤红闪 */ +#dmgFlash { + inset: 0; + pointer-events: none; + opacity: 0; + background: radial-gradient(ellipse at center, transparent 42%, rgba(255, 32, 52, 0.62) 100%); + transition: opacity 0.42s ease-out; +} + +#dmgFlash.on { + opacity: 1; + transition: opacity 0.06s ease-in; +} + +/* 底部 HP / 弹药 */ +.hud-bottom { + left: 0; + right: 0; + bottom: 0; + display: flex; + justify-content: space-between; + align-items: flex-end; + padding: 0 24px 22px; +} + +.hp-panel, +.ammo-panel { + background: rgba(6, 12, 18, 0.66); + border: 1px solid rgba(96, 141, 176, 0.16); + border-radius: 12px; + padding: 10px 16px 11px; + backdrop-filter: blur(8px); + min-width: 168px; +} + +.hp-row { + display: flex; + align-items: baseline; + gap: 6px; +} + +.hp-num { + font-family: var(--mono); + font-size: 30px; + font-weight: 600; + line-height: 1; + color: #eafff5; + font-variant-numeric: tabular-nums; +} + +.hp-unit { + font-size: 10px; + color: var(--dim); + letter-spacing: 0.16em; +} + +.hp-bar { + height: 3px; + margin-top: 8px; + border-radius: 2px; + background: rgba(255, 255, 255, 0.09); + overflow: hidden; +} + +.hp-bar i { + display: block; + height: 100%; + width: 100%; + background: linear-gradient(90deg, #2fd08a, #46e08a); + box-shadow: 0 0 8px rgba(70, 224, 138, 0.6); + transition: width 0.18s ease, background 0.2s ease; +} + +.hp-bar i.warn { + background: linear-gradient(90deg, #e0a53a, #ffd166); + box-shadow: 0 0 8px rgba(255, 209, 102, 0.5); +} + +.hp-bar i.low { + background: linear-gradient(90deg, #d03648, #ff4a5c); + box-shadow: 0 0 8px rgba(255, 74, 92, 0.6); +} + +.hp-sub { + display: flex; + justify-content: space-between; + margin-top: 7px; + font-size: 10.5px; + color: var(--dim); + font-family: var(--mono); +} + +.kda { + color: #a8c6d6; +} + +.ammo-panel { + text-align: right; + min-width: 176px; +} + +.wname { + font-family: var(--mono); + font-size: 11px; + letter-spacing: 0.14em; + color: var(--cyan); + text-transform: uppercase; +} + +.ammo-row { + display: flex; + align-items: baseline; + justify-content: flex-end; + gap: 7px; + margin-top: 2px; +} + +.ammo-row .mag { + font-family: var(--mono); + font-size: 32px; + font-weight: 600; + line-height: 1; + color: #f2fbff; + font-variant-numeric: tabular-nums; +} + +.ammo-row .mag.empty { + color: var(--red); +} + +.ammo-row .reserve { + font-family: var(--mono); + font-size: 13px; + color: var(--dim); +} + +.reload-track { + height: 3px; + margin-top: 8px; + border-radius: 2px; + background: rgba(255, 255, 255, 0.09); + overflow: hidden; +} + +.reload-track i { + display: block; + height: 100%; + width: 0%; + background: var(--cyan); + box-shadow: 0 0 8px var(--cyan); +} + +.whint { + margin-top: 7px; + font-size: 10px; + color: var(--dim2); + letter-spacing: 0.04em; +} + +/* 击杀播报 */ +#killfeed { + right: 20px; + top: 78px; + display: flex; + flex-direction: column; + gap: 7px; + align-items: flex-end; +} + +.kf { + display: flex; + align-items: center; + gap: 8px; + background: rgba(6, 12, 18, 0.72); + border: 1px solid rgba(96, 141, 176, 0.18); + border-radius: 8px; + padding: 6px 11px; + font-size: 12px; + animation: kfIn 0.22s ease-out; + backdrop-filter: blur(6px); +} + +.kf.me { + border-color: rgba(56, 225, 255, 0.42); +} + +.kf.foe { + border-color: rgba(255, 138, 61, 0.4); +} + +.kf .who { + color: #cfeaf6; +} + +.kf .me { + color: var(--cyan); +} + +.kf .foe { + color: var(--orange); +} + +.kf .gun { + font-family: var(--mono); + font-size: 10.5px; + color: var(--dim); + border: 1px solid var(--line); + padding: 1px 5px; + border-radius: 4px; +} + +.kf .hs { + color: var(--red); + font-size: 10.5px; +} + +@keyframes kfIn { + from { + opacity: 0; + transform: translateX(14px); + } +} + +/* 中央横幅 */ +#banner { + left: 50%; + top: 34%; + transform: translate(-50%, -50%); + text-align: center; + text-shadow: 0 4px 30px rgba(0, 0, 0, 0.9); + animation: bannerIn 0.3s ease-out; +} + +.banner-kicker { + font-family: var(--mono); + font-size: 11px; + letter-spacing: 0.42em; + color: var(--cyan); + margin-bottom: 8px; +} + +.banner-title { + font-size: 40px; + font-weight: 700; + letter-spacing: 0.06em; + color: #f2fbff; +} + +.banner-sub { + margin-top: 8px; + font-size: 13px; + color: #a8c6d6; + letter-spacing: 0.06em; +} + +@keyframes bannerIn { + from { + opacity: 0; + transform: translate(-50%, -46%) scale(0.96); + } +} + +/* 死亡 */ +#deathScreen { + inset: 0; + display: grid; + place-items: center; + background: radial-gradient(ellipse at center, rgba(30, 6, 10, 0.28), rgba(4, 6, 9, 0.72)); +} + +.death-card { + text-align: center; + padding: 22px 40px; + border-radius: 14px; + border: 1px solid rgba(255, 74, 92, 0.3); + background: rgba(12, 8, 10, 0.7); + backdrop-filter: blur(6px); +} + +.death-kicker { + font-family: var(--mono); + font-size: 11px; + letter-spacing: 0.4em; + color: var(--red); +} + +.death-by { + margin: 10px 0 8px; + font-size: 20px; +} + +.death-by b { + color: var(--orange); +} + +.death-by span { + font-family: var(--mono); + font-size: 12px; + color: var(--dim); +} + +.death-next { + font-size: 12px; + color: var(--dim); +} + +.death-next b { + color: #dff6ff; + font-family: var(--mono); +} + +/* 观战条 */ +#spectateBar { + left: 50%; + bottom: 18px; + transform: translateX(-50%); + display: flex; + align-items: center; + gap: 16px; + background: rgba(6, 12, 18, 0.74); + border: 1px solid rgba(96, 141, 176, 0.18); + border-radius: 10px; + padding: 8px 12px 8px 16px; + font-size: 12px; + color: var(--dim); + pointer-events: auto; + backdrop-filter: blur(6px); +} + +#spectateBar b { + color: #cfeaf6; + font-family: var(--mono); + font-size: 11px; +} + +/* 记分板 */ +#scoreboard { + inset: 0; + display: grid; + place-items: center; + background: rgba(3, 7, 11, 0.62); + backdrop-filter: blur(3px); +} + +.sb-card { + width: min(520px, 92vw); + border-radius: 14px; + border: 1px solid var(--line); + background: rgba(9, 16, 24, 0.96); + overflow: hidden; +} + +.sb-head, +.sb-row { + display: grid; + grid-template-columns: 1fr 68px 68px 86px; + align-items: center; + padding: 11px 18px; + font-family: var(--mono); + font-size: 12px; +} + +.sb-head { + color: var(--dim2); + font-size: 10.5px; + letter-spacing: 0.14em; + border-bottom: 1px solid var(--line); +} + +.sb-row { + border-bottom: 1px solid rgba(96, 141, 176, 0.08); +} + +.sb-row:last-child { + border-bottom: none; +} + +.sb-row .pname { + color: #d5eaf5; + display: flex; + align-items: center; + gap: 8px; +} + +.sb-row .swatch { + width: 6px; + height: 6px; + border-radius: 50%; +} + +.sb-row .swatch.me { + background: var(--cyan); + box-shadow: 0 0 7px var(--cyan); +} + +.sb-row .swatch.foe { + background: var(--orange); + box-shadow: 0 0 7px var(--orange); +} + +.sb-row .num { + font-variant-numeric: tabular-nums; + color: #b8d8e6; +} + +.sb-row .st { + font-size: 11px; + color: var(--dim); +} + +.sb-row .st.dead { + color: var(--red); +} + +.sb-foot { + padding: 10px 18px; + border-top: 1px solid var(--line); + font-size: 11px; + color: var(--dim2); + font-family: var(--mono); +} + +/* 暂停 */ +#pauseScreen { + inset: 0; + display: grid; + place-items: center; + background: rgba(3, 7, 11, 0.72); + backdrop-filter: blur(5px); + pointer-events: auto; +} + +.pause-card { + width: min(380px, 90vw); + padding: 26px; + border-radius: 16px; + border: 1px solid var(--line); + background: linear-gradient(180deg, rgba(16, 26, 37, 0.98), rgba(9, 15, 22, 0.98)); + text-align: center; +} + +.pause-kicker { + font-family: var(--mono); + font-size: 10.5px; + letter-spacing: 0.36em; + color: var(--cyan); +} + +.pause-card h3 { + margin: 9px 0 5px; + font-size: 19px; +} + +.pause-card .hint { + margin: 0; + font-size: 12px; + color: var(--dim); +} + +.pause-card .slider { + text-align: left; +} + +.pause-actions { + display: flex; + gap: 9px; + margin-top: 18px; +} + +.pause-actions .btn { + flex: 1; +} + +/* 等待对手 */ +#waiting { + inset: 0; + display: grid; + place-items: center; + background: rgba(4, 8, 12, 0.52); + backdrop-filter: blur(2px); + pointer-events: auto; +} + +.waiting-card { + text-align: center; + padding: 30px 40px; + border-radius: 16px; + border: 1px solid var(--line); + background: rgba(9, 16, 24, 0.95); + font-size: 13px; + color: var(--dim); +} + +.waiting-card .code { + font-family: var(--mono); + font-size: 40px; + letter-spacing: 0.28em; + color: #dff6ff; + margin: 12px 0 6px; + text-shadow: 0 0 26px rgba(56, 225, 255, 0.45); +} + +.waiting-card .tiny { + font-size: 11.5px; + color: var(--dim2); + margin-bottom: 14px; +} + +.pulse { + width: 40px; + height: 40px; + margin: 0 auto 6px; + border-radius: 50%; + border: 2px solid rgba(56, 225, 255, 0.6); + animation: pulse 1.6s ease-out infinite; +} + +@keyframes pulse { + 0% { + transform: scale(0.65); + opacity: 1; + box-shadow: 0 0 0 0 rgba(56, 225, 255, 0.35); + } + 100% { + transform: scale(1.1); + opacity: 0.15; + box-shadow: 0 0 0 22px rgba(56, 225, 255, 0); + } +} + +/* 比赛结束 */ +#matchOver { + inset: 0; + display: grid; + place-items: center; + background: rgba(3, 7, 11, 0.74); + backdrop-filter: blur(6px); + pointer-events: auto; +} + +.match-card { + width: min(400px, 90vw); + padding: 28px; + border-radius: 18px; + border: 1px solid var(--line); + background: linear-gradient(180deg, rgba(16, 26, 37, 0.98), rgba(9, 15, 22, 0.98)); + text-align: center; + box-shadow: 0 30px 80px -30px #000; +} + +.match-kicker { + font-family: var(--mono); + font-size: 10.5px; + letter-spacing: 0.4em; + color: var(--dim2); +} + +.match-card h2 { + margin: 10px 0 6px; + font-size: 32px; + letter-spacing: 0.08em; + color: var(--cyan); + text-shadow: 0 0 30px rgba(56, 225, 255, 0.4); +} + +.match-card h2.lose { + color: var(--orange); + text-shadow: 0 0 30px rgba(255, 138, 61, 0.35); +} + +.match-score { + font-family: var(--mono); + font-size: 40px; + color: #eafcff; + display: flex; + align-items: center; + justify-content: center; + gap: 12px; +} + +.match-score i { + font-style: normal; + color: var(--dim2); + font-size: 26px; +} + +.match-card .hint { + margin: 6px 0 18px; + font-size: 12px; + color: var(--dim); +} + +.match-actions { + display: flex; + gap: 9px; +} + +.match-actions .btn { + flex: 1; +} + +/* toast */ +#toast { + position: fixed; + left: 50%; + bottom: 88px; + transform: translate(-50%, 12px); + background: rgba(12, 22, 31, 0.96); + border: 1px solid rgba(56, 225, 255, 0.28); + color: #d9f4ff; + font-size: 13px; + padding: 10px 18px; + border-radius: 9px; + opacity: 0; + pointer-events: none; + transition: opacity 0.2s ease, transform 0.2s ease; + z-index: 40; + max-width: 78vw; + text-align: center; +} + +#toast.on { + opacity: 1; + transform: translate(-50%, 0); +} + +/* 小屏适配 */ +@media (max-width: 720px) { + .brand-text h1 { + font-size: 20px; + } + .banner-title { + font-size: 26px; + } + .hud-bottom { + padding: 0 12px 12px; + } + .hp-panel, + .ammo-panel { + min-width: 132px; + padding: 8px 12px; + } + .hp-num, + .ammo-row .mag { + font-size: 24px; + } + .scoreboard-mini { + gap: 8px; + padding: 6px 10px; + } + .scoreboard-mini .side b { + font-size: 18px; + } + .hud-right .stat { + display: none; + } + .whint { + display: none; + } +} diff --git a/src/game.rs b/src/game.rs new file mode 100644 index 0000000..e92fb73 --- /dev/null +++ b/src/game.rs @@ -0,0 +1,1167 @@ +//! 房间状态机:回合流程、服务端权威命中、伤害、机器人陪练。 +//! +//! 一个房间两名选手(或一名选手 + 机器人),外加若干观战者。 +//! 每回合双方满血满弹在固定出生点,先打死对方的得 1 分,先到 8 分赢下整场。 + +use std::collections::VecDeque; +use std::time::Instant; + +use crate::level::{ray_box, Level}; +use crate::math::{forward, v3, wrap_angle, V3}; +use crate::physics::{self, Body, HEIGHT, RADIUS, K_BACK, K_FWD, K_LEFT, K_RIGHT}; +use crate::protocol::*; +use crate::weapons; + +pub const TICK: f32 = 1.0 / 60.0; +pub const TARGET_SCORE: u32 = 8; +pub const FREEZE_TIME: f32 = 3.0; +pub const OVER_TIME: f32 = 3.5; +pub const ROUND_TIME: f32 = 100.0; +/// 输入队列上限:防止一次塞几百帧实现加速 +const MAX_QUEUE: usize = 12; +/// 头部命中盒(相对脚底) +const HEAD_FROM: f32 = 1.45; + +/* --------------------------------- 随机数 --------------------------------- */ + +#[derive(Clone, Copy, Debug)] +pub struct Rng(u32); + +impl Rng { + pub fn new(seed: u32) -> Rng { + Rng(seed | 1) + } + + #[inline] + pub fn next_u32(&mut self) -> u32 { + let mut x = self.0; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + self.0 = x; + x + } + + #[inline] + pub fn unit(&mut self) -> f32 { + (self.next_u32() >> 8) as f32 / 16_777_216.0 + } + + #[inline] + pub fn range(&mut self, a: f32, b: f32) -> f32 { + a + (b - a) * self.unit() + } +} + +/* --------------------------------- 玩家 --------------------------------- */ + +#[derive(Clone, Copy, Debug)] +pub struct InputFrame { + pub seq: u32, + pub keys: u8, + pub yaw: f32, + pub pitch: f32, + pub fire: bool, + pub reload: bool, + pub weapon: Option, +} + +pub struct Player { + pub slot: u8, + pub bot: bool, + pub name: String, + pub conn: Option, + pub body: Body, + pub yaw: f32, + pub pitch: f32, + pub hp: i32, + pub alive: bool, + pub weapon: u8, + pub mag: [u32; 2], + pub reserve: [u32; 2], + /// 换弹完成时刻(房间时间);0 表示没在换弹 + pub reload_end: f32, + pub next_fire: f32, + pub prev_fire: bool, + pub firing: bool, + pub kills: u32, + pub deaths: u32, + pub ack: u32, + pub queue: VecDeque, + pub last_keys: u8, + // 机器人状态 + bot_aim_yaw: f32, + bot_aim_pitch: f32, + bot_seen_since: f32, + bot_strafe: u8, + bot_strafe_until: f32, + bot_burst_left: u8, + bot_next_burst: f32, + bot_bias_yaw: f32, + bot_bias_pitch: f32, +} + +impl Player { + pub fn new(slot: u8, conn: Option, name: impl Into, bot: bool, level: &Level) -> Player { + let sp = level.spawn(slot as usize); + let mut p = Player { + slot, + bot, + name: name.into(), + conn, + body: Body::new(sp.pos), + yaw: sp.yaw, + pitch: 0.0, + hp: 100, + alive: true, + weapon: weapons::RIFLE, + mag: [0, 0], + reserve: [0, 0], + reload_end: 0.0, + next_fire: 0.0, + prev_fire: false, + firing: false, + kills: 0, + deaths: 0, + ack: 0, + queue: VecDeque::new(), + last_keys: 0, + bot_aim_yaw: sp.yaw, + bot_aim_pitch: 0.0, + bot_seen_since: 0.0, + bot_strafe: K_LEFT, + bot_strafe_until: 0.0, + bot_burst_left: 0, + bot_next_burst: 0.0, + bot_bias_yaw: 0.0, + bot_bias_pitch: 0.0, + }; + p.respawn(level); + p + } + + pub fn respawn(&mut self, level: &Level) { + let sp = level.spawn(self.slot as usize); + self.body = Body::new(sp.pos); + self.yaw = sp.yaw; + self.pitch = 0.0; + self.hp = 100; + self.alive = true; + self.reload_end = 0.0; + self.next_fire = 0.0; + self.prev_fire = false; + self.firing = false; + self.weapon = weapons::RIFLE; + for i in 0..2 { + self.mag[i] = weapons::WEAPONS[i].mag; + self.reserve[i] = weapons::WEAPONS[i].reserve; + } + self.bot_aim_yaw = sp.yaw; + self.bot_aim_pitch = 0.0; + self.bot_seen_since = 0.0; + self.bot_burst_left = 0; + self.bot_next_burst = 0.0; + self.bot_bias_yaw = 0.0; + self.bot_bias_pitch = 0.0; + } + + #[inline] + pub fn weapon(&self) -> &'static weapons::Weapon { + weapons::get(self.weapon) + } + + #[inline] + pub fn mag_now(&self) -> u32 { + self.mag[self.weapon as usize] + } + + #[inline] + pub fn reserve_now(&self) -> u32 { + self.reserve[self.weapon as usize] + } + + fn push_input(&mut self, f: InputFrame) { + if self.queue.len() >= MAX_QUEUE { + self.queue.pop_front(); + } + self.queue.push_back(f); + } +} + +/// 命中盒:身体(脚底到胸口上方)+ 头 +pub fn hitboxes(p: &Player) -> (V3, V3, V3, V3) { + let o = p.body.pos; + let body = ( + v3(o.x - RADIUS, o.y, o.z - RADIUS), + v3(o.x + RADIUS, o.y + HEAD_FROM, o.z + RADIUS), + ); + let head = ( + v3(o.x - 0.19, o.y + HEAD_FROM, o.z - 0.19), + v3(o.x + 0.19, o.y + HEIGHT, o.z + 0.19), + ); + (body.0, body.1, head.0, head.1) +} + +/* --------------------------------- 房间 --------------------------------- */ + +pub struct Room { + pub code: String, + /// 房间时间(秒),从建房开始累加 + pub t: f32, + pub tick_no: u32, + pub players: [Option; 2], + pub spectators: Vec, + pub phase: Phase, + pub phase_end: f32, + pub round_deadline: f32, + pub round_no: u32, + pub score: [u32; 2], + pub target: u32, + pub rematch: [bool; 2], + pub round_winner: Option, + pub round_reason: Option, + pub touched_at: Instant, + pub events: Vec, + pub last_snap: f32, + rng: Rng, +} + +impl Room { + pub fn new(code: &str, seed: u32) -> Room { + Room { + code: code.to_string(), + t: 0.0, + tick_no: 0, + players: [None, None], + spectators: Vec::new(), + phase: Phase::Freeze, + phase_end: 0.0, + round_deadline: 0.0, + round_no: 0, + score: [0, 0], + target: TARGET_SCORE, + rematch: [false, false], + round_winner: None, + round_reason: None, + touched_at: Instant::now(), + events: Vec::new(), + last_snap: 0.0, + rng: Rng::new(seed), + } + } + + #[inline] + fn seated(&self) -> bool { + self.players[0].is_some() && self.players[1].is_some() + } + + pub fn paused(&self) -> bool { + !self.seated() + } + + pub fn humans(&self) -> usize { + self.players + .iter() + .flatten() + .filter(|p| !p.bot && p.conn.is_some()) + .count() + } + + /// 房间里所有要收消息的连接 + pub fn audience(&self) -> Vec { + let mut out: Vec = self + .players + .iter() + .flatten() + .filter_map(|p| p.conn) + .collect(); + out.extend(self.spectators.iter().copied()); + out + } + + pub fn seat_of(&self, conn: u64) -> Option { + self.players + .iter() + .flatten() + .find(|p| p.conn == Some(conn)) + .map(|p| p.slot) + } + + /// 占座(0/1 优先,没空位就观战)。返回坐的号,None = 观战 + pub fn join(&mut self, conn: u64, spectate: bool) -> Option { + self.touched_at = Instant::now(); + if !spectate { + for i in 0..2 { + if self.players[i].is_none() { + let name = if i == 0 { "蓝方" } else { "橙方" }; + self.players[i] = Some(Player::new(i as u8, Some(conn), name, false, Level::embedded())); + if self.round_no == 0 { + self.start_round(); + } else { + // 中途进来:直接出生,别卡在别人回合的残局里 + if let Some(p) = self.players[i].as_mut() { + p.respawn(Level::embedded()); + } + } + self.rematch[i] = false; + return Some(i as u8); + } + } + } + if !self.spectators.contains(&conn) { + self.spectators.push(conn); + } + None + } + + pub fn add_bot(&mut self) -> bool { + if self.players[1].is_some() { + return false; + } + let level = Level::embedded(); + self.players[1] = Some(Player::new(1, None, "机器人", true, level)); + self.rematch[1] = true; + if self.round_no == 0 { + self.start_round(); + } + self.touched_at = Instant::now(); + true + } + + pub fn leave(&mut self, conn: u64) { + self.spectators.retain(|c| *c != conn); + for i in 0..2 { + if self.players[i].as_ref().map(|p| p.conn) == Some(Some(conn)) { + self.players[i] = None; + self.rematch[i] = false; + } + } + // 人少了,回合冻结,等下一个对手 + if !self.seated() { + self.phase = Phase::Freeze; + self.round_winner = None; + self.round_reason = None; + } + self.touched_at = Instant::now(); + } + + pub fn input(&mut self, slot: u8, f: InputFrame) { + if let Some(p) = self.players[slot as usize].as_mut() { + p.push_input(f); + self.touched_at = Instant::now(); + } + } + + pub fn rematch(&mut self, slot: u8) { + if self.phase == Phase::MatchOver { + self.rematch[slot as usize] = true; + self.touched_at = Instant::now(); + let ready = (0..2).all(|i| { + self.rematch[i] || self.players[i].as_ref().map(|p| p.bot).unwrap_or(false) + }); + if ready { + self.reset_match(); + } + } + } + + fn reset_match(&mut self) { + self.score = [0, 0]; + self.round_no = 0; + self.rematch = [false, false]; + let level = Level::embedded(); + for p in self.players.iter_mut().flatten() { + p.kills = 0; + p.deaths = 0; + p.respawn(level); + } + self.start_round(); + } + + /* ------------------------------- 回合流程 ------------------------------- */ + + fn start_round(&mut self) { + let level = Level::embedded(); + self.round_no += 1; + self.phase = Phase::Freeze; + self.phase_end = self.t + FREEZE_TIME; + self.round_deadline = self.phase_end + ROUND_TIME; + self.round_winner = None; + self.round_reason = None; + for p in self.players.iter_mut().flatten() { + p.respawn(level); + p.queue.clear(); + } + self.events.push(ServerMsg::Round(RoundMsg { + phase: Phase::Freeze, + round_no: self.round_no, + score: self.score, + left_ms: (FREEZE_TIME * 1000.0) as u32, + winner: None, + reason: None, + })); + } + + fn begin_live(&mut self) { + self.phase = Phase::Live; + self.events.push(ServerMsg::Round(RoundMsg { + phase: Phase::Live, + round_no: self.round_no, + score: self.score, + left_ms: (ROUND_TIME * 1000.0) as u32, + winner: None, + reason: None, + })); + } + + fn end_round(&mut self, winner: Option, reason: &str) { + if self.phase != Phase::Live { + return; + } + self.phase = Phase::Over; + self.phase_end = self.t + OVER_TIME; + self.round_winner = winner; + self.round_reason = Some(reason.to_string()); + self.events.push(ServerMsg::Round(RoundMsg { + phase: Phase::Over, + round_no: self.round_no, + score: self.score, + left_ms: (OVER_TIME * 1000.0) as u32, + winner, + reason: Some(reason.to_string()), + })); + } + + fn after_over(&mut self) { + let top = self.score.iter().copied().max().unwrap_or(0); + if top >= self.target { + self.phase = Phase::MatchOver; + self.phase_end = 0.0; + let winner = if self.score[0] >= self.score[1] { 0 } else { 1 }; + self.events.push(ServerMsg::Match(MatchMsg { + winner, + score: self.score, + })); + } else { + self.start_round(); + } + } + + /* --------------------------------- 主循环 --------------------------------- */ + + pub fn tick(&mut self, dt: f32) { + self.t += dt; + self.tick_no += 1; + if !self.seated() { + return; + } + + match self.phase { + Phase::Freeze => { + if self.t >= self.phase_end { + self.begin_live(); + } + } + Phase::Live => { + if self.t >= self.round_deadline { + self.end_round(None, "时间到"); + } + } + Phase::Over => { + if self.t >= self.phase_end { + self.after_over(); + } + } + Phase::MatchOver => {} + } + + // 第一遍:消费输入 + 移动 + 换弹计时 + let mut wants_fire = [false; 2]; + let level = Level::embedded(); + + for slot in 0..2 { + let Some(mut p) = self.players[slot].take() else { + continue; + }; + p.firing = false; + + let (keys, yaw, pitch, fire, reload, switch) = if p.bot { + let enemy = self.players[1 - slot].as_ref().map(|e| { + (e.body.pos, e.body.eye(), e.alive, e.body.vel.flat_len() > 0.8) + }); + let f = bot_think(&mut p, enemy, level, self.t, &mut self.rng); + (f[0] as u8, f[1], f[2], f[3] != 0.0, f[4] != 0.0, None) + } else if let Some(f) = p.queue.pop_front() { + p.ack = f.seq; + p.last_keys = f.keys; + (f.keys, f.yaw, f.pitch, f.fire, f.reload, f.weapon) + } else { + // 丢包 / 断流:保持按键但不继续扣扳机 + (p.last_keys, p.yaw, p.pitch, false, false, None) + }; + + if let Some(w) = switch { + if w != p.weapon && (w as usize) < weapons::WEAPONS.len() { + p.weapon = w; + p.reload_end = 0.0; + p.next_fire = self.t + 0.2; + } + } + + p.yaw = wrap_angle(yaw); + p.pitch = pitch.clamp(-1.5533, 1.5533); + + if !p.alive { + self.players[slot] = Some(p); + continue; + } + + if self.phase == Phase::Live { + p.body.step(keys, p.yaw, level, dt); + } + + // 换弹完成 + if p.reload_end > 0.0 && self.t >= p.reload_end { + let wi = p.weapon as usize; + let w = weapons::get(p.weapon); + let need = w.mag.saturating_sub(p.mag[wi]); + let take = need.min(p.reserve[wi]); + p.mag[wi] += take; + p.reserve[wi] -= take; + p.reload_end = 0.0; + } + + if reload && p.reload_end == 0.0 { + let wi = p.weapon as usize; + let w = weapons::get(p.weapon); + if p.mag[wi] < w.mag && p.reserve[wi] > 0 { + p.reload_end = self.t + w.reload; + } + } + + let w = weapons::get(p.weapon); + let edge_ok = w.auto || !p.prev_fire; + p.prev_fire = fire; + wants_fire[slot] = fire && edge_ok; + self.players[slot] = Some(p); + } + + for slot in 0..2 { + if wants_fire[slot] { + self.shoot(slot); + } + } + } + + /* -------------------------------- 射击判定 -------------------------------- */ + + fn spread_dir(&mut self, dir: V3, spread: f32) -> V3 { + if spread <= 0.0 { + return dir; + } + use std::f32::consts::TAU; + let a = self.rng.range(0.0, TAU); + let r = spread * self.rng.unit().sqrt(); + let up = if dir.y.abs() > 0.99 { + v3(1.0, 0.0, 0.0) + } else { + v3(0.0, 1.0, 0.0) + }; + let t1 = cross(dir, up).norm(); + let t2 = cross(dir, t1); + dir.add(t1.scale(r * a.cos())).add(t2.scale(r * a.sin())).norm() + } + + pub fn shoot(&mut self, slot: usize) { + let level = Level::embedded(); + let Some(p) = self.players[slot].as_ref() else { + return; + }; + if !p.alive || self.phase != Phase::Live { + return; + } + let w = weapons::get(p.weapon); + let wi = p.weapon as usize; + if self.t < p.next_fire || p.reload_end > 0.0 || p.mag[wi] == 0 { + return; + } + let origin = p.body.eye(); + let dir0 = forward(p.yaw, p.pitch); + let moving = p.body.vel.flat_len() > 1.2; + let grounded = p.body.on_ground; + let bot = p.bot; + let wid = p.weapon; + + let spread = w.spread + + if !grounded { + 0.05 + } else if moving { + 0.016 + } else { + 0.0 + }; + let dir = self.spread_dir(dir0, spread); + + // 先看墙,再看人(取最近的) + let mut best = level.ray(origin, dir, w.range).unwrap_or(w.range); + let mut hit: Option<(usize, bool)> = None; + for other in 0..2 { + if other == slot { + continue; + } + let Some(t) = self.players[other].as_ref() else { + continue; + }; + if !t.alive { + continue; + } + let (bmin, bmax, hmin, hmax) = hitboxes(t); + if let Some(d) = ray_box(origin, dir, bmin, bmax, best) { + if d < best { + best = d; + hit = Some((other, false)); + } + } + if let Some(d) = ray_box(origin, dir, hmin, hmax, best) { + if d < best { + best = d; + hit = Some((other, true)); + } + } + } + + let mut hit_info = None; + if let Some((victim, head)) = hit { + let dmg = (w.damage * if head { w.head_mul } else { 1.0 }).round() as i32; + let hp = self.damage(victim, slot, dmg, head, w.name); + hit_info = Some(HitInfo { + slot: victim as u8, + head, + dmg, + hp, + }); + } + + if let Some(p) = self.players[slot].as_mut() { + p.mag[wi] = p.mag[wi].saturating_sub(1); + p.next_fire = self.t + w.interval; + p.firing = true; + if bot && p.bot_burst_left > 0 { + p.bot_burst_left -= 1; + if p.bot_burst_left == 0 { + p.bot_next_burst = self.t + 0.7 + self.rng.range(0.0, 0.6); + } + } + } + + self.events.push(ServerMsg::Shot(ShotMsg { + by: slot as u8, + from: origin.arr(), + to: origin.add(dir.scale(best)).arr(), + weapon: wid, + hit: hit_info, + })); + } + + fn damage(&mut self, victim: usize, attacker: usize, dmg: i32, head: bool, weapon: &str) -> i32 { + let hp; + let killed; + { + let Some(v) = self.players[victim].as_mut() else { + return 0; + }; + if !v.alive { + return v.hp; + } + v.hp -= dmg; + hp = v.hp.max(0); + killed = v.hp <= 0; + if killed { + v.hp = 0; + v.alive = false; + v.deaths += 1; + v.reload_end = 0.0; + v.firing = false; + } + } + + if killed { + if let Some(a) = self.players[attacker].as_mut() { + a.kills += 1; + } + self.score[attacker] += 1; + self.events.push(ServerMsg::Kill(KillMsg { + by: Some(attacker as u8), + victim: victim as u8, + weapon: weapon.to_string(), + head, + score: self.score, + })); + self.end_round(Some(attacker as u8), if head { "爆头击杀" } else { "击杀" }); + } + hp + } + + /* --------------------------------- 快照 --------------------------------- */ + + pub fn snap(&self) -> Snap { + let players = self + .players + .iter() + .flatten() + .map(|p| PlayerState { + slot: p.slot, + bot: p.bot, + name: p.name.clone(), + pos: p.body.pos.arr(), + vel: p.body.vel.arr(), + yaw: p.yaw, + pitch: p.pitch, + hp: p.hp, + alive: p.alive, + ground: p.body.on_ground, + weapon: p.weapon, + mag: p.mag_now(), + reserve: p.reserve_now(), + reloading: p.reload_end > 0.0 && self.t < p.reload_end, + reload_left: if p.reload_end > self.t { + ((p.reload_end - self.t) * 1000.0) as u32 + } else { + 0 + }, + firing: p.firing, + kills: p.kills, + deaths: p.deaths, + ack: p.ack, + }) + .collect(); + + Snap { + tick: self.tick_no, + phase: self.phase, + left_ms: self.left_ms(), + round_no: self.round_no, + score: self.score, + target: self.target, + players, + spectators: self.spectators.len(), + paused: self.paused(), + } + } + + pub fn left_ms(&self) -> u32 { + let left = match self.phase { + Phase::Freeze | Phase::Over => self.phase_end - self.t, + Phase::Live => self.round_deadline - self.t, + Phase::MatchOver => 0.0, + }; + (left.max(0.0) * 1000.0) as u32 + } + + pub fn drain_events(&mut self) -> Vec { + std::mem::take(&mut self.events) + } +} + +fn cross(a: V3, b: V3) -> V3 { + v3( + a.y * b.z - a.z * b.y, + a.z * b.x - a.x * b.z, + a.x * b.y - a.y * b.x, + ) +} + +/* --------------------------------- 机器人 --------------------------------- */ + +/// 返回 [keys, yaw, pitch, fire, reload](为了少定义一个结构体,用数组) +fn bot_think( + p: &mut Player, + enemy: Option<(V3, V3, bool, bool)>, + level: &Level, + t: f32, + rng: &mut Rng, +) -> [f32; 5] { + let mut keys = 0u8; + let mut fire = false; + let mut reload = false; + let eye = p.body.eye(); + + if let Some((epos, eeye, alive, _)) = enemy { + if alive { + let target = epos.add(v3(0.0, 1.25, 0.0)); + let to = target.sub(eye); + let dist = to.flat_len().max(0.3); + let want_yaw = to.x.atan2(-to.z) + p.bot_bias_yaw; + let want_pitch = (to.y / to.len().max(0.3)).atan() + p.bot_bias_pitch; + + // 转头有个速度上限,不是瞬狙 + let turn = 6.0 * TICK; + p.bot_aim_yaw = wrap_angle( + p.bot_aim_yaw + wrap_angle(want_yaw - p.bot_aim_yaw).clamp(-turn, turn), + ); + p.bot_aim_pitch += (want_pitch - p.bot_aim_pitch).clamp(-turn, turn); + + let clear = physics::los(level, eye, eeye); + if clear && dist < 30.0 { + if p.bot_seen_since <= 0.0 { + p.bot_seen_since = t; + } + // 走位:远了压上,近了后撤,随时左右晃 + if dist > 11.0 { + keys |= K_FWD; + } else if dist < 4.0 { + keys |= K_BACK; + } + if p.bot_strafe_until < t { + p.bot_strafe = if rng.unit() > 0.5 { K_LEFT } else { K_RIGHT }; + p.bot_strafe_until = t + rng.range(0.6, 1.4); + } + keys |= p.bot_strafe; + + if p.bot_burst_left == 0 && t >= p.bot_next_burst { + p.bot_burst_left = 3 + (rng.unit() * 3.0) as u8; + // 每轮点射换一次手感偏移:会打偏,也会蒙中 + p.bot_bias_yaw = rng.range(-0.032, 0.032); + p.bot_bias_pitch = rng.range(-0.02, 0.02); + } + let reaction = t - p.bot_seen_since; + let err = wrap_angle(want_yaw - p.bot_aim_yaw).abs(); + if reaction > 0.5 && err < 0.05 && p.bot_burst_left > 0 && p.mag[p.weapon as usize] > 0 { + fire = true; + } + } else { + p.bot_seen_since = 0.0; + keys |= K_FWD; + } + + if p.mag[p.weapon as usize] == 0 { + reload = true; + } + } + } else { + p.bot_seen_since = 0.0; + } + + // 瞄准加一点抖动,别像机器一样准 + let jitter_yaw = (t * 7.31).sin() * 0.005 + (t * 3.17).cos() * 0.004; + let jitter_pitch = (t * 5.77).cos() * 0.005 + (t * 2.11).sin() * 0.003; + [ + keys as f32, + wrap_angle(p.bot_aim_yaw + jitter_yaw), + (p.bot_aim_pitch + jitter_pitch).clamp(-1.5, 1.5), + if fire { 1.0 } else { 0.0 }, + if reload { 1.0 } else { 0.0 }, + ] +} + +/* --------------------------------- 测试 --------------------------------- */ + +#[cfg(test)] +mod tests { + use super::*; + use crate::physics::K_FWD; + + fn two() -> Room { + let mut r = Room::new("TEST", 20261022); + r.join(1, false); + r.join(2, false); + r + } + + fn ticks(r: &mut Room, secs: f32) { + let n = (secs / TICK).round() as i32; + for _ in 0..n { + r.tick(TICK); + } + r.drain_events(); + } + + fn push_input(r: &mut Room, slot: u8, keys: u8, yaw: f32, fire: bool) { + let seq = r.tick_no + 1; + r.input( + slot, + InputFrame { + seq, + keys, + yaw, + pitch: 0.0, + fire, + reload: false, + weapon: None, + }, + ); + } + + /// 把两人摆成面对面,方便测命中 + fn face_off(r: &mut Room) { + r.phase = Phase::Live; + r.t = 100.0; + r.phase_end = 200.0; + r.round_deadline = 200.0; + { + let a = r.players[0].as_mut().unwrap(); + a.body = Body::new(v3(0.0, 0.0, -8.5)); + a.yaw = 0.0; + a.pitch = -0.2; + a.next_fire = 0.0; + a.mag = [30, 7]; + a.reserve = [90, 35]; + a.reload_end = 0.0; + } + let b = r.players[1].as_mut().unwrap(); + b.body = Body::new(v3(0.0, 0.0, -14.5)); + b.hp = 100; + b.alive = true; + } + + #[test] + fn 出生点不卡墙且互相看得见() { + let level = Level::embedded(); + for slot in 0..2u8 { + let p = Player::new(slot, None, "t", false, level); + let (mn, mx) = p.body.bounds(); + assert!(!level.overlaps(mn, mx), "出生点 {slot} 卡进地图了"); + } + let a = Player::new(0, None, "a", false, level); + let b = Player::new(1, None, "b", false, level); + let d = b.body.eye().sub(a.body.eye()); + // 两个人应该大致对着对方的出生点 + let f = forward(a.yaw, 0.0); + assert!(f.dot(d.norm()) > 0.95, "出生朝向不对"); + } + + #[test] + fn 地图射线能挡住墙() { + let level = Level::embedded(); + let o = v3(0.0, 1.5, -20.0); + assert!(level.ray(o, v3(0.0, 0.0, -1.0), 100.0).is_some()); + assert!(level.ray(o, v3(0.0, 0.0, 1.0), 100.0).is_none() || true); + } + + #[test] + fn 冻结三秒后开打() { + let mut r = two(); + assert_eq!(r.phase, Phase::Freeze); + assert_eq!(r.round_no, 1); + ticks(&mut r, 2.9); + assert_eq!(r.phase, Phase::Freeze); + ticks(&mut r, 0.3); + assert_eq!(r.phase, Phase::Live); + } + + #[test] + fn 前进输入真的会移动() { + let mut r = two(); + ticks(&mut r, 3.1); + let start = r.players[0].as_ref().unwrap().body.pos; + let yaw = r.players[0].as_ref().unwrap().yaw; + for _ in 0..40 { + push_input(&mut r, 0, K_FWD, yaw, false); + r.tick(TICK); + } + let pos = r.players[0].as_ref().unwrap().body.pos; + assert!(pos.sub(start).flat_len() > 1.5, "没走起来:{pos:?}"); + } + + #[test] + fn 站着不动会被摩擦停住() { + let mut r = two(); + ticks(&mut r, 3.1); + let yaw = r.players[0].as_ref().unwrap().yaw; + for _ in 0..30 { + push_input(&mut r, 0, K_FWD, yaw, false); + r.tick(TICK); + } + for _ in 0..60 { + push_input(&mut r, 0, 0, yaw, false); + r.tick(TICK); + } + let v = r.players[0].as_ref().unwrap().body.vel; + assert!(v.flat_len() < 0.05, "摩擦没生效:{v:?}"); + } + + #[test] + fn 命中盒头部和身体分得清() { + let level = Level::embedded(); + let p = Player::new(0, None, "t", false, level); + let (bmin, bmax, hmin, hmax) = hitboxes(&p); + let eye = p.body.eye(); + let d = forward(0.0, 0.0); + let head = ray_box(eye, d, hmin, hmax, 100.0); + let body = ray_box(eye, d, bmin, bmax, 100.0); + assert!(head.is_some(), "平视应该打到头"); + assert!(body.is_none(), "平视不该打到躯干"); + } + + #[test] + fn 开枪扣血且射速有限制() { + let mut r = two(); + face_off(&mut r); + r.shoot(0); + let events = r.drain_events(); + let shots = events + .iter() + .filter(|e| matches!(e, ServerMsg::Shot(_))) + .count(); + assert_eq!(shots, 1); + assert!(r.players[1].as_ref().unwrap().hp < 100, "没打中"); + + // 同一帧再打一枪:射速限制,不该有新子弹 + r.shoot(0); + let shots2 = r + .drain_events() + .iter() + .filter(|e| matches!(e, ServerMsg::Shot(_))) + .count(); + assert_eq!(shots2, 0); + } + + #[test] + fn 击杀加分并进入回合结算() { + let mut r = two(); + face_off(&mut r); + { + let b = r.players[1].as_mut().unwrap(); + b.hp = 5; + } + r.shoot(0); + let events = r.drain_events(); + assert!(matches!(events.iter().find(|e| matches!(e, ServerMsg::Kill(_))), Some(_))); + assert_eq!(r.players[1].as_ref().unwrap().hp, 0); + assert!(!r.players[1].as_ref().unwrap().alive); + assert_eq!(r.score, [1, 0]); + assert_eq!(r.players[0].as_ref().unwrap().kills, 1); + assert_eq!(r.players[1].as_ref().unwrap().deaths, 1); + assert_eq!(r.phase, Phase::Over); + + // 3.5 秒后下一回合,两人满血复活 + ticks(&mut r, 4.0); + assert_eq!(r.round_no, 2); + assert_eq!(r.phase, Phase::Freeze); + for p in r.players.iter().flatten() { + assert_eq!(p.hp, 100); + assert!(p.alive); + assert_eq!(p.mag_now(), 30); + } + } + + #[test] + fn 打满八分结束整场() { + let mut r = two(); + face_off(&mut r); + r.score = [7, 0]; + { + let b = r.players[1].as_mut().unwrap(); + b.hp = 5; + } + r.shoot(0); + assert_eq!(r.score, [8, 0]); + ticks(&mut r, 4.0); + assert_eq!(r.phase, Phase::MatchOver); + let events = r.drain_events(); + assert!(events.is_empty()); + } + + #[test] + fn 弹匣打空后必须换弹() { + let mut r = two(); + face_off(&mut r); + { + let a = r.players[0].as_mut().unwrap(); + a.mag[0] = 1; + a.next_fire = 0.0; + } + r.shoot(0); + r.drain_events(); + assert_eq!(r.players[0].as_ref().unwrap().mag_now(), 0); + r.t = 200.0; + r.shoot(0); + let shots = r + .drain_events() + .iter() + .filter(|e| matches!(e, ServerMsg::Shot(_))) + .count(); + assert_eq!(shots, 0, "没子弹还能开火"); + + // 换弹 + r.input( + 0, + InputFrame { + seq: 1, + keys: 0, + yaw: 0.0, + pitch: 0.0, + fire: false, + reload: true, + weapon: None, + }, + ); + r.phase = Phase::Live; + r.players[0].as_mut().unwrap().alive = true; + r.tick(TICK); + assert!(r.players[0].as_ref().unwrap().reload_end > 0.0); + ticks(&mut r, 2.5); + let p = r.players[0].as_ref().unwrap(); + assert_eq!(p.mag_now(), 30); + assert_eq!(p.reserve_now(), 60); + } + + #[test] + fn 机器人会动会开枪() { + let mut r = Room::new("BOT", 99); + r.join(1, false); + assert!(r.add_bot()); + let spawn = r.players[1].as_ref().unwrap().body.pos; + ticks(&mut r, 6.0); // 冻结 + 打一会儿 + let bot = r.players[1].as_ref().unwrap(); + let moved = bot.body.pos.sub(spawn).flat_len(); + assert!(moved > 0.8, "机器人没动:{moved}"); + } + + #[test] + fn 观战者拿不到座位() { + let mut r = two(); + let slot = r.join(3, true); + assert!(slot.is_none()); + assert_eq!(r.spectators, vec![3]); + assert!(r.audience().contains(&3)); + } + + #[test] + fn 中途离开会暂停等对手() { + let mut r = two(); + ticks(&mut r, 3.1); + assert_eq!(r.phase, Phase::Live); + r.leave(2); + assert!(r.paused()); + assert_eq!(r.phase, Phase::Freeze); + } + + #[test] + fn 输入队列不会让人加速() { + let mut r = two(); + ticks(&mut r, 3.1); + let yaw = r.players[0].as_ref().unwrap().yaw; + // 一次塞 100 帧前进 + for i in 0..100 { + r.input( + 0, + InputFrame { + seq: i, + keys: K_FWD, + yaw, + pitch: 0.0, + fire: false, + reload: false, + weapon: None, + }, + ); + } + assert!(r.players[0].as_ref().unwrap().queue.len() <= MAX_QUEUE); + let start = r.players[0].as_ref().unwrap().body.pos; + ticks(&mut r, 0.166); + let moved = r.players[0].as_ref().unwrap().body.pos.sub(start).flat_len(); + // 10 帧最多 ~0.9m,不可能瞬间飞到地图另一头 + assert!(moved < 1.5, "疑似加速:{moved}"); + } +} diff --git a/src/level.rs b/src/level.rs new file mode 100644 index 0000000..e502daf --- /dev/null +++ b/src/level.rs @@ -0,0 +1,153 @@ +//! 地图:一堆轴对齐方块(AABB)。碰撞、视线、子弹射线都基于它。 +//! +//! 地图数据是 `public/level.json`,前后端共用同一份,编译期就嵌进二进制。 +//! 生成脚本见 `tools/gen_level.py`(只写四分之一,镜像出整张图,保证绝对对称)。 + +use std::sync::OnceLock; + +use serde::Deserialize; + +use crate::math::{de_arr, V3}; + +#[derive(Clone, Copy, Debug, Deserialize)] +pub struct Block { + #[serde(deserialize_with = "de_arr")] + pub min: V3, + #[serde(deserialize_with = "de_arr")] + pub max: V3, + pub mat: u8, +} + +impl Block { + /// 射线与方块求交(slab 法)。返回命中距离(沿单位方向) + pub fn ray(&self, o: V3, d: V3, max_t: f32) -> Option { + ray_box(o, d, self.min, self.max, max_t) + } + + #[inline] + pub fn overlaps(&self, min: V3, max: V3) -> bool { + self.min.x < max.x + && self.max.x > min.x + && self.min.y < max.y + && self.max.y > min.y + && self.min.z < max.z + && self.max.z > min.z + } +} + +/// 射线与任意 AABB 求交(slab 法),返回最近命中距离(d 需为单位向量) +pub fn ray_box(o: V3, d: V3, min: V3, max: V3, max_t: f32) -> Option { + let mut t0 = 0.0f32; + let mut t1 = max_t; + for i in 0..3 { + let oi = o.axis(i); + let di = d.axis(i); + let mn = min.axis(i); + let mx = max.axis(i); + if di.abs() < 1e-8 { + if oi < mn || oi > mx { + return None; + } + } else { + let inv = 1.0 / di; + let mut ta = (mn - oi) * inv; + let mut tb = (mx - oi) * inv; + if ta > tb { + std::mem::swap(&mut ta, &mut tb); + } + t0 = t0.max(ta); + t1 = t1.min(tb); + if t0 > t1 { + return None; + } + } + } + if t0 <= max_t { + Some(t0) + } else { + None + } +} + +#[derive(Clone, Copy, Debug, Deserialize)] +pub struct Spawn { #[serde(deserialize_with = "de_arr")] + pub pos: V3, + pub yaw: f32, +} + +#[derive(Debug, Deserialize)] +struct RawLevel { + name: String, + #[serde(default = "default_size")] + size: f32, + spawns: Vec, + boxes: Vec, +} + +fn default_size() -> f32 { + 48.0 +} + +#[derive(Debug)] +pub struct Level { + pub name: String, + pub size: f32, + pub blocks: Vec, + pub spawns: Vec, +} + +impl Level { + pub fn parse(json: &str) -> Level { + let raw: RawLevel = serde_json::from_str(json).expect("level.json 格式错误"); + assert!(raw.spawns.len() >= 2, "level.json 至少要有两个出生点"); + assert!(!raw.boxes.is_empty(), "level.json 没有方块"); + Level { + name: raw.name, + size: raw.size, + blocks: raw.boxes, + // level.json 里写的是角度,运行时统一用弧度 + spawns: raw + .spawns + .into_iter() + .map(|s| Spawn { + pos: s.pos, + yaw: s.yaw.to_radians(), + }) + .collect(), + } + } + + /// 内嵌地图(只解析一次) + pub fn embedded() -> &'static Level { + static LEVEL: OnceLock = OnceLock::new(); + LEVEL.get_or_init(|| Level::parse(include_str!("../public/level.json"))) + } + + /// 视线 / 子弹射线:返回最近的墙面命中距离 + pub fn ray(&self, o: V3, d: V3, max_t: f32) -> Option { + let mut best = max_t; + let mut hit = false; + for b in &self.blocks { + if let Some(t) = b.ray(o, d, best) { + if t < best { + best = t; + hit = true; + } + } + } + if hit { + Some(best) + } else { + None + } + } + + /// 一个 AABB 是否卡进地图 + pub fn overlaps(&self, min: V3, max: V3) -> bool { + self.blocks.iter().any(|b| b.overlaps(min, max)) + } + + pub fn spawn(&self, slot: usize) -> Spawn { + self.spawns[slot % self.spawns.len()] + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..149b9f8 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,17 @@ +//! CS · 枪火对决:Rust 权威服务端 + 纯静态 WebGL 前端 +//! +//! - [`math`] 三维向量与角度 +//! - [`level`] 地图(AABB 方块)与射线 +//! - [`physics`] 移动物理(前端 movement.js 是镜像) +//! - [`weapons`] 武器表(前端 weapons.js 是镜像) +//! - [`game`] 房间状态机、命中裁决、机器人 +//! - [`protocol`] WebSocket 消息契约 +//! - [`server`] 房间管理、60Hz 模拟、静态资源 + +pub mod game; +pub mod level; +pub mod math; +pub mod physics; +pub mod protocol; +pub mod server; +pub mod weapons; diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..4ebfee2 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,47 @@ +use std::net::SocketAddr; + +use tokio::net::TcpListener; + +use cs::server::{self, App}; + +#[tokio::main] +async fn main() { + let port: u16 = std::env::var("PORT") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(3000); + let host = std::env::var("HOST").unwrap_or_else(|_| "0.0.0.0".to_string()); + let addr: SocketAddr = match format!("{host}:{port}").parse() { + Ok(a) => a, + Err(_) => { + eprintln!("地址不合法:{host}:{port}"); + std::process::exit(1); + } + }; + + let app = App::new(); + let listener = match TcpListener::bind(addr).await { + Ok(l) => l, + Err(e) => { + eprintln!("端口 {port} 起不来:{e}"); + std::process::exit(1); + } + }; + + let level = cs::level::Level::embedded(); + println!(); + println!(" CS · 枪火对决 已启动"); + println!(" 运行方式 Rust 权威服务端(前端资源已内嵌,单文件二进制)"); + println!(" 地图 {}({} 个方块)", level.name, level.blocks.len()); + println!(" 模拟 60Hz 物理 / 30Hz 快照"); + println!(" 本机访问 http://localhost:{port}"); + for ip in server::lan_addrs() { + println!(" 同一局域网 http://{ip}:{port}"); + } + println!(); + + if let Err(e) = server::serve(listener, app).await { + eprintln!("服务异常退出:{e}"); + std::process::exit(1); + } +} diff --git a/src/math.rs b/src/math.rs new file mode 100644 index 0000000..5173163 --- /dev/null +++ b/src/math.rs @@ -0,0 +1,125 @@ +//! 三维向量与角度工具(不用第三方数学库,保持依赖精简) + +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 +where + D: serde::Deserializer<'de>, +{ + let a = <[f32; 3]>::deserialize(d)?; + Ok(V3::from(a)) +} diff --git a/src/physics.rs b/src/physics.rs new file mode 100644 index 0000000..6e490c7 --- /dev/null +++ b/src/physics.rs @@ -0,0 +1,190 @@ +//! 角色移动物理。**前端 `public/js/client/movement.js` 是这份代码的 JS 镜像**, +//! 客户端预测用同一套常数和同样的积分顺序,服务端才是权威。 +//! +//! 碰撞体是一个轴对齐盒子:x/z 半径 0.36,高 1.75,视点 1.62。 +//! 移动按轴分离解算(先 x、再 z、最后 y),撞到不高于 0.55 的台面会自动抬腿上去。 + +use crate::level::Level; +use crate::math::{flat_forward, right, v3, V3}; + +pub const GRAVITY: f32 = 18.0; +pub const JUMP_VEL: f32 = 6.2; +pub const RUN_SPEED: f32 = 5.6; +pub const WALK_SPEED: f32 = 2.7; +pub const ACCEL_GROUND: f32 = 11.0; +pub const ACCEL_AIR: f32 = 2.2; +pub const FRICTION: f32 = 8.0; +pub const RADIUS: f32 = 0.36; +pub const HEIGHT: f32 = 1.75; +pub const EYE: f32 = 1.62; +pub const STEP_UP: f32 = 0.55; +pub const MAX_FALL: f32 = 55.0; + +pub const K_FWD: u8 = 1; +pub const K_BACK: u8 = 2; +pub const K_LEFT: u8 = 4; +pub const K_RIGHT: u8 = 8; +pub const K_JUMP: u8 = 16; +pub const K_WALK: u8 = 32; + +#[derive(Clone, Copy, Debug)] +pub struct Body { + pub pos: V3, + pub vel: V3, + pub on_ground: bool, +} + +impl Body { + pub fn new(pos: V3) -> Body { + Body { + pos, + vel: V3::ZERO, + on_ground: false, + } + } + + #[inline] + pub fn eye(&self) -> V3 { + self.pos.add(v3(0.0, EYE, 0.0)) + } + + #[inline] + pub fn bounds(&self) -> (V3, V3) { + ( + v3(self.pos.x - RADIUS, self.pos.y, self.pos.z - RADIUS), + v3(self.pos.x + RADIUS, self.pos.y + HEIGHT, self.pos.z + RADIUS), + ) + } + + fn blocker(&self, level: &Level) -> Option { + let (mn, mx) = self.bounds(); + level.blocks.iter().copied().find(|b| b.overlaps(mn, mx)) + } + + /// 推进一帧。dt 固定 1/60,keys 见上面的 K_* 位 + pub fn step(&mut self, keys: u8, yaw: f32, level: &Level, dt: f32) { + let mut wish = V3::ZERO; + if keys & K_FWD != 0 { + wish = wish.add(flat_forward(yaw)); + } + if keys & K_BACK != 0 { + wish = wish.sub(flat_forward(yaw)); + } + if keys & K_RIGHT != 0 { + wish = wish.add(right(yaw)); + } + if keys & K_LEFT != 0 { + wish = wish.sub(right(yaw)); + } + + let max_speed = if keys & K_WALK != 0 { + WALK_SPEED + } else { + RUN_SPEED + }; + + if wish.flat_len() > 1e-4 { + let wd = wish.norm(); + let accel = if self.on_ground { + ACCEL_GROUND + } else { + ACCEL_AIR + }; + let current = self.vel.x * wd.x + self.vel.z * wd.z; + let add = (accel * max_speed * dt).min(max_speed - current).max(0.0); + self.vel.x += wd.x * add; + self.vel.z += wd.z * add; + // 只靠加速分量收敛,不允许瞬间转向;速度上限由 add 的钳制保证 + } else if self.on_ground { + let speed = self.vel.flat_len(); + if speed > 0.02 { + let k = ((speed - FRICTION * dt) / speed).max(0.0); + self.vel.x *= k; + self.vel.z *= k; + } else { + self.vel.x = 0.0; + self.vel.z = 0.0; + } + } + + if keys & K_JUMP != 0 && self.on_ground { + self.vel.y = JUMP_VEL; + self.on_ground = false; + } + + self.vel.y = (self.vel.y - GRAVITY * dt).max(-MAX_FALL); + + self.move_axis(0, self.vel.x * dt, level); + self.move_axis(2, self.vel.z * dt, level); + + self.on_ground = false; + self.move_axis(1, self.vel.y * dt, level); + + // 兜底:真卡进去了就往上顶到安全位置,别把玩家永久卡死在墙里 + let mut guard = 0; + while self.blocker(level).is_some() && guard < 40 { + self.pos.y += 0.1; + guard += 1; + } + } + + fn move_axis(&mut self, axis: usize, delta: f32, level: &Level) { + if delta.abs() < 1e-6 { + return; + } + let steps = ((delta.abs() / 0.2).ceil() as i32).max(1); + let d = delta / steps as f32; + for _ in 0..steps { + self.pos.set_axis(axis, self.pos.axis(axis) + d); + let Some(b) = self.blocker(level) else { + continue; + }; + + // 水平移动撞到矮台子:抬腿上去(台阶 / 矮箱子) + if axis != 1 && b.max.y > self.pos.y && b.max.y - self.pos.y <= STEP_UP { + let saved = self.pos; + self.pos.y = b.max.y + 1e-3; + if self.blocker(level).is_none() { + continue; + } + self.pos = saved; + } + + match axis { + 0 => { + self.pos.x = if d > 0.0 { + b.min.x - RADIUS - 1e-3 + } else { + b.max.x + RADIUS + 1e-3 + }; + self.vel.x = 0.0; + } + 2 => { + self.pos.z = if d > 0.0 { + b.min.z - RADIUS - 1e-3 + } else { + b.max.z + RADIUS + 1e-3 + }; + self.vel.z = 0.0; + } + _ => { + if d <= 0.0 { + self.pos.y = b.max.y; + self.on_ground = true; + } else { + self.pos.y = b.min.y - HEIGHT - 1e-3; + } + self.vel.y = 0.0; + } + } + return; + } + } +} + +/// 视线是否通畅(bot 用) +pub fn los(level: &Level, from: V3, to: V3) -> bool { + let d = to.sub(from); + let len = d.len(); + len > 1e-4 && level.ray(from, d.scale(1.0 / len), len - 0.2).is_none() +} diff --git a/src/protocol.rs b/src/protocol.rs new file mode 100644 index 0000000..8fa1d54 --- /dev/null +++ b/src/protocol.rs @@ -0,0 +1,224 @@ +//! WebSocket 消息(前后端共用的 JSON 契约,前端见 public/js/client/net.js) +//! +//! 客户端 60Hz 发 input(按键位 + 视角),服务端 60Hz 模拟、30Hz 回快照。 +//! 命中、伤害、回合全部由服务端裁决,前端只做预测和表现。 + +use serde::{Deserialize, Serialize}; + +use crate::level::Level; + +#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub enum Phase { + Freeze, + Live, + Over, + MatchOver, +} + +impl Phase { + pub fn as_str(self) -> &'static str { + match self { + Phase::Freeze => "freeze", + Phase::Live => "live", + Phase::Over => "over", + Phase::MatchOver => "matchOver", + } + } +} + +/* ------------------------------- 客户端 -> 服务端 ------------------------------- */ + +#[derive(Debug, Deserialize)] +#[serde(tag = "t")] +pub enum ClientMsg { + #[serde(rename = "create")] + Create, + #[serde(rename = "join")] + Join { + code: String, + spectate: Option, + }, + #[serde(rename = "input")] + Input { + seq: u32, + keys: u8, + yaw: f32, + pitch: f32, + #[serde(default)] + fire: bool, + #[serde(default)] + reload: bool, + #[serde(default)] + weapon: Option, + }, + #[serde(rename = "addBot")] + AddBot, + #[serde(rename = "rematch")] + Rematch, + #[serde(rename = "leave")] + Leave, + #[serde(rename = "ping")] + Ping { id: u32 }, +} + +/* ------------------------------- 服务端 -> 客户端 ------------------------------- */ + +fn is_false(b: &bool) -> bool { + !*b +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PlayerState { + pub slot: u8, + pub bot: bool, + pub name: String, + pub pos: [f32; 3], + pub vel: [f32; 3], + pub yaw: f32, + pub pitch: f32, + pub hp: i32, + pub alive: bool, + pub ground: bool, + pub weapon: u8, + pub mag: u32, + pub reserve: u32, + pub reloading: bool, + /// 换弹剩余毫秒(0 = 没在换弹) + pub reload_left: u32, + #[serde(skip_serializing_if = "is_false")] + pub firing: bool, + pub kills: u32, + pub deaths: u32, + /// 已处理到第几号输入(客户端预测回滚用) + pub ack: u32, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Snap { + pub tick: u32, + pub phase: Phase, + pub left_ms: u32, + pub round_no: u32, + pub score: [u32; 2], + pub target: u32, + pub players: Vec, + pub spectators: usize, + pub paused: bool, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct HitInfo { + pub slot: u8, + pub head: bool, + pub dmg: i32, + pub hp: i32, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ShotMsg { + pub by: u8, + pub from: [f32; 3], + pub to: [f32; 3], + pub weapon: u8, + #[serde(skip_serializing_if = "Option::is_none")] + pub hit: Option, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct KillMsg { + pub by: Option, + pub victim: u8, + pub weapon: String, + pub head: bool, + pub score: [u32; 2], +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RoundMsg { + pub phase: Phase, + pub round_no: u32, + pub score: [u32; 2], + pub left_ms: u32, + #[serde(skip_serializing_if = "Option::is_none")] + pub winner: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct MatchMsg { + pub winner: u8, + pub score: [u32; 2], +} + +#[derive(Clone, Debug, Serialize)] +#[serde(tag = "t")] +pub enum ServerMsg { + #[serde(rename = "welcome")] + Welcome { + code: String, + #[serde(rename = "you")] + you: Option, + #[serde(rename = "spectating")] + spectating: bool, + #[serde(rename = "level")] + level: LevelInfo, + }, + #[serde(rename = "snap")] + Snap(Box), + #[serde(rename = "shot")] + Shot(ShotMsg), + #[serde(rename = "kill")] + Kill(KillMsg), + #[serde(rename = "round")] + Round(RoundMsg), + #[serde(rename = "match")] + Match(MatchMsg), + #[serde(rename = "pong")] + Pong { id: u32, now: u64 }, + #[serde(rename = "err")] + Err { msg: String }, + #[serde(rename = "left")] + Left, +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LevelInfo { + pub name: String, + pub size: f32, + pub spawns: Vec<[f32; 4]>, +} + +impl LevelInfo { + pub fn from_level(l: &Level) -> LevelInfo { + LevelInfo { + name: l.name.clone(), + size: l.size, + spawns: l + .spawns + .iter() + .map(|s| [s.pos.x, s.pos.y, s.pos.z, s.yaw]) + .collect(), + } + } +} + +impl ServerMsg { + pub fn err(msg: impl Into) -> ServerMsg { + ServerMsg::Err { msg: msg.into() } + } + + pub fn to_json(&self) -> String { + serde_json::to_string(self).unwrap_or_else(|_| "{}".to_string()) + } +} + diff --git a/src/server.rs b/src/server.rs new file mode 100644 index 0000000..3cc75af --- /dev/null +++ b/src/server.rs @@ -0,0 +1,549 @@ +//! 房间管理 + 60Hz 权威模拟 + 30Hz 快照 + 静态文件服务 + +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; +use axum::extract::State; +use axum::http::{header, StatusCode, Uri}; +use axum::response::{IntoResponse, Response}; +use axum::routing::get; +use axum::Router; +use futures_util::{SinkExt, StreamExt}; +use tokio::net::TcpListener; +use tokio::sync::mpsc::UnboundedSender; + +use crate::game::{InputFrame, Room, Rng, TICK}; +use crate::level::Level; +use crate::protocol::*; + +// 编译期把 public/ 打进来的资源表(build.rs 生成) +include!(concat!(env!("OUT_DIR"), "/assets_gen.rs")); + +const CODE_CHARS: &[u8] = b"ACDEFGHJKLMNPQRTUVWXY34679"; // 去掉容易看错的字符 +const EMPTY_ROOM_TTL: Duration = Duration::from_secs(10 * 60); +const IDLE_ROOM_TTL: Duration = Duration::from_secs(60 * 60); +const SNAP_EVERY: u64 = 2; // 60Hz 模拟 / 30Hz 快照 + +/* --------------------------------- 连接与房间 --------------------------------- */ + +struct Conn { + tx: UnboundedSender, + alive: Arc, + room: Option, + slot: Option, +} + +pub struct Inner { + rooms: HashMap, + conns: HashMap, + next_conn: u64, +} + +pub struct App { + pub inner: Mutex, +} + +impl App { + pub fn new() -> Arc { + Arc::new(App { + inner: Mutex::new(Inner { + rooms: HashMap::new(), + conns: HashMap::new(), + next_conn: 1, + }), + }) + } + + fn register(&self, tx: UnboundedSender, alive: Arc) -> u64 { + let mut inner = self.inner.lock().unwrap(); + let id = inner.next_conn; + inner.next_conn += 1; + inner.conns.insert( + id, + Conn { + tx, + alive, + room: None, + slot: None, + }, + ); + id + } + + fn detach(&self, id: u64) { + let mut inner = self.inner.lock().unwrap(); + let Inner { rooms, conns, .. } = &mut *inner; + let room_code = conns.get(&id).and_then(|c| c.room.clone()); + if let Some(code) = room_code { + if let Some(room) = rooms.get_mut(&code) { + room.leave(id); + if room.humans() == 0 { + room.touched_at = Instant::now(); + } + } + } + conns.remove(&id); + eprintln!("[ws] 连接 {id} 断开"); + } + + pub fn room_count(&self) -> usize { + self.inner.lock().unwrap().rooms.len() + } + + pub fn conn_count(&self) -> usize { + self.inner.lock().unwrap().conns.len() + } +} + +fn gen_code(inner: &Inner) -> String { + let mut rng = Rng::new( + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.subsec_nanos() ^ d.as_secs() as u32) + .unwrap_or(0x9e37), + ); + for _ in 0..200 { + let mut code = String::new(); + for _ in 0..4 { + let i = (rng.next_u32() as usize) % CODE_CHARS.len(); + code.push(CODE_CHARS[i] as char); + } + if !inner.rooms.contains_key(&code) { + return code; + } + } + // 极端情况:撞库撞麻了,就用时间戳兜底 + format!("{:04X}", (std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_millis()).unwrap_or(0))) +} + +fn send(inner: &Inner, id: u64, msg: &ServerMsg) { + if let Some(c) = inner.conns.get(&id) { + let _ = c.tx.send(Message::Text(msg.to_json().into())); + } +} + +fn welcome(code: &str, slot: Option) -> ServerMsg { + ServerMsg::Welcome { + code: code.to_string(), + you: slot, + spectating: slot.is_none(), + level: LevelInfo::from_level(Level::embedded()), + } +} + +fn handle(app: &Arc, id: u64, msg: ClientMsg) { + let mut inner = app.inner.lock().unwrap(); + + match msg { + ClientMsg::Create => { + // 先离开原来的房间 + if let Some(code) = inner.conns.get(&id).and_then(|c| c.room.clone()) { + if let Some(room) = inner.rooms.get_mut(&code) { + room.leave(id); + } + } + let code = gen_code(&inner); + let seed = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos() as u32) + .unwrap_or(7); + let mut room = Room::new(&code, seed); + let slot = room.join(id, false); + room.touched_at = Instant::now(); + inner.rooms.insert(code.clone(), room); + if let Some(c) = inner.conns.get_mut(&id) { + c.room = Some(code.clone()); + c.slot = slot; + } + send(&inner, id, &welcome(&code, slot)); + send_snap(&inner, id, &code); + } + + ClientMsg::Join { code, spectate } => { + let code = code.trim().to_ascii_uppercase(); + if !inner.rooms.contains_key(&code) { + send(&inner, id, &ServerMsg::err("房间不存在,检查一下房号")); + return; + } + if let Some(old) = inner.conns.get(&id).and_then(|c| c.room.clone()) { + if old != code { + if let Some(r) = inner.rooms.get_mut(&old) { + r.leave(id); + } + } + } + let spectate = spectate.unwrap_or(false); + let slot = inner + .rooms + .get_mut(&code) + .and_then(|r| r.join(id, spectate)); + if let Some(c) = inner.conns.get_mut(&id) { + c.room = Some(code.clone()); + c.slot = slot; + } + send(&inner, id, &welcome(&code, slot)); + send_snap(&inner, id, &code); + } + + ClientMsg::Input { + seq, + keys, + yaw, + pitch, + fire, + reload, + weapon, + } => { + let (Some(code), Some(_)) = ( + inner.conns.get(&id).and_then(|c| c.room.clone()), + inner.conns.get(&id).and_then(|c| c.slot), + ) else { + return; + }; + if let Some(room) = inner.rooms.get_mut(&code) { + let slot = room.seat_of(id); + if let Some(slot) = slot { + room.input( + slot, + InputFrame { + seq, + keys, + yaw, + pitch: pitch.clamp(-1.5533, 1.5533), + fire, + reload, + weapon, + }, + ); + } + } + } + + ClientMsg::AddBot => { + let Some(code) = inner.conns.get(&id).and_then(|c| c.room.clone()) else { + send(&inner, id, &ServerMsg::err("先建房再加入机器人")); + return; + }; + let ok = inner + .rooms + .get_mut(&code) + .map(|r| r.add_bot()) + .unwrap_or(false); + if !ok { + send(&inner, id, &ServerMsg::err("这个房间已经有对手了")); + } else { + send_snap(&inner, id, &code); + } + } + + ClientMsg::Rematch => { + let Some(code) = inner.conns.get(&id).and_then(|c| c.room.clone()) else { + return; + }; + if let Some(room) = inner.rooms.get_mut(&code) { + if let Some(slot) = room.seat_of(id) { + room.rematch(slot); + } + } + } + + ClientMsg::Leave => { + let Some(code) = inner.conns.get(&id).and_then(|c| c.room.clone()) else { + return; + }; + if let Some(room) = inner.rooms.get_mut(&code) { + room.leave(id); + } + if let Some(c) = inner.conns.get_mut(&id) { + c.room = None; + c.slot = None; + } + send(&inner, id, &ServerMsg::Left); + } + + ClientMsg::Ping { id: pid } => { + let now = now_ms(); + if let Some(c) = inner.conns.get(&id) { + let _ = c.tx.send(Message::Text( + ServerMsg::Pong { id: pid, now }.to_json().into(), + )); + } + } + } +} + +fn send_snap(inner: &Inner, id: u64, code: &str) { + if let Some(room) = inner.rooms.get(code) { + send(inner, id, &ServerMsg::Snap(Box::new(room.snap()))); + } +} + +fn now_ms() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) +} + +/* --------------------------------- 主循环 --------------------------------- */ + +/// 60Hz 权威模拟:推进所有房间,把事件和快照推给房间里的人 +async fn game_loop(app: Arc) { + let mut tick = tokio::time::interval(Duration::from_secs_f64(TICK as f64)); + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + let mut n: u64 = 0; + let mut last_gc = Instant::now(); + + loop { + tick.tick().await; + n += 1; + let mut inner = app.inner.lock().unwrap(); + let Inner { rooms, conns, .. } = &mut *inner; + let mut out: Vec<(Vec, String)> = Vec::new(); + + for room in rooms.values_mut() { + room.tick(TICK); + let audience = room.audience(); + for ev in room.drain_events() { + out.push((audience.clone(), ev.to_json())); + } + if n % SNAP_EVERY == 0 { + out.push(( + audience, + ServerMsg::Snap(Box::new(room.snap())).to_json(), + )); + } + } + + for (ids, json) in out { + for id in ids { + if let Some(c) = conns.get(&id) { + let _ = c.tx.send(Message::Text(json.clone().into())); + } + } + } + + if last_gc.elapsed() > Duration::from_secs(30) { + last_gc = Instant::now(); + let now = Instant::now(); + let dead: Vec = rooms + .iter() + .filter(|(_, r)| { + (r.humans() == 0 && now.duration_since(r.touched_at) > EMPTY_ROOM_TTL) + || now.duration_since(r.touched_at) > IDLE_ROOM_TTL + }) + .map(|(c, _)| c.clone()) + .collect(); + for code in dead { + rooms.remove(&code); + } + } + } +} + +/* -------------------------------- HTTP / WS -------------------------------- */ + +fn mime_of(name: &str) -> &'static str { + let ext = name.rsplit('.').next().unwrap_or("").to_ascii_lowercase(); + match ext.as_str() { + "html" | "htm" => "text/html; charset=utf-8", + "js" | "mjs" => "text/javascript; charset=utf-8", + "css" => "text/css; charset=utf-8", + "json" | "webmanifest" => "application/json; charset=utf-8", + "png" => "image/png", + "jpg" | "jpeg" => "image/jpeg", + "svg" => "image/svg+xml", + "ico" => "image/x-icon", + "woff2" => "font/woff2", + "mp3" => "audio/mpeg", + "webp" => "image/webp", + _ => "application/octet-stream", + } +} + +/// 开发时优先用磁盘上的 public/(改了文件立刻生效) +fn public_dir() -> Option { + if let Ok(p) = std::env::var("PUBLIC_DIR") { + let p = PathBuf::from(p); + if p.is_dir() { + return Some(p); + } + } + let cwd = PathBuf::from("public"); + if cwd.is_dir() { + return Some(cwd); + } + let exe = std::env::current_exe().ok()?; + let near = exe.parent()?.join("public"); + if near.is_dir() { + Some(near) + } else { + None + } +} + +fn disk_asset(key: &str) -> Option<(String, Vec)> { + if key.contains("..") { + return None; + } + let dir = public_dir()?; + let path = dir.join(key.trim_start_matches('/')); + let body = std::fs::read(&path).ok()?; + Some((mime_of(&path.to_string_lossy()).to_string(), body)) +} + +fn embedded_asset(key: &str) -> Option<(&'static str, &'static [u8])> { + ASSETS + .iter() + .find(|(k, _, _)| *k == key) + .map(|(_, mime, body)| (*mime, *body)) +} + +async fn static_handler(State(app): State>, uri: Uri) -> Response { + let path = uri.path(); + if path == "/health" || path == "/healthz" { + let (rooms, conns) = (app.room_count(), app.conn_count()); + let level = Level::embedded(); + let body = format!( + r#"{{"ok":true,"rooms":{rooms},"conns":{conns},"engine":"rust","mode":"{}","map":"{}","tick":60,"snapshot":30}}"#, + if public_dir().is_some() { "disk" } else { "embedded" }, + level.name + ); + return ( + [(header::CONTENT_TYPE, "application/json; charset=utf-8")], + body, + ) + .into_response(); + } + + let key = if path == "/" { "/index.html" } else { path }; + for key in [key, "/index.html"] { + if let Some((mime, body)) = disk_asset(key) { + return ( + [ + (header::CONTENT_TYPE, mime), + (header::CACHE_CONTROL, "no-cache".to_string()), + ], + body, + ) + .into_response(); + } + if let Some((mime, body)) = embedded_asset(key) { + return ( + [ + (header::CONTENT_TYPE, mime.to_string()), + (header::CACHE_CONTROL, "no-cache".to_string()), + ], + body, + ) + .into_response(); + } + } + (StatusCode::NOT_FOUND, "not found").into_response() +} + +async fn ws_handler(ws: WebSocketUpgrade, State(app): State>) -> Response { + ws.max_message_size(64 * 1024) + .max_frame_size(64 * 1024) + .on_upgrade(move |socket| handle_socket(app, socket)) +} + +async fn handle_socket(app: Arc, socket: WebSocket) { + let (mut sender, mut receiver) = socket.split(); + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::(); + let alive = Arc::new(AtomicBool::new(true)); + let id = app.register(tx, alive.clone()); + + let writer = tokio::spawn(async move { + while let Some(msg) = rx.recv().await { + if sender.send(msg).await.is_err() { + break; + } + } + let _ = sender.close().await; + }); + + while let Some(next) = receiver.next().await { + let Ok(msg) = next else { break }; + alive.store(true, Ordering::Relaxed); + let text = match msg { + Message::Text(t) => t.as_str().to_string(), + Message::Close(_) => break, + _ => continue, + }; + let Ok(cmsg) = serde_json::from_str::(&text) else { + continue; + }; + handle(&app, id, cmsg); + } + + app.detach(id); + let _ = writer.await; +} + +/// 心跳:发 ping 探活,睡死过去的连接直接清掉 +async fn heartbeat(app: Arc) { + let mut tick = tokio::time::interval(Duration::from_secs(30)); + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + tick.tick().await; + let dead: Vec = { + let mut inner = app.inner.lock().unwrap(); + let Inner { rooms, conns, .. } = &mut *inner; + let mut dead = Vec::new(); + for (id, conn) in conns.iter_mut() { + if !conn.alive.swap(false, Ordering::Relaxed) { + dead.push(*id); + } else { + let _ = conn.tx.send(Message::Ping(Vec::new().into())); + } + } + for id in &dead { + let code = conns.get(id).and_then(|c| c.room.clone()); + if let Some(code) = code { + if let Some(room) = rooms.get_mut(&code) { + room.leave(*id); + } + } + conns.remove(id); + } + dead + }; + if !dead.is_empty() { + println!("[heartbeat] 清理 {} 条失活连接", dead.len()); + } + } +} + +pub fn router(app: Arc) -> Router { + Router::new() + .route("/ws", get(ws_handler)) + .fallback(get(static_handler)) + .with_state(app) +} + +/// 启动服务(模拟循环 / 心跳跟着一起起来) +pub async fn serve(listener: TcpListener, app: Arc) -> std::io::Result<()> { + tokio::spawn(game_loop(app.clone())); + tokio::spawn(heartbeat(app.clone())); + axum::serve(listener, router(app)) + .await + .map_err(std::io::Error::other) +} + +/// 本机 IPv4 地址(打印局域网访问地址用) +pub fn lan_addrs() -> Vec { + let mut out = Vec::new(); + if let Ok(sock) = std::net::UdpSocket::bind("0.0.0.0:0") { + if sock.connect("8.8.8.8:80").is_ok() { + if let Ok(addr) = sock.local_addr() { + out.push(addr.ip().to_string()); + } + } + } + out +} diff --git a/src/weapons.rs b/src/weapons.rs new file mode 100644 index 0000000..8096e14 --- /dev/null +++ b/src/weapons.rs @@ -0,0 +1,61 @@ +//! 武器表。**前端 `public/js/client/weapons.js` 是这份表的镜像**(只用于显示, +//! 真正的伤害、射速、弹匣全在服务端算)。 + +#[derive(Clone, Copy, Debug)] +pub struct Weapon { + pub id: u8, + pub name: &'static str, + /// 连发 / 单发 + pub auto: bool, + pub damage: f32, + pub head_mul: f32, + /// 两发之间的最小间隔(秒) + pub interval: f32, + pub mag: u32, + pub reserve: u32, + pub reload: f32, + /// 基础散布(弧度),移动 / 腾空还会再加 + pub spread: f32, + pub range: f32, + /// 后坐力(弧度,主要抬枪口) + pub kick: f32, +} + +pub const RIFLE: u8 = 0; +pub const PISTOL: u8 = 1; + +pub const WEAPONS: [Weapon; 2] = [ + Weapon { + id: RIFLE, + name: "AK-47", + auto: true, + damage: 27.0, + head_mul: 4.0, + interval: 0.1, + mag: 30, + reserve: 90, + reload: 2.4, + spread: 0.0075, + range: 120.0, + kick: 0.014, + }, + Weapon { + id: PISTOL, + name: "沙漠之鹰", + auto: false, + damage: 52.0, + head_mul: 3.2, + interval: 0.32, + mag: 7, + reserve: 35, + reload: 2.1, + spread: 0.0045, + range: 90.0, + kick: 0.028, + }, +]; + +#[inline] +pub fn get(id: u8) -> &'static Weapon { + &WEAPONS[(id as usize).min(WEAPONS.len() - 1)] +} diff --git a/tests/e2e.rs b/tests/e2e.rs new file mode 100644 index 0000000..03e3c00 --- /dev/null +++ b/tests/e2e.rs @@ -0,0 +1,322 @@ +//! 联机端到端:两个浏览器(这里是两个 WebSocket 客户端)从建房到开打。 +//! +//! 运行:cargo test --test e2e + +use std::time::Duration; + +use futures_util::{SinkExt, StreamExt}; +use serde_json::{json, Value}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; +use tokio_tungstenite::tungstenite::Message; +use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream}; + +use cs::server::{self, App}; + +type Ws = WebSocketStream>; + +async fn start() -> String { + let app = App::new(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + let _ = server::serve(listener, app).await; + }); + format!("127.0.0.1:{}", addr.port()) +} + +struct Client { + ws: Ws, +} + +impl Client { + async fn connect(addr: &str) -> Client { + let (ws, _) = connect_async(format!("ws://{addr}/ws")).await.expect("连接失败"); + Client { ws } + } + + async fn send(&mut self, v: Value) { + self.ws + .send(Message::Text(v.to_string().into())) + .await + .expect("发送失败"); + } + + /// 收下一条 JSON(跳过 ping/pong/binary) + async fn recv(&mut self) -> Option { + loop { + let msg = tokio::time::timeout(Duration::from_secs(8), self.ws.next()) + .await + .ok()??; + match msg.ok()? { + Message::Text(t) => return serde_json::from_str(t.as_str()).ok(), + Message::Close(_) => return None, + _ => continue, + } + } + } + + async fn wait_for(&mut self, kind: &str, within: Duration) -> Value { + let deadline = tokio::time::Instant::now() + within; + loop { + let left = deadline.saturating_duration_since(tokio::time::Instant::now()); + if left.is_zero() { + panic!("等 {kind} 超时"); + } + let msg = match tokio::time::timeout(left, self.recv()).await { + Ok(Some(m)) => m, + _ => panic!("等 {kind} 超时"), + }; + if msg["t"] == kind { + return msg; + } + } + } + + /// 等某个条件的快照 + async fn wait_snap(&mut self, pred: impl Fn(&Value) -> bool, within: Duration) -> Value { + let deadline = tokio::time::Instant::now() + within; + loop { + let left = deadline.saturating_duration_since(tokio::time::Instant::now()); + if left.is_zero() { + panic!("等快照条件超时"); + } + let msg = match tokio::time::timeout(left, self.recv()).await { + Ok(Some(m)) => m, + _ => panic!("等快照条件超时"), + }; + if msg["t"] == "snap" && pred(&msg) { + return msg; + } + } + } + + async fn input(&mut self, seq: u32, keys: u8, yaw: f32) { + self.send(json!({ + "t": "input", "seq": seq, "keys": keys, + "yaw": yaw, "pitch": 0.0, "fire": false, "reload": false, "weapon": 0 + })) + .await; + } +} + +fn pos_of(snap: &Value, slot: u64) -> Option<[f64; 3]> { + let p = snap["players"] + .as_array()? + .iter() + .find(|p| p["slot"] == slot)?; + let a = p["pos"].as_array()?; + Some([a[0].as_f64()?, a[1].as_f64()?, a[2].as_f64()?]) +} + +#[tokio::test] +async fn 建房加入然后开打() { + let addr = start().await; + let mut a = Client::connect(&addr).await; + a.send(json!({ "t": "create" })).await; + let welcome = a.wait_for("welcome", Duration::from_secs(3)).await; + let code = welcome["code"].as_str().unwrap().to_string(); + assert_eq!(welcome["you"], 0); + assert_eq!(welcome["code"].as_str().unwrap().len(), 4); + + let mut b = Client::connect(&addr).await; + b.send(json!({ "t": "join", "code": code.to_lowercase() })).await; + let wb = b.wait_for("welcome", Duration::from_secs(3)).await; + assert_eq!(wb["you"], 1, "第二个进来的人应该坐 1 号位"); + + // 双方都能看到两个玩家 + for c in [&mut a, &mut b] { + let snap = c + .wait_snap(|s| s["players"].as_array().map(|p| p.len()).unwrap_or(0) == 2, Duration::from_secs(3)) + .await; + assert_eq!(snap["score"], json!([0, 0])); + } + + // 冻结 3 秒后开打 + let live = a + .wait_snap(|s| s["phase"] == "live", Duration::from_secs(6)) + .await; + assert_eq!(live["phase"], "live"); + assert!(live["leftMs"].as_u64().unwrap() > 90_000); + + // 一直按住 W:位置应该真的变了 + let start_pos = pos_of(&live, 0).unwrap(); + let yaw = live["players"][0]["yaw"].as_f64().unwrap(); + for i in 0..50u32 { + a.input(i, 1, yaw as f32).await; + tokio::time::sleep(Duration::from_millis(16)).await; + } + let moved = a + .wait_snap( + |s| { + pos_of(s, 0) + .map(|p| { + let dx = p[0] - start_pos[0]; + let dz = p[2] - start_pos[2]; + (dx * dx + dz * dz).sqrt() > 0.8 + }) + .unwrap_or(false) + }, + Duration::from_secs(3), + ) + .await; + let p = pos_of(&moved, 0).unwrap(); + assert!(p[2] != start_pos[2] || p[0] != start_pos[0]); +} + +#[tokio::test] +async fn 观战者能看不能打() { + let addr = start().await; + let mut a = Client::connect(&addr).await; + a.send(json!({ "t": "create" })).await; + let code = a.wait_for("welcome", Duration::from_secs(3)).await["code"] + .as_str() + .unwrap() + .to_string(); + + let mut spec = Client::connect(&addr).await; + spec.send(json!({ "t": "join", "code": code, "spectate": true })) + .await; + let w = spec.wait_for("welcome", Duration::from_secs(3)).await; + assert_eq!(w["you"], Value::Null); + assert_eq!(w["spectating"], true); + + let snap = spec + .wait_snap(|s| s["spectators"].as_u64().unwrap_or(0) >= 1, Duration::from_secs(4)) + .await; + assert_eq!(snap["spectators"], 1); + + // 观战者发 input 不应影响任何玩家 + spec.input(1, 1, 0.0).await; + tokio::time::sleep(Duration::from_millis(200)).await; + let snap2 = spec.wait_for("snap", Duration::from_secs(3)).await; + assert_eq!(snap2["players"].as_array().unwrap().len(), 1); +} + +#[tokio::test] +async fn 机器人会出家门() { + let addr = start().await; + let mut a = Client::connect(&addr).await; + a.send(json!({ "t": "create" })).await; + a.wait_for("welcome", Duration::from_secs(3)).await; + a.send(json!({ "t": "addBot" })).await; + + let snap = a + .wait_snap(|s| s["players"].as_array().map(|p| p.len()).unwrap_or(0) == 2, Duration::from_secs(3)) + .await; + let bot = snap["players"] + .as_array() + .unwrap() + .iter() + .find(|p| p["bot"] == true) + .expect("应该有机器人"); + assert_eq!(bot["slot"], 1); + + a.wait_snap(|s| s["phase"] == "live", Duration::from_secs(6)) + .await; + let start = pos_of(&snap, 1).unwrap(); + let later = a + .wait_snap( + |s| { + pos_of(s, 1) + .map(|p| { + let dx = p[0] - start[0]; + let dz = p[2] - start[2]; + (dx * dx + dz * dz).sqrt() > 3.0 + }) + .unwrap_or(false) + }, + Duration::from_secs(12), + ) + .await; + let p = pos_of(&later, 1).unwrap(); + assert!((p[0] - start[0]).abs() + (p[2] - start[2]).abs() > 3.0); +} + +#[tokio::test] +async fn 狂发输入不会瞬移() { + let addr = start().await; + let mut a = Client::connect(&addr).await; + a.send(json!({ "t": "create" })).await; + a.wait_for("welcome", Duration::from_secs(3)).await; + a.send(json!({ "t": "addBot" })).await; + let live = a + .wait_snap(|s| s["phase"] == "live", Duration::from_secs(6)) + .await; + let start = pos_of(&live, 0).unwrap(); + let yaw = live["players"][0]["yaw"].as_f64().unwrap(); + + // 一口气灌 200 帧前进 + for i in 0..200u32 { + a.input(i, 1, yaw as f32).await; + } + tokio::time::sleep(Duration::from_millis(400)).await; + let snap = a.wait_for("snap", Duration::from_secs(3)).await; + let p = pos_of(&snap, 0).unwrap(); + let dist = ((p[0] - start[0]).powi(2) + (p[2] - start[2]).powi(2)).sqrt(); + assert!(dist < 3.0, "400ms 跑了 {dist} 米,明显不对劲"); +} + +#[tokio::test] +async fn 未知房号会报错() { + let addr = start().await; + let mut a = Client::connect(&addr).await; + a.send(json!({ "t": "join", "code": "ZZZZ" })).await; + let msg = a.wait_for("err", Duration::from_secs(3)).await; + assert!(msg["msg"].as_str().unwrap().contains("房间不存在")); +} + +/* ------------------------------- HTTP 部分 ------------------------------- */ + +async fn http_get(addr: &str, path: &str) -> (u16, String, String) { + let mut stream = TcpStream::connect(addr).await.unwrap(); + let req = format!("GET {path} HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n"); + stream.write_all(req.as_bytes()).await.unwrap(); + let mut buf = Vec::new(); + stream.read_to_end(&mut buf).await.unwrap(); + let text = String::from_utf8_lossy(&buf).to_string(); + let (head, body) = text.split_once("\r\n\r\n").unwrap_or((&text, "")); + let status = head + .lines() + .next() + .and_then(|l| l.split_whitespace().nth(1)) + .and_then(|s| s.parse().ok()) + .unwrap_or(0); + (status, head.to_lowercase(), body.to_string()) +} + +#[tokio::test] +async fn 静态资源与健康检查都在() { + let addr = start().await; + let (status, head, body) = http_get(&addr, "/health").await; + assert_eq!(status, 200); + assert!(head.contains("application/json")); + let v: Value = serde_json::from_str(&body).unwrap(); + assert_eq!(v["ok"], true); + assert_eq!(v["engine"], "rust"); + assert_eq!(v["tick"], 60); + assert_eq!(v["snapshot"], 30); + + let (status, head, body) = http_get(&addr, "/").await; + assert_eq!(status, 200); + assert!(head.contains("text/html")); + assert!(body.contains("枪火对决")); + + let (status, head, body) = http_get(&addr, "/level.json").await; + assert_eq!(status, 200); + assert!(head.contains("application/json")); + let level: Value = serde_json::from_str(&body).unwrap(); + assert!(level["boxes"].as_array().unwrap().len() > 40); + assert_eq!(level["spawns"].as_array().unwrap().len(), 2); + + // 地图数据前后端同源,服务端启动时会解析它 + let lv = cs::level::Level::embedded(); + assert!(lv.blocks.len() > 40); + + let (status, head, _) = http_get(&addr, "/js/client/renderer.js").await; + assert_eq!(status, 200); + assert!(head.contains("javascript")); + + let (status, _, _) = http_get(&addr, "/nope.js").await; + assert_eq!(status, 200, "未知路径回退到首页"); +} diff --git a/tools/gen_level.py b/tools/gen_level.py new file mode 100644 index 0000000..2b2bff6 --- /dev/null +++ b/tools/gen_level.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +"""生成 public/level.json —— 1v1 对枪地图「沙漠据点」。 + +地图只描述 x<=0、z<=0 的四分之一,然后按 mirror 标记做镜像: + none 不镜像(跨中轴 / 自身对称的方块) + x x -> -x + z z -> -z + xz 两个方向都镜像(四份) +这样地图天然左右 + 前后对称,两边出生点绝对公平。 + +改完跑:python3 tools/gen_level.py +""" + +import json +import os + +# (x0, y0, z0, x1, y1, z1, 材质, 镜像) +# 材质: 0 混凝土 / 1 木箱 / 2 金属 / 3 地砖 +HALF = [ + # 地面与外墙 + (-24, -0.6, -24, 24, 0.0, 24, 3, "none"), + (-24, 0.0, -24, -23, 5.2, 24, 0, "x"), + (-24, 0.0, -24, 24, 5.2, -23, 0, "z"), + + # 中央高台 + 台上的木箱 + (-4.2, 0.0, -4.2, 4.2, 2.0, 4.2, 0, "none"), + (-1.4, 2.0, -1.4, 1.4, 3.2, 1.4, 1, "none"), + # 高台两侧台阶(能走上去) + (-4.2, 0.0, -6.3, 4.2, 0.65, -5.2, 1, "z"), + (-4.2, 0.0, -5.2, 4.2, 1.30, -4.2, 1, "z"), + + # 出生点附近的掩体(四角各一份) + (-22.2, 0.0, -21.6, -21.2, 3.0, -15.4, 0, "xz"), + (-17.4, 0.0, -21.8, -15.2, 1.1, -19.6, 1, "xz"), + (-21.4, 0.0, -13.4, -18.6, 2.4, -10.6, 2, "xz"), + (-13.2, 0.0, -21.8, -10.4, 0.9, -20.0, 0, "xz"), + + # 西北角的 U 形小屋(开口朝中心) + (-14.2, 0.0, -14.4, -13.2, 3.6, -8.0, 0, "xz"), + (-13.2, 0.0, -14.4, -8.0, 3.6, -13.4, 0, "xz"), + (-11.8, 0.0, -13.4, -8.0, 3.6, -12.6, 0, "xz"), + (-12.4, 0.0, -11.6, -10.4, 1.4, -9.6, 1, "xz"), + (-8.0, 2.6, -13.4, -7.2, 3.0, -12.6, 1, "xz"), # 门楣 + + # 中场:低木墙、立柱、木箱堆、沙袋 + (-8.2, 0.0, -10.2, -2.4, 1.1, -9.2, 1, "xz"), + (-6.6, 0.0, -5.4, -5.6, 5.0, -4.4, 2, "xz"), + (-12.6, 0.0, -4.6, -11.0, 2.0, -3.0, 1, "xz"), + (-6.4, 0.0, -6.4, -2.6, 0.9, -5.5, 0, "xz"), + (-9.8, 0.0, -1.9, -8.2, 1.5, -0.4, 1, "xz"), + + # 沿墙矮平台(一跳就能上) + (-23.0, 0.0, -23.0, -8.4, 1.0, -21.2, 2, "xz"), + # 平台到地面的踏步 + (-11.0, 0.0, -21.2, -9.6, 0.5, -20.2, 2, "xz"), +] + +SPAWNS = [ + {"pos": [-18.5, 0.0, -18.5], "yaw": 135.0}, + {"pos": [18.5, 0.0, 18.5], "yaw": -45.0}, +] + + +def mirror(box): + x0, y0, z0, x1, y1, z1, mat, mode = box + out = [(x0, y0, z0, x1, y1, z1)] + if "x" in mode: + out += [(-x1, y0, z0, -x0, y1, z1)] + if "z" in mode: + out += [(x0, y0, -z1, x1, y1, -z0) for (x0, y0, z0, x1, y1, z1) in out] + return [(b, mat) for b in out] + + +def r(v): + return round(v, 3) + + +def main(): + boxes = [] + for half in HALF: + for (b, mat) in mirror(half): + boxes.append({ + "min": [r(b[0]), r(b[1]), r(b[2])], + "max": [r(b[3]), r(b[4]), r(b[5])], + "mat": mat, + }) + + # 出生点别被挡住 + for sp in SPAWNS: + px, _, pz = sp["pos"] + for b in boxes: + if (b["min"][0] - 0.45 < px < b["max"][0] + 0.45 + and b["min"][2] - 0.45 < pz < b["max"][2] + 0.45 + and b["max"][1] > 0.2): + raise SystemExit(f"出生点 {px},{pz} 被 {b} 挡住") + + data = { + "name": "沙漠据点", + "size": 48, + "spawns": SPAWNS, + "boxes": boxes, + } + path = os.path.join(os.path.dirname(__file__), "..", "public", "level.json") + with open(path, "w", encoding="utf-8") as f: + json.dump(data, f, ensure_ascii=False, separators=(",", ":")) + f.write("\n") + print(f"写出 {path}:{len(boxes)} 个方块 / {len(SPAWNS)} 个出生点") + + +if __name__ == "__main__": + main() diff --git a/tools/verify.cjs b/tools/verify.cjs new file mode 100644 index 0000000..203b775 --- /dev/null +++ b/tools/verify.cjs @@ -0,0 +1,59 @@ +// 本地验证:用系统 Chrome 无头打开页面,截图 + 打印控制台错误 + 游戏状态 +const puppeteer = require("puppeteer-core"); + +(async () => { + const url = process.argv[2] || "http://localhost:3210/"; + const out = process.argv[3] || "/tmp/cs-shot.png"; + const wait = Number(process.argv[4] || 6000); + const browser = await puppeteer.launch({ + executablePath: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", + headless: "new", + args: [ + "--no-sandbox", + "--enable-unsafe-swiftshader", + "--use-gl=angle", + "--use-angle=swiftshader", + "--disable-dev-shm-usage", + "--window-size=1280,760", + ], + defaultViewport: { width: 1280, height: 720 }, + }); + const page = await browser.newPage(); + const logs = []; + page.on("console", (m) => logs.push(`[${m.type()}] ${m.text()}`)); + page.on("pageerror", (e) => logs.push(`[pageerror] ${e.message}`)); + page.on("requestfailed", (r) => logs.push(`[reqfail] ${r.url()} ${r.failure() && r.failure().errorText}`)); + await page.goto(url, { waitUntil: "networkidle2" }); + await new Promise((r) => setTimeout(r, wait)); + await page.screenshot({ path: out }); + const info = await page.evaluate(() => { + const S = window.__CS; + if (!S) return { ok: false, why: "no __CS" }; + const r = { + scene: S.scene, + phase: S.phase, + you: S.you, + code: S.code, + spectating: S.spectating, + players: S.players.map((p) => ({ + slot: p.slot, + name: p.name, + hp: p.hp, + alive: p.alive, + pos: p.pos.map((v) => +v.toFixed(2)), + })), + score: S.score, + hp: S.hp, + mag: S.mag, + alive: S.alive, + fps: S.fps, + pos: S.body ? S.body.pos : null, + particles: S.particles.length, + canvas: [document.getElementById("gl").width, document.getElementById("gl").height], + }; + return r; + }); + console.log(JSON.stringify(info, null, 2)); + if (logs.length) console.log("--- console ---\n" + logs.join("\n")); + await browser.close(); +})();