diff --git a/README.md b/README.md index fc9fd5d..861b27d 100644 --- a/README.md +++ b/README.md @@ -50,9 +50,9 @@ make test - `--smoke-test `: Render `` frames and exit cleanly (for automated verification). ## Default controls -- **Player 1 (keyboard):** `W/S` or `Up/Down` (throttle/brake), `A/D` or `Left/Right` (steer), `Left Shift` (boost), `Space` (minigun), `E` (missile), `Q` (auto-pilot), `C` (camera view), `Esc`/`P` (pause). -- **Player 2 (split-screen):** `Arrow keys` (steer/throttle/brake), `Right Shift` (boost), `Right Ctrl` (minigun), `Enter` (missile). -- **Gamepad:** Left stick / D-pad (steer), `RT`/`A` (throttle), `LT`/`B` (brake), `LB`/`X` (boost), `RB` (minigun), `Y` (missile), `Start` (pause). +- **Player 1 (keyboard):** `W/S` or `Up/Down` (throttle/brake), `A/D` or `Left/Right` (steer), `Left Shift` (boost), `Space` (minigun), `E` (missile), `Q` (auto-pilot), `R` (recover to track), `C` (camera view), `H` (HUD toggle), `Esc`/`P` (pause). +- **Player 2 (split-screen):** `Arrow keys` (steer/throttle/brake), `Right Shift` (boost), `Right Ctrl` (minigun), `Enter` (missile), `Backspace` (recover to track). +- **Gamepad:** Left stick / D-pad (steer), `RT`/`A` (throttle), `LT`/`B` (brake), `LB`/`X` (boost), `RB` (minigun), `Y` (missile), `Back`/`Select` (recover to track), `Start` (pause). - **Hotkeys:** `F2` (toggle classic mode), `F4` (switch OPL3 / SoundFont music), `F11` or `Alt+Enter` (toggle fullscreen), `1–9` / `[` `]` (switch tracks in Track Viewer). User configuration, highscores, clone ghosts, and championship saves are stored in your OS user preferences directory (`SDL_GetPrefPath`). Original files in `data/` are never modified. diff --git a/src/assets/flic.cpp b/src/assets/flic.cpp index 8733273..87fdd5a 100644 --- a/src/assets/flic.cpp +++ b/src/assets/flic.cpp @@ -25,12 +25,34 @@ inline uint32_t read_le32(const uint8_t* p) { } // namespace +void FlicPlayer::close() { + file_data_.clear(); + file_data_.shrink_to_fit(); + indexed_.clear(); + indexed_.shrink_to_fit(); + rgba_.clear(); + rgba_.shrink_to_fit(); + palette_.fill({0, 0, 0, 255}); + width_ = 320; + height_ = 200; + num_frames_ = 0; + frame_index_ = 0; + first_frame_offset_ = 0; + next_frame_offset_ = 0; + fps_ = 120.0f / 9.0f; + vga6_palette_ = false; +} + bool FlicPlayer::open(const Vfs& vfs, const std::string& path) { + close(); if (!vfs.read_file(path, file_data_)) { LOG_ERROR("Failed to read FLIC file: %s", path.c_str()); return false; } - if (file_data_.size() < 16) return false; + if (file_data_.size() < 16) { + close(); + return false; + } uint32_t hdr_len = read_le32(file_data_.data() + 0); uint16_t magic = read_le16(file_data_.data() + 4); @@ -40,27 +62,34 @@ bool FlicPlayer::open(const Vfs& vfs, const std::string& path) { height_ = read_le16(file_data_.data() + 10); } else { LOG_ERROR("Unsupported FLIC magic %04x in %s", magic, path.c_str()); + close(); return false; } - if (width_ <= 0 || height_ <= 0 || hdr_len >= file_data_.size()) { + if (width_ <= 0 || width_ > 4096 || height_ <= 0 || height_ > 4096 || + static_cast(width_) * static_cast(height_) > 4096ULL * 4096ULL || + hdr_len >= file_data_.size()) { + close(); return false; } // Standard FLC uses 128B header; Bullfrog INTRO.DAT uses a 12-byte compact header followed immediately by 0xF1FA! size_t first_off = hdr_len; - if (first_off + 6 <= file_data_.size() && read_le16(file_data_.data() + first_off + 4) != 0xF1FA) { + if (file_data_.size() - first_off >= 6u && read_le16(file_data_.data() + first_off + 4) != 0xF1FA) { // Fallback scan for first 0xF1FA chunk header first_off = 128; - for (size_t i = hdr_len; i + 6 <= std::min(file_data_.size(), 256); ++i) { + size_t limit = std::min(file_data_.size(), 256); + for (size_t i = hdr_len; limit >= 6u && i <= limit - 6u; ++i) { if (read_le16(file_data_.data() + i + 4) == 0xF1FA) { - first_off = i - 0; // wait: magic is at chunk+4, so chunk starts at i! + first_off = i; break; } } } // Verify chunk start at first_off has 0xF1FA at +4 - if (first_off + 16 > file_data_.size() || read_le16(file_data_.data() + first_off + 4) != 0xF1FA) { + if (first_off >= file_data_.size() || file_data_.size() - first_off < 16u || + read_le16(file_data_.data() + first_off + 4) != 0xF1FA) { LOG_ERROR("Could not locate first 0xF1FA FLC frame chunk in %s", path.c_str()); + close(); return false; } @@ -74,6 +103,7 @@ bool FlicPlayer::open(const Vfs& vfs, const std::string& path) { } else { fps_ = 15.0f; } + fps_ = std::clamp(fps_, 1.0f, 120.0f); palette_.fill({0, 0, 0, 255}); indexed_.assign(static_cast(width_) * height_, 0); @@ -117,22 +147,23 @@ bool FlicPlayer::decode_chunk_frame(size_t offset) { const size_t total = file_data_.size(); // Advance past optional prefix/non-frame chunks if any - while (offset + 16 <= total) { - uint32_t fsize = read_le32(base + offset); + while (offset <= total && total - offset >= 16u) { + size_t fsize = static_cast(read_le32(base + offset)); uint16_t ftype = read_le16(base + offset + 4); - if (fsize < 6 || offset + fsize > total) { + if (fsize < 6u || fsize > total - offset) { return false; } if (ftype == 0xF1FA) { + if (fsize < 16u) return false; uint16_t chunks = read_le16(base + offset + 6); - size_t pos = offset + 16; + size_t pos = offset + 16u; size_t frame_end = offset + fsize; - for (uint16_t c = 0; c < chunks && pos + 6 <= frame_end; ++c) { - uint32_t csize = read_le32(base + pos); + for (uint16_t c = 0; c < chunks && frame_end - pos >= 6u; ++c) { + size_t csize = static_cast(read_le32(base + pos)); uint16_t ctype = read_le16(base + pos + 4); const uint8_t* cd = base + pos + 6; - size_t cdata_len = (csize >= 6 && pos + csize <= frame_end) ? (csize - 6) : 0; + size_t cdata_len = (csize >= 6u && csize <= frame_end - pos) ? (csize - 6u) : 0; switch (ctype) { case 4: // FLI_COLOUR256 (0..255 8-bit RGB) @@ -181,12 +212,17 @@ bool FlicPlayer::decode_chunk_frame(size_t offset) { if (cp >= cdata_len) break; uint8_t val = cd[cp++]; for (int k = 0; k < cnt && x < width_; ++k, ++x) { - indexed_[static_cast(y) * width_ + x] = val; + if (x >= 0) { + indexed_[static_cast(y) * width_ + static_cast(x)] = val; + } } } else if (cnt < 0) { int run = -cnt; for (int k = 0; k < run && x < width_ && cp < cdata_len; ++k, ++x) { - indexed_[static_cast(y) * width_ + x] = cd[cp++]; + if (x >= 0) { + indexed_[static_cast(y) * width_ + static_cast(x)] = cd[cp]; + } + ++cp; } } } @@ -198,23 +234,28 @@ bool FlicPlayer::decode_chunk_frame(size_t offset) { int y = read_le16(cd + 0); int lines = read_le16(cd + 2); size_t cp = 4; - for (int l = 0; l < lines && y < height_ && cp < cdata_len; ++l, ++y) { + for (int l = 0; l < lines && y >= 0 && y < height_ && cp < cdata_len; ++l, ++y) { uint8_t packets = cd[cp++]; int x = 0; for (uint8_t pk = 0; pk < packets && cp < cdata_len; ++pk) { - x += cd[cp++]; + x = std::min(width_, x + cd[cp++]); if (cp >= cdata_len) break; int8_t cnt = static_cast(cd[cp++]); if (cnt > 0) { for (int k = 0; k < cnt && x < width_ && cp < cdata_len; ++k, ++x) { - indexed_[static_cast(y) * width_ + x] = cd[cp++]; + if (x >= 0) { + indexed_[static_cast(y) * width_ + static_cast(x)] = cd[cp]; + } + ++cp; } } else if (cnt < 0) { if (cp >= cdata_len) break; uint8_t val = cd[cp++]; int run = -cnt; for (int k = 0; k < run && x < width_; ++k, ++x) { - indexed_[static_cast(y) * width_ + x] = val; + if (x >= 0) { + indexed_[static_cast(y) * width_ + static_cast(x)] = val; + } } } } @@ -227,38 +268,38 @@ bool FlicPlayer::decode_chunk_frame(size_t offset) { int lines = read_le16(cd); size_t cp = 2; int y = 0; - for (int l = 0; l < lines && y < height_ && cp + 2 <= cdata_len;) { + for (int l = 0; l < lines && y >= 0 && y < height_ && cdata_len - cp >= 2u;) { int16_t word = read_le16s(cd + cp); cp += 2; if ((word & 0xC000) == 0xC000) { - y += -word; + y = std::min(height_, y + static_cast(-static_cast(word))); } else if ((word & 0xC000) == 0x4000) { // odd last byte + packets uint8_t last_b = static_cast(word & 0xFF); - if (width_ > 0) { + if (width_ > 0 && y < height_) { indexed_[static_cast(y) * width_ + (width_ - 1)] = last_b; } } else { uint16_t packets = static_cast(word); int x = 0; - for (uint16_t pk = 0; pk < packets && cp + 2 <= cdata_len; ++pk) { - x += cd[cp++]; + for (uint16_t pk = 0; pk < packets && cdata_len - cp >= 2u; ++pk) { + x = std::min(width_, x + cd[cp++]); int8_t cnt = static_cast(cd[cp++]); if (cnt > 0) { - for (int k = 0; k < cnt && cp + 2 <= cdata_len; ++k) { + for (int k = 0; k < cnt && cdata_len - cp >= 2u; ++k) { uint8_t b0 = cd[cp++], b1 = cd[cp++]; - if (x < width_) indexed_[static_cast(y) * width_ + x] = b0; - if (x + 1 < width_) indexed_[static_cast(y) * width_ + x + 1] = b1; - x += 2; + if (x >= 0 && x < width_) indexed_[static_cast(y) * width_ + x] = b0; + if (x + 1 >= 0 && x + 1 < width_) indexed_[static_cast(y) * width_ + x + 1] = b1; + x = std::min(width_, x + 2); } } else if (cnt < 0) { - if (cp + 2 > cdata_len) break; + if (cdata_len - cp < 2u) break; uint8_t b0 = cd[cp++], b1 = cd[cp++]; int run = -cnt; - for (int k = 0; k < run; ++k) { - if (x < width_) indexed_[static_cast(y) * width_ + x] = b0; - if (x + 1 < width_) indexed_[static_cast(y) * width_ + x + 1] = b1; - x += 2; + for (int k = 0; k < run && x < width_; ++k) { + if (x >= 0 && x < width_) indexed_[static_cast(y) * width_ + x] = b0; + if (x + 1 >= 0 && x + 1 < width_) indexed_[static_cast(y) * width_ + x + 1] = b1; + x = std::min(width_, x + 2); } } } @@ -272,7 +313,9 @@ bool FlicPlayer::decode_chunk_frame(size_t offset) { default: break; } - pos += std::max(csize, 6); + size_t adv = std::max(csize, 6u); + if (adv > frame_end - pos) break; + pos += adv; } next_frame_offset_ = offset + fsize; return true; diff --git a/src/assets/flic.hpp b/src/assets/flic.hpp index 5e25137..00c0be3 100644 --- a/src/assets/flic.hpp +++ b/src/assets/flic.hpp @@ -13,6 +13,7 @@ namespace top_octane::assets { class FlicPlayer { public: bool open(const Vfs& vfs, const std::string& path = "DATA/INTRO.DAT"); + void close(); void reset(); bool step_frame(); // Decodes next frame into current_rgba; returns false at EOF diff --git a/src/assets/level.cpp b/src/assets/level.cpp index a54b90a..8c34d36 100644 --- a/src/assets/level.cpp +++ b/src/assets/level.cpp @@ -212,23 +212,31 @@ bool LevelData::load(const Vfs& vfs, int level_num) { checkpoints.push_back(gate); } - // 6. Extract main closed racing waypoint circuit (type == 9 && subtype != 0 cycle) + // 6. Extract main closed racing waypoint circuit (type == 9 && subtype != 0 cycle) in O(W) main_waypoints.clear(); std::vector best_cycle; - for (const auto& [id, ent] : wp_map) { - if (ent.subtype == 0) continue; + { + std::array visit_state{}; // 0=unvisited, 1=visiting, 2=done + std::array path_pos{}; std::vector path; - std::unordered_map seen_pos; - uint16_t cur = id; - while (wp_map.count(cur) && !seen_pos.count(cur)) { - seen_pos[cur] = path.size(); - path.push_back(cur); - cur = wp_map[cur].next_id; - } - if (seen_pos.count(cur)) { - std::vector cyc(path.begin() + static_cast(seen_pos[cur]), path.end()); - if (cyc.size() > best_cycle.size()) { - best_cycle = std::move(cyc); + for (const auto& [id, ent] : wp_map) { + if (ent.subtype == 0 || visit_state[id] == 2) continue; + path.clear(); + uint16_t cur = id; + while (cur < kMaxEntities && entity_slots[cur].type == 9 && visit_state[cur] == 0) { + path_pos[cur] = path.size(); + visit_state[cur] = 1; + path.push_back(cur); + cur = entity_slots[cur].next_id; + } + if (cur < kMaxEntities && entity_slots[cur].type == 9 && visit_state[cur] == 1) { + std::vector cyc(path.begin() + static_cast(path_pos[cur]), path.end()); + if (cyc.size() > best_cycle.size()) { + best_cycle = std::move(cyc); + } + } + for (uint16_t node_id : path) { + visit_state[node_id] = 2; } } } @@ -369,12 +377,16 @@ bool LevelData::load(const Vfs& vfs, int level_num) { } const MapEntry& LevelData::cell(int x, int z) const { + static const MapEntry kEmptyEntry{}; + if (map.empty()) return kEmptyEntry; x = std::clamp(x, 0, kMapWidth - 1); z = std::clamp(z, 0, kMapHeight - 1); return map[static_cast(z) * kMapWidth + x]; } MapEntry& LevelData::cell_mut(int x, int z) { + static MapEntry kDummyEntry{}; + if (map.empty()) return kDummyEntry; x = std::clamp(x, 0, kMapWidth - 1); z = std::clamp(z, 0, kMapHeight - 1); return map[static_cast(z) * kMapWidth + x]; @@ -385,6 +397,7 @@ float LevelData::cell_height_world(int x, int z) const { } float LevelData::sample_height_world(float wx, float wz) const { + if (!std::isfinite(wx) || !std::isfinite(wz)) return 0.0f; float cx = std::clamp(wx, 0.0f, static_cast(kMapWidth - 1)); float cz = std::clamp(wz, 0.0f, static_cast(kMapHeight - 1)); int x0 = std::min(static_cast(cx), kMapWidth - 2); @@ -406,6 +419,7 @@ float LevelData::sample_height_world(float wx, float wz) const { } float LevelData::sample_height_alt_diag(float wx, float wz) const { + if (!std::isfinite(wx) || !std::isfinite(wz)) return 0.0f; float cx = std::clamp(wx, 0.0f, static_cast(kMapWidth - 1)); float cz = std::clamp(wz, 0.0f, static_cast(kMapHeight - 1)); int x0 = std::min(static_cast(cx), kMapWidth - 2); @@ -425,13 +439,82 @@ float LevelData::sample_height_alt_diag(float wx, float wz) const { return h11 + (h01 - h11) * (1.0f - fx) + (h10 - h11) * (1.0f - fz); } +float LevelData::sample_entity_surface_y(float wx, float wz) const { + if (!std::isfinite(wx) || !std::isfinite(wz)) { + return 0.0f; + } + float gy = sample_height_world(wx, wz); + int x = static_cast(std::floor(wx)); + int z = static_cast(std::floor(wz)); + if (x < 0 || x >= kMapWidth || z < 0 || z >= kMapHeight) { + return gy; + } + const MapEntry& m = cell(x, z); + if (m.tex_or_col >= 0) { + return gy; + } + int col_idx = -m.tex_or_col; + if (col_idx <= 0 || col_idx >= kMaxColumns) { + return gy; + } + const ColumnDefinition& col = columns[col_idx]; + uint16_t mask = col.shape_mask; + if (mask == 0) { + return gy; + } + if ((mask & 1u) != 0) { + int s = 0; + while (s < 8 && (mask & (1u << s)) != 0) { + ++s; + } + return gy + static_cast(s); + } + if ((mask & 0xF8u) != 0) { + return gy; + } + int s0 = 1; + while (s0 < 8 && (mask & (1u << s0)) == 0) { + ++s0; + } + if (s0 >= 8) { + return gy; + } + int s1 = s0; + while (s1 < 8 && (mask & (1u << s1)) != 0) { + ++s1; + } + int16_t blk_id = col.blocks[s1 - 1]; + if (blk_id < 0 || blk_id >= kMaxBlocks) { + return gy; + } + uint8_t top_tex = blocks[blk_id].tex[4]; + bool top_is_road = (top_tex == 50 || top_tex == 30 || + (top_tex >= 100 && top_tex <= 107) || + (top_tex >= 136 && top_tex <= 155)); + if (!top_is_road) { + return gy; + } + uint16_t ft = col.floor_tex; + bool floor_is_road_or_pad = (ft >= 40 && ft <= 55) || (ft >= 76 && ft <= 79) || + (ft >= 116 && ft <= 127) || (ft >= 136 && ft <= 155); + if (ft == 0) { + return gy + static_cast(s1); + } + if (s0 == 1 && s1 == 2 && (top_tex >= 136 && top_tex <= 155) && !floor_is_road_or_pad) { + return gy + static_cast(s1); + } + return gy; +} + Vec3 LevelData::sample_normal_world(float wx, float wz) const { + if (!std::isfinite(wx) || !std::isfinite(wz)) return Vec3(0.0f, 1.0f, 0.0f); constexpr float eps = 0.25f; float hL = sample_height_world(wx - eps, wz); float hR = sample_height_world(wx + eps, wz); float hD = sample_height_world(wx, wz - eps); float hU = sample_height_world(wx, wz + eps); - return Vec3(hL - hR, 2.0f * eps, hD - hU).normalized(); + Vec3 n = Vec3(hL - hR, 2.0f * eps, hD - hU).normalized(); + return (n.len_sq() > 1e-6f) ? n : Vec3(0.0f, 1.0f, 0.0f); } bool LevelData::is_cell_solid_at_point(int x, int z, float qx, float qz, @@ -489,6 +572,11 @@ bool LevelData::is_cliff_blocking_at_y(int x, int z, float world_y) const { void LevelData::sample_surface_and_ceiling(float wx, float wz, float craft_y, float& out_floor_y, float& out_ceil_y) const { + if (!std::isfinite(wx) || !std::isfinite(wz) || !std::isfinite(craft_y)) { + out_floor_y = 0.0f; + out_ceil_y = 1e6f; + return; + } out_floor_y = sample_height_world(wx, wz); out_ceil_y = 1e6f; @@ -506,16 +594,19 @@ void LevelData::sample_surface_and_ceiling(float wx, float wz, float craft_y, return; } const ColumnDefinition& col = columns[col_idx]; - float ground_y_top = out_floor_y; - float ground_y_bot = std::min(ground_y_top, sample_height_alt_diag(wx, wz)); + float ground_y = out_floor_y; for (int s = 0; s < 8; ++s) { if ((col.shape_mask & (1u << s)) == 0) continue; - float slot_top = ground_y_top + static_cast(s) + 1.0f; - float slot_bot = ground_y_bot + static_cast(s); + float slot_bot = ground_y + static_cast(s); + float slot_top = slot_bot + 1.0f; if (slot_top <= craft_y + 0.30f) { out_floor_y = std::max(out_floor_y, slot_top); } else if (slot_bot >= craft_y - 0.10f) { out_ceil_y = std::min(out_ceil_y, slot_bot); + } else if (s == 0 || (craft_y - slot_bot) > 0.55f) { + out_floor_y = std::max(out_floor_y, slot_top); + } else { + out_ceil_y = std::min(out_ceil_y, slot_bot); } } } diff --git a/src/assets/level.hpp b/src/assets/level.hpp index cd328ac..7221686 100644 --- a/src/assets/level.hpp +++ b/src/assets/level.hpp @@ -151,6 +151,7 @@ struct LevelData { float cell_height_world(int x, int z) const; float sample_height_world(float wx, float wz) const; float sample_height_alt_diag(float wx, float wz) const; + float sample_entity_surface_y(float wx, float wz) const; Vec3 sample_normal_world(float wx, float wz) const; bool is_cell_solid_at_point(int x, int z, float qx, float qz, float world_y, float craft_height = 0.42f) const; diff --git a/src/assets/model.cpp b/src/assets/model.cpp index d768158..1b82632 100644 --- a/src/assets/model.cpp +++ b/src/assets/model.cpp @@ -28,6 +28,11 @@ inline uint32_t read_le32(const uint8_t* p) { bool ObjectTextureAtlas::load(const Vfs& vfs, const Palette& pal, const std::string& dat_path, const std::string& tab_path) { + width = 256; + height = 0; + rgba.clear(); + entries.clear(); + std::vector raw_dat, dat, raw_tab, tab; if (!vfs.read_file(dat_path, raw_dat) || !rnc_unpack(raw_dat, dat)) { LOG_ERROR("Failed to read object texture atlas: %s", dat_path.c_str()); @@ -38,14 +43,13 @@ bool ObjectTextureAtlas::load(const Vfs& vfs, const Palette& pal, return false; } - width = 256; - if (dat.size() % width != 0 || dat.empty()) { + if (dat.size() % width != 0 || dat.empty() || dat.size() / width > 8192u) { LOG_ERROR("Invalid object texture atlas size: %zu", dat.size()); return false; } height = static_cast(dat.size() / width); - rgba.resize(dat.size() * 4); + rgba.resize(dat.size() * 4u); for (size_t i = 0; i < dat.size(); ++i) { uint8_t cidx = dat[i]; const Rgba8& c = pal.colors[cidx]; @@ -55,11 +59,10 @@ bool ObjectTextureAtlas::load(const Vfs& vfs, const Palette& pal, rgba[i * 4 + 3] = (cidx == 0) ? 0 : 255; } - entries.clear(); - size_t count = tab.size() / 6; + size_t count = tab.size() / 6u; entries.reserve(count); for (size_t i = 0; i < count; ++i) { - const uint8_t* e = tab.data() + i * 6; + const uint8_t* e = tab.data() + i * 6u; ObjectTexEntry te; te.offset = read_le32(e); te.w = e[4]; @@ -72,6 +75,10 @@ bool ObjectTextureAtlas::load(const Vfs& vfs, const Palette& pal, } bool ModelMesh::load(const Vfs& vfs, const std::string& path, const ObjectTextureAtlas* atlas) { + vertices.clear(); + triangles.clear(); + bounds_min = bounds_max = Vec3(0, 0, 0); + std::vector raw, data; if (!vfs.read_file(path, raw) || !rnc_unpack(raw, data)) { LOG_ERROR("Failed to read 3D model: %s", path.c_str()); @@ -89,7 +96,8 @@ bool ModelMesh::load(const Vfs& vfs, const std::string& path, const ObjectTextur uint16_t num_faces = read_le16(data.data() + 38); uint16_t num_verts = read_le16(data.data() + 40); - if (58ull + l0 + l1 + l2 > data.size() || l1 != static_cast(num_verts) * 6u) { + size_t payload_sz = static_cast(l0) + static_cast(l1) + static_cast(l2); + if (payload_sz > data.size() - 58u || l1 != static_cast(num_verts) * 6u) { LOG_ERROR("Invalid chunk sizes in %s (l0=%u l1=%u l2=%u verts=%u)", path.c_str(), l0, l1, l2, num_verts); return false; @@ -128,12 +136,15 @@ bool ModelMesh::load(const Vfs& vfs, const std::string& path, const ObjectTextur triangles.clear(); triangles.reserve(num_faces); - uint32_t pos = 0; - while (pos < l0) { + size_t pos = 0; + const size_t l0_sz = static_cast(l0); + while (pos < l0_sz) { uint8_t op = c0[pos]; if (op == 5) { - if (pos + 12 > l0) { + if (l0_sz - pos < 12u) { LOG_ERROR("Truncated op5 face in %s", path.c_str()); + vertices.clear(); + triangles.clear(); return false; } ModelTriangle tri; @@ -146,30 +157,37 @@ bool ModelMesh::load(const Vfs& vfs, const std::string& path, const ObjectTextur for (int k = 0; k < 3; ++k) { if (tri.v[k] >= num_verts) { LOG_ERROR("Vertex index OOB in %s", path.c_str()); + vertices.clear(); + triangles.clear(); return false; } uint8_t px_u = c0[pos + 6 + k * 2 + 0]; uint8_t px_v = c0[pos + 6 + k * 2 + 1]; - if (atlas && tri.tex_id < atlas->entries.size()) { + if (atlas && tri.tex_id < atlas->entries.size() && + atlas->width > 0 && atlas->height > 0) { const ObjectTexEntry& te = atlas->entries[tri.tex_id]; if (px_u > te.w || px_v > te.h) { LOG_WARN("UV out of entry bounds in %s (tex=%u uv=%u,%u wh=%u,%u)", path.c_str(), tri.tex_id, px_u, px_v, te.w, te.h); } - tri.u[k] = (static_cast(te.x) + static_cast(px_u)) / + int clamped_u = std::clamp(px_u, 0, std::max(0, static_cast(te.w) - 1)); + int clamped_v = std::clamp(px_v, 0, std::max(0, static_cast(te.h) - 1)); + tri.u[k] = (static_cast(te.x) + static_cast(clamped_u) + 0.5f) / static_cast(atlas->width); - tri.v_coord[k] = (static_cast(te.y) + static_cast(px_v)) / + tri.v_coord[k] = (static_cast(te.y) + static_cast(clamped_v) + 0.5f) / static_cast(atlas->height); } else { - tri.u[k] = static_cast(px_u) / 256.0f; - tri.v_coord[k] = static_cast(px_v) / 256.0f; + tri.u[k] = (static_cast(px_u) + 0.5f) / 256.0f; + tri.v_coord[k] = (static_cast(px_v) + 0.5f) / 256.0f; } } triangles.push_back(tri); - pos += 12; + pos += 12u; } else if (op == 4) { - if (pos + 6 > l0) { + if (l0_sz - pos < 6u) { LOG_ERROR("Truncated op4 face in %s", path.c_str()); + vertices.clear(); + triangles.clear(); return false; } ModelTriangle tri; @@ -182,13 +200,17 @@ bool ModelMesh::load(const Vfs& vfs, const std::string& path, const ObjectTextur for (int k = 0; k < 3; ++k) { if (tri.v[k] >= num_verts) { LOG_ERROR("Vertex index OOB in %s", path.c_str()); + vertices.clear(); + triangles.clear(); return false; } } triangles.push_back(tri); - pos += 6; + pos += 6u; } else { - LOG_ERROR("Unknown model face opcode %u at %u in %s", op, pos, path.c_str()); + LOG_ERROR("Unknown model face opcode %u at %zu in %s", op, pos, path.c_str()); + vertices.clear(); + triangles.clear(); return false; } } @@ -196,6 +218,8 @@ bool ModelMesh::load(const Vfs& vfs, const std::string& path, const ObjectTextur if (triangles.size() != num_faces) { LOG_ERROR("Face count mismatch in %s: parsed %zu expected %u", path.c_str(), triangles.size(), num_faces); + vertices.clear(); + triangles.clear(); return false; } return true; diff --git a/src/assets/music_bank.cpp b/src/assets/music_bank.cpp index 809243e..957c35b 100644 --- a/src/assets/music_bank.cpp +++ b/src/assets/music_bank.cpp @@ -60,26 +60,28 @@ bool starts_with_icase(const std::string& s, const std::string& prefix) { } // namespace bool MusicArchive::load(const Vfs& vfs, const std::string& path) { + for (auto& bvec : banks) bvec.clear(); std::vector raw; if (!vfs.read_file(path, raw) || raw.size() < 80) { LOG_ERROR("Failed to read music archive: %s", path.c_str()); return false; } - uint32_t fat_off = read_le32(raw.data() + raw.size() - 4); - if (fat_off + 8 + 4 * 16 > raw.size()) { - LOG_ERROR("Invalid MUSIC.DAT FAT offset: %u", fat_off); + size_t fat_off = static_cast(read_le32(raw.data() + raw.size() - 4)); + if (fat_off > raw.size() || raw.size() - fat_off < 8u + 4u * 16u) { + LOG_ERROR("Invalid MUSIC.DAT FAT offset: %zu", fat_off); return false; } for (int b = 0; b < 4; ++b) { - size_t bo = static_cast(fat_off) + 8u + static_cast(b) * 16u; - uint32_t off_fat = read_le32(raw.data() + bo + 0); - uint32_t off_data = read_le32(raw.data() + bo + 4); - uint32_t len_fat = read_le32(raw.data() + bo + 8); - uint32_t len_data = read_le32(raw.data() + bo + 12); + size_t bo = fat_off + 8u + static_cast(b) * 16u; + size_t off_fat = static_cast(read_le32(raw.data() + bo + 0)); + size_t off_data = static_cast(read_le32(raw.data() + bo + 4)); + size_t len_fat = static_cast(read_le32(raw.data() + bo + 8)); + size_t len_data = static_cast(read_le32(raw.data() + bo + 12)); - if (off_fat + len_fat > raw.size() || off_data + len_data > raw.size()) { + if (off_fat > raw.size() || len_fat > raw.size() - off_fat || + off_data > raw.size() || len_data > raw.size() - off_data) { LOG_ERROR("Out-of-bounds bank %d in MUSIC.DAT", b); return false; } @@ -90,10 +92,10 @@ bool MusicArchive::load(const Vfs& vfs, const std::string& path) { const uint8_t* ent = raw.data() + off_fat + i * 32u; char name_buf[19]{}; std::memcpy(name_buf, ent, 18); - uint32_t s_off = read_le32(ent + 18); - uint32_t s_sz = read_le32(ent + 26); + size_t s_off = static_cast(read_le32(ent + 18)); + size_t s_sz = static_cast(read_le32(ent + 26)); - if (s_off + s_sz > len_data) { + if (s_off > len_data || s_sz > len_data - s_off) { LOG_ERROR("Truncated track %s in MUSIC.DAT bank %d", name_buf, b); return false; } @@ -127,27 +129,28 @@ bool parse_xmi_sequence(const uint8_t* data, size_t size, const std::string& nam const uint8_t* evnt_ptr = nullptr; uint32_t evnt_sz = 0; - for (size_t i = 0; i + 8 <= size;) { + for (size_t i = 0; i + 8u <= size;) { const uint8_t* id = data + i; - uint32_t csz = read_be32(data + i + 4); + size_t csz = static_cast(read_be32(data + i + 4)); if (std::memcmp(id, "FORM", 4) == 0 || std::memcmp(id, "CAT ", 4) == 0) { // Enter container header (id + size + 4-byte formType) - if (i + 12 <= size) { - i += 12; + if (size - i >= 12u) { + i += 12u; continue; } break; } - if (std::memcmp(id, "TIMB", 4) == 0 && i + 8 + csz <= size) { + size_t rem = size - i - 8u; + if (std::memcmp(id, "TIMB", 4) == 0 && csz <= rem) { timb_ptr = data + i + 8; - timb_sz = csz; - } else if (std::memcmp(id, "EVNT", 4) == 0 && i + 8 + csz <= size) { + timb_sz = static_cast(csz); + } else if (std::memcmp(id, "EVNT", 4) == 0 && csz <= rem) { evnt_ptr = data + i + 8; - evnt_sz = csz; + evnt_sz = static_cast(csz); break; } size_t adv = 8u + csz + (csz & 1u); - if (adv == 0 || i + adv > size) break; + if (csz > rem || adv > size - i) break; i += adv; } @@ -247,8 +250,8 @@ bool OplTimbreBank::load(const Vfs& vfs, const std::string& path) { uint8_t patch = data[pos]; uint8_t bank = data[pos + 1]; if (patch == 0xFFu && bank == 0xFFu) break; - uint32_t off = read_le32(data.data() + pos + 2); - if (off + 14 <= data.size()) { + size_t off = static_cast(read_le32(data.data() + pos + 2)); + if (off <= data.size() && data.size() - off >= 14u) { OplPatch p; p.patch = patch; p.bank = bank; @@ -288,26 +291,6 @@ bool SoundFontBank::load_from_bytes(const uint8_t* data, size_t size) { presets.clear(); is_sf2 = false; - auto find_subchunk = [&](const char* tag, const uint8_t*& ptr, uint32_t& sz) -> bool { - for (size_t pos = 12; pos + 8 <= size;) { - const uint8_t* cid = data + pos; - uint32_t csz = read_le32(data + pos + 4); - if (std::memcmp(cid, "LIST", 4) == 0) { - pos += 12; - continue; - } - if (std::memcmp(cid, tag, 4) == 0 && pos + 8 + csz <= size) { - ptr = data + pos + 8; - sz = csz; - return true; - } - size_t adv = 8u + csz + (csz & 1u); - if (adv == 0 || pos + adv > size) break; - pos += adv; - } - return false; - }; - const uint8_t *ifil_p = nullptr, *smpl_p = nullptr, *snam_p = nullptr; const uint8_t *phdr_p = nullptr, *pbag_p = nullptr, *pgen_p = nullptr; const uint8_t *inst_p = nullptr, *ibag_p = nullptr, *igen_p = nullptr, *shdr_p = nullptr; @@ -315,23 +298,47 @@ bool SoundFontBank::load_from_bytes(const uint8_t* data, size_t size) { uint32_t phdr_sz = 0, pbag_sz = 0, pgen_sz = 0; uint32_t inst_sz = 0, ibag_sz = 0, igen_sz = 0, shdr_sz = 0; - if (find_subchunk("ifil", ifil_p, ifil_sz) && ifil_sz >= 4) { + // Single-pass RIFF LIST/subchunk scanner + for (size_t pos = 12; pos + 8u <= size;) { + const uint8_t* cid = data + pos; + size_t csz = static_cast(read_le32(data + pos + 4)); + if (std::memcmp(cid, "LIST", 4) == 0) { + if (size - pos < 12u) break; + pos += 12u; + continue; + } + size_t rem = size - pos - 8u; + if (csz <= rem) { + const uint8_t* payload = data + pos + 8u; + uint32_t sz32 = static_cast(csz); + if (!ifil_p && std::memcmp(cid, "ifil", 4) == 0) { ifil_p = payload; ifil_sz = sz32; } + else if (!smpl_p && std::memcmp(cid, "smpl", 4) == 0) { smpl_p = payload; smpl_sz = sz32; } + else if (!snam_p && std::memcmp(cid, "snam", 4) == 0) { snam_p = payload; snam_sz = sz32; } + else if (!phdr_p && std::memcmp(cid, "phdr", 4) == 0) { phdr_p = payload; phdr_sz = sz32; } + else if (!pbag_p && std::memcmp(cid, "pbag", 4) == 0) { pbag_p = payload; pbag_sz = sz32; } + else if (!pgen_p && std::memcmp(cid, "pgen", 4) == 0) { pgen_p = payload; pgen_sz = sz32; } + else if (!inst_p && std::memcmp(cid, "inst", 4) == 0) { inst_p = payload; inst_sz = sz32; } + else if (!ibag_p && std::memcmp(cid, "ibag", 4) == 0) { ibag_p = payload; ibag_sz = sz32; } + else if (!igen_p && std::memcmp(cid, "igen", 4) == 0) { igen_p = payload; igen_sz = sz32; } + else if (!shdr_p && std::memcmp(cid, "shdr", 4) == 0) { shdr_p = payload; shdr_sz = sz32; } + } + size_t adv = 8u + csz + (csz & 1u); + if (csz > rem || adv > size - pos) break; + pos += adv; + } + + if (ifil_p && ifil_sz >= 4) { uint16_t major = read_le16(ifil_p); is_sf2 = (major >= 2); } - if (!find_subchunk("smpl", smpl_p, smpl_sz) || - !find_subchunk("phdr", phdr_p, phdr_sz) || - !find_subchunk("pbag", pbag_p, pbag_sz) || - !find_subchunk("pgen", pgen_p, pgen_sz) || - !find_subchunk("inst", inst_p, inst_sz) || - !find_subchunk("ibag", ibag_p, ibag_sz) || - !find_subchunk("igen", igen_p, igen_sz) || - !find_subchunk("shdr", shdr_p, shdr_sz)) { + if (!smpl_p || !phdr_p || !pbag_p || !pgen_p || !inst_p || !ibag_p || !igen_p || !shdr_p) { LOG_ERROR("Missing required SoundFont chunks"); return false; } - find_subchunk("snam", snam_p, snam_sz); + + constexpr size_t kMaxSamples = 16384u; + constexpr size_t kMaxTotalZones = 65536u; size_t pool_samples = smpl_sz / 2u; sample_pool.resize(pool_samples); @@ -341,7 +348,7 @@ bool SoundFontBank::load_from_bytes(const uint8_t* data, size_t size) { // Parse sample headers (SF1 = 16B + snam[20B], SF2 = 46B) if (is_sf2) { - size_t scnt = shdr_sz / 46u; + size_t scnt = std::min(static_cast(shdr_sz / 46u), kMaxSamples + 1u); for (size_t i = 0; i + 1 < scnt; ++i) { const uint8_t* p = shdr_p + i * 46u; char nbuf[21]{}; @@ -360,7 +367,7 @@ bool SoundFontBank::load_from_bytes(const uint8_t* data, size_t size) { samples.push_back(std::move(s)); } } else { - size_t scnt = shdr_sz / 16u; + size_t scnt = std::min(static_cast(shdr_sz / 16u), kMaxSamples); for (size_t i = 0; i < scnt; ++i) { const uint8_t* p = shdr_p + i * 16u; SoundFontSample s; @@ -470,7 +477,7 @@ bool SoundFontBank::load_from_bytes(const uint8_t* data, size_t size) { break; case 9: if (is_sf2) { - gs.zone.filter_q_db = std::clamp(static_cast(g.val) * 0.1f, 0.0f, 24.0f); + gs.zone.filter_q_db = std::clamp(static_cast(sval) * 0.1f, 0.0f, 24.0f); } else { float q_norm = static_cast(std::min(g.val, 127u)) / 127.0f; gs.zone.filter_q_db = q_norm * 12.0f; @@ -524,7 +531,7 @@ bool SoundFontBank::load_from_bytes(const uint8_t* data, size_t size) { case 45: gs.loop_start_coarse = sval; break; case 48: if (is_sf2) { - gs.zone.attenuation_db = std::clamp(static_cast(g.val) * 0.1f, 0.0f, 144.0f); + gs.zone.attenuation_db = std::clamp(static_cast(sval) * 0.1f, 0.0f, 144.0f); } else { float vol = static_cast(std::min(g.val, 127u)); gs.zone.attenuation_db = (127.0f - vol) * 0.375f; @@ -614,7 +621,8 @@ bool SoundFontBank::load_from_bytes(const uint8_t* data, size_t size) { } }; - for (size_t pi = 0; pi + 1 < phdr_cnt; ++pi) { + size_t total_zones = 0; + for (size_t pi = 0; pi + 1 < phdr_cnt && total_zones < kMaxTotalZones; ++pi) { const uint8_t* p = phdr_p + pi * 38u; char nbuf[21]{}; std::memcpy(nbuf, p, 20); @@ -627,7 +635,7 @@ bool SoundFontBank::load_from_bytes(const uint8_t* data, size_t size) { uint16_t pb1 = read_le16(phdr_p + (pi + 1) * 38u + 24); std::vector global_pgens; - for (uint16_t pb = pb0; pb < pb1 && static_cast(pb + 1) < pbag_cnt; ++pb) { + for (uint16_t pb = pb0; pb < pb1 && static_cast(pb + 1) < pbag_cnt && total_zones < kMaxTotalZones; ++pb) { uint16_t pg0 = read_le16(pbag_p + pb * 4u); uint16_t pg1 = read_le16(pbag_p + (pb + 1) * 4u); auto pgens = read_gens(pgen_p, pg0, pg1, pgen_sz); @@ -648,7 +656,7 @@ bool SoundFontBank::load_from_bytes(const uint8_t* data, size_t size) { uint16_t ib1 = read_le16(inst_p + (inst_idx + 1) * 22u + 20); GenState global_zone; - for (uint16_t ib = ib0; ib < ib1 && static_cast(ib + 1) < ibag_cnt; ++ib) { + for (uint16_t ib = ib0; ib < ib1 && static_cast(ib + 1) < ibag_cnt && total_zones < kMaxTotalZones; ++ib) { uint16_t ig0 = read_le16(ibag_p + ib * 4u); uint16_t ig1 = read_le16(ibag_p + (ib + 1) * 4u); auto igens = read_gens(igen_p, ig0, ig1, igen_sz); @@ -676,6 +684,7 @@ bool SoundFontBank::load_from_bytes(const uint8_t* data, size_t size) { } if (gs.zone.key_lo <= gs.zone.key_hi && gs.zone.vel_lo <= gs.zone.vel_hi) { pr.zones.push_back(finalize_gen_state(gs)); + ++total_zones; } } else if (ib == ib0) { global_zone = gs; diff --git a/src/assets/rnc.cpp b/src/assets/rnc.cpp index 8015d8f..f4c763f 100644 --- a/src/assets/rnc.cpp +++ b/src/assets/rnc.cpp @@ -9,6 +9,8 @@ namespace top_octane::assets { namespace { +constexpr uint32_t kMaxRncUnpackedBytes = 32u * 1024u * 1024u; + inline uint16_t read_be16(const uint8_t* p) { return static_cast((static_cast(p[0]) << 8) | p[1]); } @@ -34,21 +36,33 @@ struct HuffEntry { struct Rnc1BitStream { const uint8_t* src = nullptr; size_t pos = 0; + size_t size = 0; uint32_t bitbuf = 0; int bitcnt = 0; + bool error = false; - void init(const uint8_t* buf) { + void init(const uint8_t* buf, size_t buf_size) { src = buf; pos = 0; - bitbuf = read_le16(src); + size = buf_size; + error = (!src || size < 2); + bitbuf = error ? 0u : read_le16(src); bitcnt = 16; } void advance(int n) { + if (error || n < 0 || n > 16) { + error = true; + return; + } bitbuf >>= n; bitcnt -= n; if (bitcnt < 16) { pos += 2; + if (pos + 2 > size) { + error = true; + return; + } bitbuf |= static_cast(read_le16(src + pos)) << bitcnt; bitcnt += 16; } @@ -61,7 +75,12 @@ struct Rnc1BitStream { } void fix() { + if (error || pos + 2 > size) { + error = true; + return; + } bitcnt -= 16; + if (bitcnt < 0) bitcnt = 0; uint32_t keep_mask = (bitcnt > 0) ? ((1u << bitcnt) - 1u) : 0u; bitbuf &= keep_mask; bitbuf |= static_cast(read_le16(src + pos)) << bitcnt; @@ -72,10 +91,13 @@ struct Rnc1BitStream { bool build_huff_table(Rnc1BitStream& bs, std::vector& out) { out.clear(); uint32_t num = bs.read(0x1F, 5); + if (bs.error) return false; if (num == 0) return true; + if (num > 32) return false; std::array lens{}; for (uint32_t i = 0; i < num; ++i) { lens[i] = static_cast(bs.read(0x0F, 4)); + if (bs.error) return false; } uint32_t code = 0; @@ -99,21 +121,26 @@ bool build_huff_table(Rnc1BitStream& bs, std::vector& out) { } code <<= 1; } - return true; + return !bs.error; } bool read_huff(Rnc1BitStream& bs, const std::vector& tbl, uint32_t& out_val) { + if (bs.error || tbl.empty()) return false; for (const auto& e : tbl) { if ((bs.bitbuf & e.mask) == e.code) { bs.advance(e.bits); + if (bs.error) return false; if (e.sym < 2) { out_val = e.sym; - } else { + } else if (e.sym <= 17) { int extra = e.sym - 1; - uint32_t mask = (1u << extra) - 1u; - out_val = bs.read(mask, extra) | (1u << extra); + uint32_t high_bit = 1u << extra; + uint32_t mask = high_bit - 1u; + out_val = bs.read(mask, extra) | high_bit; + } else { + return false; } - return true; + return !bs.error; } } return false; @@ -127,8 +154,12 @@ bool unpack_rnc1(const uint8_t* data, size_t size, std::vector& output) uint16_t packed_crc = read_be16(data + 14); uint8_t pack_chunks = data[17]; - if (18u + packed_len > size) { - LOG_ERROR("RNC1 truncated: need %u, got %zu", 18u + packed_len, size); + if (unpacked_len > kMaxRncUnpackedBytes) { + LOG_ERROR("RNC1 unpacked size too large: %u", unpacked_len); + return false; + } + if (static_cast(packed_len) > size || size - static_cast(packed_len) < 18u) { + LOG_ERROR("RNC1 truncated: need 18+%u, got %zu", packed_len, size); return false; } if (rnc_crc16(data + 18, packed_len) != packed_crc) { @@ -137,37 +168,56 @@ bool unpack_rnc1(const uint8_t* data, size_t size, std::vector& output) } // Pad with trailing zero bytes so 16-bit prefetch reads safely at end-of-stream - std::vector src(packed_len + 8, 0); - std::memcpy(src.data(), data + 18, packed_len); + const size_t src_limit = static_cast(packed_len) + 4u; + std::vector src(static_cast(packed_len) + 8u, 0); + if (packed_len > 0) { + std::memcpy(src.data(), data + 18, packed_len); + } Rnc1BitStream bs; - bs.init(src.data()); + bs.init(src.data(), src.size()); bs.read(3, 2); // lock & key bits + if (bs.error) return false; output.clear(); output.reserve(unpacked_len); std::vector raw_t, dist_t, len_t; for (uint8_t chunk = 0; chunk < pack_chunks; ++chunk) { - build_huff_table(bs, raw_t); - build_huff_table(bs, dist_t); - build_huff_table(bs, len_t); + if (!build_huff_table(bs, raw_t) || + !build_huff_table(bs, dist_t) || + !build_huff_table(bs, len_t)) { + output.clear(); + return false; + } int subchunks = static_cast(bs.read(0xFFFF, 16)); + if (bs.error) { + output.clear(); + return false; + } while (true) { uint32_t raw_len = 0; if (!read_huff(bs, raw_t, raw_len)) { LOG_ERROR("RNC1 raw huffman decode failure"); + output.clear(); return false; } if (raw_len > 0) { - if (bs.pos + raw_len > packed_len + 4) { + if (bs.pos > src_limit || + static_cast(raw_len) > src_limit - bs.pos || + static_cast(raw_len) > static_cast(unpacked_len) - output.size()) { LOG_ERROR("RNC1 raw copy OOB"); + output.clear(); return false; } output.insert(output.end(), src.data() + bs.pos, src.data() + bs.pos + raw_len); bs.pos += raw_len; bs.fix(); + if (bs.error) { + output.clear(); + return false; + } } --subchunks; if (subchunks <= 0) break; @@ -175,12 +225,15 @@ bool unpack_rnc1(const uint8_t* data, size_t size, std::vector& output) uint32_t dist = 0, mlen = 0; if (!read_huff(bs, dist_t, dist) || !read_huff(bs, len_t, mlen)) { LOG_ERROR("RNC1 match huffman decode failure"); + output.clear(); return false; } - dist += 1; - mlen += 2; - if (dist > output.size()) { - LOG_ERROR("RNC1 back-reference OOB: dist=%u size=%zu", dist, output.size()); + dist += 1u; + mlen += 2u; + if (dist > output.size() || + static_cast(mlen) > static_cast(unpacked_len) - output.size()) { + LOG_ERROR("RNC1 back-reference OOB: dist=%u mlen=%u size=%zu", dist, mlen, output.size()); + output.clear(); return false; } for (uint32_t k = 0; k < mlen; ++k) { @@ -191,10 +244,12 @@ bool unpack_rnc1(const uint8_t* data, size_t size, std::vector& output) if (output.size() != unpacked_len) { LOG_ERROR("RNC1 length mismatch: got %zu expected %u", output.size(), unpacked_len); + output.clear(); return false; } if (rnc_crc16(output.data(), output.size()) != unpacked_crc) { LOG_ERROR("RNC1 unpacked CRC16 mismatch"); + output.clear(); return false; } return true; @@ -207,16 +262,25 @@ bool unpack_rnc2(const uint8_t* data, size_t size, std::vector& output) uint32_t packed_len = read_be32(data + 8); uint16_t unpacked_crc = read_be16(data + 12); uint16_t packed_crc = read_be16(data + 14); - if (18u + packed_len > size) return false; + if (unpacked_len > kMaxRncUnpackedBytes) return false; + if (static_cast(packed_len) > size || size - static_cast(packed_len) < 18u) { + return false; + } if (rnc_crc16(data + 18, packed_len) != packed_crc) return false; const uint8_t* src = data + 18; size_t pos = 0; uint16_t bitbuf = 0; int bitcnt = 0; + bool eof_err = false; auto getbit = [&]() -> int { + if (eof_err) return 1; if (bitcnt == 0) { - bitbuf = (pos < packed_len) ? src[pos++] : 0; + if (pos >= packed_len) { + eof_err = true; + return 1; + } + bitbuf = src[pos++]; bitcnt = 8; } int bit = (bitbuf >> 7) & 1; @@ -225,17 +289,31 @@ bool unpack_rnc2(const uint8_t* data, size_t size, std::vector& output) return bit; }; auto getbyte = [&]() -> uint8_t { - return (pos < packed_len) ? src[pos++] : 0; + if (eof_err || pos >= packed_len) { + eof_err = true; + return 0; + } + return src[pos++]; }; output.clear(); output.reserve(unpacked_len); getbit(); getbit(); + if (eof_err) return false; - while (true) { - while (getbit() == 0) { - output.push_back(getbyte()); + while (!eof_err) { + while (!eof_err && getbit() == 0) { + uint8_t b = getbyte(); + if (eof_err || output.size() >= unpacked_len) { + output.clear(); + return false; + } + output.push_back(b); + } + if (eof_err) { + output.clear(); + return false; } uint32_t len = 2; uint32_t dist = 0; @@ -249,24 +327,33 @@ bool unpack_rnc2(const uint8_t* data, size_t size, std::vector& output) } else { len = 3; if (getbit() == 0) { - // raw run of 12..72 bytes if (getbit() == 0) { len = 2; int b0 = getbit(), b1 = getbit(), b2 = getbit(); (void)b0; (void)b1; (void)b2; - // fallback unused by Hi-Octane (which uses RNC1 exclusively) + output.clear(); return false; } } + output.clear(); + return false; + } + if (eof_err || dist == 0 || dist > output.size() || + static_cast(len) > static_cast(unpacked_len) - output.size()) { + output.clear(); return false; } - if (dist > output.size()) return false; for (uint32_t i = 0; i < len; ++i) { output.push_back(output[output.size() - dist]); } if (output.size() >= unpacked_len) break; } - return output.size() == unpacked_len && rnc_crc16(output.data(), output.size()) == unpacked_crc; + if (eof_err || output.size() != unpacked_len || + rnc_crc16(output.data(), output.size()) != unpacked_crc) { + output.clear(); + return false; + } + return true; } } // namespace @@ -306,9 +393,18 @@ bool rnc_unpack_bytes(const uint8_t* data, size_t size, std::vector& ou output.clear(); return false; } - if (size >= 18 && data[0] == 'R' && data[1] == 'N' && data[2] == 'C') { + if (!output.empty() && data >= output.data() && data < output.data() + output.size()) { + std::vector copy(data, data + size); + return rnc_unpack_bytes(copy.data(), copy.size(), output); + } + if (size >= 4 && data[0] == 'R' && data[1] == 'N' && data[2] == 'C' && + (data[3] == 1 || data[3] == 2)) { + if (size < 18) { + output.clear(); + return false; + } if (data[3] == 1) return unpack_rnc1(data, size, output); - if (data[3] == 2) return unpack_rnc2(data, size, output); + return unpack_rnc2(data, size, output); } output.assign(data, data + size); return true; diff --git a/src/assets/sound_bank.cpp b/src/assets/sound_bank.cpp index cb73803..050db37 100644 --- a/src/assets/sound_bank.cpp +++ b/src/assets/sound_bank.cpp @@ -50,14 +50,14 @@ bool decode_wav_bytes(const uint8_t* data, size_t size, SoundSample& out_sample) uint32_t sample_rate = 22050; uint16_t bits_per_sample = 8; const uint8_t* pcm_ptr = nullptr; - uint32_t pcm_size = 0; + size_t pcm_size = 0; size_t pos = 12; - while (pos + 8 <= size) { + while (pos + 8u <= size) { const uint8_t* cid = data + pos; - uint32_t csz = read_le32(data + pos + 4); - pos += 8; - if (pos + csz > size) csz = static_cast(size - pos); + size_t csz = static_cast(read_le32(data + pos + 4)); + pos += 8u; + if (csz > size - pos) csz = size - pos; if (std::memcmp(cid, "fmt ", 4) == 0 && csz >= 16) { audio_fmt = read_le16(data + pos + 0); @@ -68,10 +68,13 @@ bool decode_wav_bytes(const uint8_t* data, size_t size, SoundSample& out_sample) pcm_ptr = data + pos; pcm_size = csz; } - pos += csz + (csz & 1u); + size_t adv = csz + (csz & 1u); + if (adv > size - pos) break; + pos += adv; } - if (!pcm_ptr || audio_fmt != 1 || channels == 0 || sample_rate == 0) { + if (!pcm_ptr || audio_fmt != 1 || (channels != 1 && channels != 2) || + sample_rate < 4000u || sample_rate > 192000u) { return false; } @@ -79,8 +82,9 @@ bool decode_wav_bytes(const uint8_t* data, size_t size, SoundSample& out_sample) out_sample.channels = static_cast(channels); out_sample.pcm_mono.clear(); + constexpr size_t kMaxWavFrames = 30u * 192000u; if (bits_per_sample == 8) { - size_t frames = pcm_size / channels; + size_t frames = std::min(pcm_size / channels, kMaxWavFrames); out_sample.pcm_mono.resize(frames); for (size_t i = 0; i < frames; ++i) { float sum = 0.0f; @@ -90,7 +94,7 @@ bool decode_wav_bytes(const uint8_t* data, size_t size, SoundSample& out_sample) out_sample.pcm_mono[i] = sum / static_cast(channels); } } else if (bits_per_sample == 16) { - size_t frames = pcm_size / (2u * channels); + size_t frames = std::min(pcm_size / (2u * channels), kMaxWavFrames); out_sample.pcm_mono.resize(frames); for (size_t i = 0; i < frames; ++i) { float sum = 0.0f; @@ -120,26 +124,30 @@ bool decode_wav_bytes(const uint8_t* data, size_t size, SoundSample& out_sample) } bool SoundBank::load(const Vfs& vfs, const std::string& path) { + gameplay_sfx.clear(); + intro_sfx.clear(); std::vector raw; if (!vfs.read_file(path, raw) || raw.size() < 256) { LOG_ERROR("Failed to read sound archive: %s", path.c_str()); return false; } - uint32_t fat_off = read_le32(raw.data() + raw.size() - 4); - if (fat_off + 12 + 10 * 16 > raw.size()) { - LOG_ERROR("Invalid SOUND.DAT tail FAT offset: %u", fat_off); + size_t fat_off = static_cast(read_le32(raw.data() + raw.size() - 4)); + if (fat_off > raw.size() || raw.size() - fat_off < 12u + 10u * 16u) { + LOG_ERROR("Invalid SOUND.DAT tail FAT offset: %zu", fat_off); return false; } auto load_bank = [&](int bank_idx, std::vector& out_list) -> bool { - size_t b_off = static_cast(fat_off) + 12u + static_cast(bank_idx) * 16u; - uint32_t off_fat = read_le32(raw.data() + b_off + 0); - uint32_t off_data = read_le32(raw.data() + b_off + 4); - uint32_t len_fat = read_le32(raw.data() + b_off + 8); - uint32_t len_data = read_le32(raw.data() + b_off + 12); + size_t b_off = fat_off + 12u + static_cast(bank_idx) * 16u; + uint32_t off_fat32 = read_le32(raw.data() + b_off + 0); + size_t off_fat = static_cast(off_fat32); + size_t off_data = static_cast(read_le32(raw.data() + b_off + 4)); + size_t len_fat = static_cast(read_le32(raw.data() + b_off + 8)); + size_t len_data = static_cast(read_le32(raw.data() + b_off + 12)); - if (off_fat == 0xFFFFFFFFu || off_fat + len_fat > raw.size() || off_data >= raw.size()) { + if (off_fat32 == 0xFFFFFFFFu || off_fat > raw.size() || len_fat > raw.size() - off_fat || + off_data >= raw.size()) { LOG_ERROR("Invalid bank %d offsets in SOUND.DAT", bank_idx); return false; } @@ -148,7 +156,7 @@ bool SoundBank::load(const Vfs& vfs, const std::string& path) { std::vector unpacked; const uint8_t* bank_buf = nullptr; size_t bank_sz = 0; - if (off_data + 18 <= raw.size() && std::memcmp(raw.data() + off_data, "RNC\x01", 4) == 0) { + if (raw.size() - off_data >= 18u && std::memcmp(raw.data() + off_data, "RNC\x01", 4) == 0) { if (!rnc_unpack_bytes(raw.data() + off_data, raw.size() - off_data, unpacked)) { LOG_ERROR("Failed to RNC-unpack SOUND.DAT bank %d", bank_idx); return false; @@ -156,7 +164,7 @@ bool SoundBank::load(const Vfs& vfs, const std::string& path) { bank_buf = unpacked.data(); bank_sz = unpacked.size(); } else { - if (off_data + len_data > raw.size()) return false; + if (len_data > raw.size() - off_data) return false; bank_buf = raw.data() + off_data; bank_sz = len_data; } @@ -167,12 +175,12 @@ bool SoundBank::load(const Vfs& vfs, const std::string& path) { const uint8_t* ent = raw.data() + off_fat + i * 32u; char name_buf[19]{}; std::memcpy(name_buf, ent, 18); - uint32_t s_off = read_le32(ent + 18); - uint32_t s_sz = read_le32(ent + 26); + size_t s_off = static_cast(read_le32(ent + 18)); + size_t s_sz = static_cast(read_le32(ent + 26)); SoundSample smp; smp.name = name_buf; - if (s_off + s_sz <= bank_sz && s_sz >= 44) { + if (s_off <= bank_sz && s_sz <= bank_sz - s_off && s_sz >= 44) { if (decode_wav_bytes(bank_buf + s_off, s_sz, smp)) { // Loudness-normalize 8-bit DOS SFX toward uniform ~0.18 RMS without clipping peaks if (smp.rms > 1e-4f) { diff --git a/src/assets/sprites.cpp b/src/assets/sprites.cpp index 7bee309..498cc31 100644 --- a/src/assets/sprites.cpp +++ b/src/assets/sprites.cpp @@ -2,6 +2,7 @@ #include "assets/rnc.hpp" #include "core/log.hpp" +#include #include namespace top_octane::assets { @@ -23,6 +24,7 @@ inline uint32_t read_le32(const uint8_t* p) { bool SpriteBank::load(const Vfs& vfs, const std::string& dat_path, const std::string& tab_path, const Palette& pal) { + sprites.clear(); std::vector raw_dat, dat, raw_tab, tab; if (!vfs.read_file(dat_path, raw_dat) || !rnc_unpack(raw_dat, dat)) { LOG_ERROR("Failed to load sprite DAT: %s", dat_path.c_str()); @@ -33,9 +35,11 @@ bool SpriteBank::load(const Vfs& vfs, const std::string& dat_path, const std::st return false; } - size_t count = tab.size() / 6; - sprites.clear(); + constexpr size_t kMaxSprites = 4096u; + constexpr size_t kMaxTotalRgbaBytes = 64u * 1024u * 1024u; + size_t count = std::min(tab.size() / 6u, kMaxSprites); sprites.resize(count); + size_t total_rgba_bytes = 0; for (size_t i = 0; i < count; ++i) { const uint8_t* entry = tab.data() + i * 6; @@ -49,7 +53,14 @@ bool SpriteBank::load(const Vfs& vfs, const std::string& dat_path, const std::st if (w <= 0 || h <= 0 || off >= dat.size()) { continue; } - img.rgba.assign(static_cast(w) * static_cast(h) * 4u, 0); + size_t bytes = static_cast(w) * static_cast(h) * 4u; + if (bytes > kMaxTotalRgbaBytes - total_rgba_bytes) { + LOG_ERROR("Sprite bank %s exceeds RGBA memory cap", dat_path.c_str()); + sprites.clear(); + return false; + } + total_rgba_bytes += bytes; + img.rgba.assign(bytes, 0); size_t p = off; int x = 0; @@ -61,24 +72,25 @@ bool SpriteBank::load(const Vfs& vfs, const std::string& dat_path, const std::st x = 0; } else if (code > 0) { int run = code; - if (p + static_cast(run) > dat.size()) { + if (static_cast(run) > dat.size() - p) { LOG_ERROR("Sprite RLE literal OOB in %s[%zu]", dat_path.c_str(), i); + sprites.clear(); return false; } for (int k = 0; k < run; ++k) { uint8_t idx = dat[p++]; if (x >= 0 && x < w) { const Rgba8& c = pal.colors[idx]; - size_t dst = (static_cast(y) * w + x) * 4u; + size_t dst = (static_cast(y) * static_cast(w) + static_cast(x)) * 4u; img.rgba[dst + 0] = c.r; img.rgba[dst + 1] = c.g; img.rgba[dst + 2] = c.b; img.rgba[dst + 3] = 255; } - ++x; + x = std::min(w, x + 1); } } else { - x += -code; + x = std::min(w, x + static_cast(-static_cast(code))); } } } @@ -87,6 +99,7 @@ bool SpriteBank::load(const Vfs& vfs, const std::string& dat_path, const std::st bool TmapBank::load(const Vfs& vfs, const Palette& pal, const std::string& dat_path, const std::string& tab_path) { + sprites.clear(); std::vector dat, tab; if (!vfs.read_file(dat_path, dat) || !vfs.read_file(tab_path, tab)) { LOG_ERROR("Failed to load TMAPS files: %s / %s", dat_path.c_str(), tab_path.c_str()); @@ -97,11 +110,13 @@ bool TmapBank::load(const Vfs& vfs, const Palette& pal, return false; } - sprites.clear(); - const size_t entry_count = tab.size() / 10u; + constexpr size_t kMaxTmapEntries = 2048u; + constexpr size_t kMaxTotalTmapBytes = 64u * 1024u * 1024u; + const size_t entry_count = std::min(tab.size() / 10u, kMaxTmapEntries); sprites.reserve(entry_count); std::vector unpacked; + size_t total_bytes = 0; for (size_t i = 0; i < entry_count; ++i) { const uint8_t* e = tab.data() + i * 10u; uint32_t ulen = read_le32(e + 0); @@ -109,14 +124,21 @@ bool TmapBank::load(const Vfs& vfs, const Palette& pal, if (ulen == 0 || off >= dat.size()) { break; } + if (ulen > 4u * 1024u * 1024u) { + sprites.clear(); + return false; + } if (!rnc_unpack_bytes(dat.data() + off, dat.size() - off, unpacked) || unpacked.size() < 6) { LOG_ERROR("Failed to unpack TMAPS entry %zu at offset %u", i, off); + sprites.clear(); return false; } const int w = static_cast(read_le16(unpacked.data() + 2)); const int h = static_cast(read_le16(unpacked.data() + 4)); - if (w <= 0 || h <= 0 || 6u + static_cast(w) * static_cast(h) > unpacked.size()) { + if (w <= 0 || h <= 0 || w > 2048 || h > 2048 || + static_cast(w) * static_cast(h) > unpacked.size() - 6u) { LOG_ERROR("Invalid TMAPS sprite dimensions %dx%d at entry %zu", w, h, i); + sprites.clear(); return false; } @@ -124,6 +146,11 @@ bool TmapBank::load(const Vfs& vfs, const Palette& pal, img.width = w; img.height = h; const size_t pix_count = static_cast(w) * static_cast(h); + if (pix_count > (kMaxTotalTmapBytes - total_bytes) / 4u) { + sprites.clear(); + return false; + } + total_bytes += pix_count * 4u; img.rgba.resize(pix_count * 4u); for (size_t k = 0; k < pix_count; ++k) { const uint8_t cidx = unpacked[6u + k]; @@ -140,6 +167,9 @@ bool TmapBank::load(const Vfs& vfs, const Palette& pal, bool load_raw_screen(const Vfs& vfs, const std::string& path, int width, int height, const Palette& pal, SpriteImage& out_img) { + if (width <= 0 || height <= 0 || width > 4096 || height > 4096) { + return false; + } std::vector raw, data; if (!vfs.read_file(path, raw) || !rnc_unpack(raw, data)) { LOG_ERROR("Failed to load raw screen: %s", path.c_str()); diff --git a/src/audio/audio_engine.cpp b/src/audio/audio_engine.cpp index f23aaea..2538e71 100644 --- a/src/audio/audio_engine.cpp +++ b/src/audio/audio_engine.cpp @@ -60,13 +60,18 @@ bool AudioEngine::init(const Vfs& vfs, const GameConfig& cfg, bool open_device) return false; } - // Pre-parse all 5 tracks for OPL3 (.XMI bank 2) and SoundFont (.WTB bank 3) - for (int i = 0; i < 5; ++i) { - const auto& xmi_raw = music_archive_.banks[static_cast(assets::MusicBankType::AdlibOpl)][i]; - assets::parse_xmi_sequence(xmi_raw.data.data(), xmi_raw.data.size(), xmi_raw.name, opl_seqs_[i]); - - const auto& wtb_raw = music_archive_.banks[static_cast(assets::MusicBankType::Awe32Wt)][i]; - assets::parse_xmi_sequence(wtb_raw.data.data(), wtb_raw.data.size(), wtb_raw.name, wt_seqs_[i]); + // Pre-parse up to 5 tracks for OPL3 (.XMI bank 2) and SoundFont (.WTB bank 3) + const auto& opl_bank_raw = music_archive_.banks[static_cast(assets::MusicBankType::AdlibOpl)]; + const auto& wt_bank_raw = music_archive_.banks[static_cast(assets::MusicBankType::Awe32Wt)]; + for (size_t i = 0; i < 5; ++i) { + if (i < opl_bank_raw.size()) { + assets::parse_xmi_sequence(opl_bank_raw[i].data.data(), opl_bank_raw[i].data.size(), + opl_bank_raw[i].name, opl_seqs_[i]); + } + if (i < wt_bank_raw.size()) { + assets::parse_xmi_sequence(wt_bank_raw[i].data.data(), wt_bank_raw[i].data.size(), + wt_bank_raw[i].name, wt_seqs_[i]); + } } // Optional external SoundFont (.sf2) @@ -115,9 +120,10 @@ bool AudioEngine::init(const Vfs& vfs, const GameConfig& cfg, bool open_device) active_backend_ = cfg.music_backend; requested_backend_ = cfg.music_backend; - master_vol_.store(cfg.master_volume, std::memory_order_relaxed); - sfx_vol_.store(cfg.sfx_volume, std::memory_order_relaxed); - music_vol_.store(cfg.music_volume, std::memory_order_relaxed); + auto sane_vol = [](float v) { return std::isfinite(v) ? std::clamp(v, 0.0f, 1.0f) : 0.0f; }; + master_vol_.store(sane_vol(cfg.master_volume), std::memory_order_relaxed); + sfx_vol_.store(sane_vol(cfg.sfx_volume), std::memory_order_relaxed); + music_vol_.store(sane_vol(cfg.music_volume), std::memory_order_relaxed); mix_sample_clock_ = static_cast(kSampleRate) * 60ull; voice_seq_ = 0; last_play_sample_gameplay_.fill(0); @@ -168,9 +174,10 @@ void AudioEngine::shutdown() { } void AudioEngine::apply_config(const GameConfig& cfg, bool window_focused) { - master_vol_.store(cfg.master_volume, std::memory_order_relaxed); - sfx_vol_.store(cfg.sfx_volume, std::memory_order_relaxed); - music_vol_.store(cfg.music_volume, std::memory_order_relaxed); + auto sane_vol = [](float v) { return std::isfinite(v) ? std::clamp(v, 0.0f, 1.0f) : 0.0f; }; + master_vol_.store(sane_vol(cfg.master_volume), std::memory_order_relaxed); + sfx_vol_.store(sane_vol(cfg.sfx_volume), std::memory_order_relaxed); + music_vol_.store(sane_vol(cfg.music_volume), std::memory_order_relaxed); muted_.store(cfg.mute_on_focus_loss && !window_focused, std::memory_order_relaxed); if (cfg.custom_soundfont_path != loaded_custom_sf_path_) { @@ -183,18 +190,20 @@ void AudioEngine::apply_config(const GameConfig& cfg, bool window_focused) { ok = true; } } - if (dev_id_ != 0) SDL_LockAudioDevice(dev_id_); - if (ok) { - custom_sf_bank_ = std::move(next_sf); - has_custom_sf_ = true; - } else { - custom_sf_bank_ = assets::SoundFontBank{}; - has_custom_sf_ = false; + { + // Parse & build off-lock above, swap pointer/bank under device lock, free old bank after unlock + if (dev_id_ != 0) SDL_LockAudioDevice(dev_id_); + std::swap(custom_sf_bank_, next_sf); + has_custom_sf_ = ok; + loaded_custom_sf_path_ = cfg.custom_soundfont_path; + sf_synth_.set_soundfont(has_custom_sf_ ? &custom_sf_bank_ : &sf_bank_); + if (active_backend_ == MusicBackend::SoundFont && xmi_player_.is_playing()) { + start_active_track(); + } else { + sf_synth_.reset(); + } + if (dev_id_ != 0) SDL_UnlockAudioDevice(dev_id_); } - loaded_custom_sf_path_ = cfg.custom_soundfont_path; - sf_synth_.reset(); - sf_synth_.set_soundfont(has_custom_sf_ ? &custom_sf_bank_ : &sf_bank_); - if (dev_id_ != 0) SDL_UnlockAudioDevice(dev_id_); } if (cfg.music_backend != requested_backend_) { @@ -230,6 +239,7 @@ int AudioEngine::find_sfx_index(const std::string& name, bool intro_bank) const void AudioEngine::play_sfx(const std::string& wav_name, float gain, float pitch, float pan, bool is_intro_bank, float min_interval_sec) { + if (!std::isfinite(gain) || !std::isfinite(pitch) || !std::isfinite(pan)) return; int idx = find_sfx_index(wav_name, is_intro_bank); if (idx < 0 && is_intro_bank) { is_intro_bank = false; @@ -244,23 +254,28 @@ void AudioEngine::play_sfx(const std::string& wav_name, float gain, float pitch, cmd.gain = std::clamp(gain, 0.0f, 2.0f); cmd.pitch = std::clamp(pitch, 0.25f, 3.0f); cmd.pan = std::clamp(pan, -1.0f, 1.0f); - cmd.min_interval_sec = std::max(0.0f, min_interval_sec); + cmd.min_interval_sec = std::isfinite(min_interval_sec) ? std::max(0.0f, min_interval_sec) : 0.0f; push_command(cmd); } void AudioEngine::play_sfx_3d(const std::string& wav_name, const Vec3& src_pos, const Vec3& listener_pos, const Vec3& listener_right, float gain, float pitch, float min_interval_sec) { + if (!std::isfinite(src_pos.x) || !std::isfinite(src_pos.y) || !std::isfinite(src_pos.z) || + !std::isfinite(listener_pos.x) || !std::isfinite(listener_pos.y) || !std::isfinite(listener_pos.z) || + !std::isfinite(listener_right.x) || !std::isfinite(listener_right.y) || !std::isfinite(listener_right.z)) { + return; + } Vec3 d = src_pos - listener_pos; float dist = d.len(); - if (dist > 28.0f) return; + if (!std::isfinite(dist) || dist > 28.0f) return; float atten = 1.0f / (1.0f + dist * 0.22f + dist * dist * 0.025f); float pan = (dist > 0.1f) ? std::clamp((d / dist).dot(listener_right), -1.0f, 1.0f) : 0.0f; play_sfx(wav_name, gain * atten, pitch, pan, false, min_interval_sec); } void AudioEngine::play_intro_sfx(int sample_index_0based, float gain, bool loop) { - if (sample_index_0based < 0 || + if (!std::isfinite(gain) || sample_index_0based < 0 || static_cast(sample_index_0based) >= sound_bank_.intro_sfx.size()) { return; } @@ -286,16 +301,19 @@ void AudioEngine::stop_intro_sfx(int sample_index_0based) { } void AudioEngine::set_engine_state(bool active, float speed_ratio, bool boosting, float scrape_amount) { + float sr = std::isfinite(speed_ratio) ? std::clamp(speed_ratio, 0.0f, 1.5f) : 0.0f; + float sc = std::isfinite(scrape_amount) ? std::clamp(scrape_amount, 0.0f, 1.0f) : 0.0f; engine_active_.store(active, std::memory_order_relaxed); - engine_speed_ratio_.store(std::clamp(speed_ratio, 0.0f, 1.5f), std::memory_order_relaxed); + engine_speed_ratio_.store(sr, std::memory_order_relaxed); engine_boosting_.store(boosting, std::memory_order_relaxed); - scrape_amount_.store(std::clamp(scrape_amount, 0.0f, 1.0f), std::memory_order_relaxed); + scrape_amount_.store(sc, std::memory_order_relaxed); } void AudioEngine::set_pitstop_state(bool on_pad, bool charging, float fill_ratio) { + float fr = std::isfinite(fill_ratio) ? std::clamp(fill_ratio, 0.0f, 1.0f) : 1.0f; pit_active_.store(on_pad, std::memory_order_relaxed); pit_charging_.store(charging, std::memory_order_relaxed); - pit_fill_ratio_.store(std::clamp(fill_ratio, 0.0f, 1.0f), std::memory_order_relaxed); + pit_fill_ratio_.store(fr, std::memory_order_relaxed); } const assets::XmiSequence& AudioEngine::xmi_sequence(MusicBackend b, MusicTrackId t) const { @@ -441,7 +459,7 @@ void AudioEngine::drain_commands() { } void AudioEngine::render_internal(float* stereo_out, int frames) { - if (frames <= 0) return; + if (!stereo_out || frames <= 0) return; std::memset(stereo_out, 0, static_cast(frames) * 2u * sizeof(float)); drain_commands(); @@ -492,25 +510,33 @@ void AudioEngine::render_internal(float* stereo_out, int frames) { } } - // 2. Render SFX + Continuous Engine & Scrape Loops into isolated SFX bus + soft compressor + // 2. Render SFX + Continuous Engine & Scrape Loops into isolated SFX bus + soft clipper if (svol > 0.001f) { - std::fill_n(sfx_bus.data(), cur * 2, 0.0f); + bool sfx_any = false; + auto ensure_sfx_bus = [&]() { + if (!sfx_any) { + std::fill_n(sfx_bus.data(), cur * 2, 0.0f); + sfx_any = true; + } + }; for (auto& v : sfx_voices_) { if (!v.active || !v.sample) continue; const auto& pcm = v.sample->pcm_mono; const size_t len = pcm.size(); - if (len < 2) { + if (len < 2 || !std::isfinite(v.pos) || v.pos < 0.0 || + !std::isfinite(v.step) || v.step <= 0.0) { v.active = false; v.loop = false; continue; } + ensure_sfx_bus(); for (int f = 0; f < cur; ++f) { size_t i0 = 0; size_t i1 = 0; if (v.loop) { - while (v.pos >= static_cast(len)) { - v.pos -= static_cast(len); + if (v.pos >= static_cast(len)) { + v.pos = std::fmod(v.pos, static_cast(len)); } i0 = static_cast(v.pos); i1 = (i0 + 1 < len) ? (i0 + 1) : 0; @@ -532,6 +558,7 @@ void AudioEngine::render_internal(float* stereo_out, int frames) { if (engine_active_.load(std::memory_order_relaxed) && engine_sample_ && !engine_sample_->pcm_mono.empty()) { + ensure_sfx_bus(); float spd = engine_speed_ratio_.load(std::memory_order_relaxed); bool bst = engine_boosting_.load(std::memory_order_relaxed); double pitch = 0.65 + 0.65 * spd + (bst ? 0.28 : 0.0); @@ -556,6 +583,7 @@ void AudioEngine::render_internal(float* stereo_out, int frames) { float scrape = scrape_amount_.load(std::memory_order_relaxed); if (scrape > 0.02f && scrape_sample_ && !scrape_sample_->pcm_mono.empty()) { + ensure_sfx_bus(); const auto& pcm = scrape_sample_->pcm_mono; size_t len = pcm.size(); double step = static_cast(scrape_sample_->sample_rate) / kSampleRate; @@ -576,6 +604,7 @@ void AudioEngine::render_internal(float* stereo_out, int frames) { const float target_pit_env = pit_on ? (pit_chg ? 1.0f : 0.45f) : 0.0f; if ((refuel_env_ > 0.001f || target_pit_env > 0.001f) && refuel_sample_ && !refuel_sample_->pcm_mono.empty()) { + ensure_sfx_bus(); const auto& pcm = refuel_sample_->pcm_mono; const size_t len = pcm.size(); const double pitch = pit_chg ? (0.78 + 0.52 * static_cast(pit_fill)) : 1.28; @@ -601,8 +630,17 @@ void AudioEngine::render_internal(float* stereo_out, int frames) { } } - for (int i = 0; i < cur * 2; ++i) { - out_ptr[i] += std::tanh(sfx_bus[i] * 1.1f) * 0.88f; + if (sfx_any) { + for (int i = 0; i < cur * 2; ++i) { + float y = sfx_bus[i] * 0.968f; + float ay = std::abs(y); + if (ay <= 0.55f) { + out_ptr[i] += y; + } else { + float lim = 0.55f + 0.33f * std::tanh((ay - 0.55f) / 0.33f); + out_ptr[i] += (y >= 0.0f) ? lim : -lim; + } + } } } } diff --git a/src/audio/opl3_synth.cpp b/src/audio/opl3_synth.cpp index 5280f0d..8963bfb 100644 --- a/src/audio/opl3_synth.cpp +++ b/src/audio/opl3_synth.cpp @@ -2,12 +2,33 @@ #include "core/math.hpp" #include +#include #include namespace top_octane::audio { namespace { +constexpr int kSinLutSize = 2048; + +inline float fast_sin_phase(double p) { + static const std::array kLut = []() { + std::array t{}; + for (int i = 0; i <= kSinLutSize; ++i) { + t[static_cast(i)] = static_cast( + std::sin((static_cast(i) / static_cast(kSinLutSize)) * kTwoPi)); + } + return t; + }(); + if (!std::isfinite(p)) return 0.0f; + p -= std::floor(p); + double fp = p * static_cast(kSinLutSize); + int i0 = static_cast(fp) & (kSinLutSize - 1); + float frac = static_cast(fp - static_cast(i0)); + return kLut[static_cast(i0)] + + (kLut[static_cast(i0) + 1u] - kLut[static_cast(i0)]) * frac; +} + constexpr double kMultTable[16] = { 0.5, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 10.0, 12.0, 12.0, 15.0, 15.0 @@ -48,15 +69,31 @@ void Opl3Synth::reset() { } void Opl3Synth::set_sample_rate(int sample_rate) { - sample_rate_ = std::max(sample_rate, 8000); + sample_rate_ = std::clamp(sample_rate, 8000, 192000); + for (auto& v : voices_) { + if (!v.active) continue; + update_operator_rates(v.op_mod); + update_operator_rates(v.op_car); + update_voice_freq(v); + } +} + +void Opl3Synth::update_operator_rates(Operator& op) { + constexpr float kDbToLn = 0.11512925465f; // ln(10) / 20 + const float dt = 1.0f / static_cast(sample_rate_); + op.attack_alpha = (op.attack_rate > 0.0f) ? (1.0f - std::exp(-op.attack_rate * dt)) : 0.0f; + op.decay_mul = (op.decay_rate > 0.0f) ? std::exp(-op.decay_rate * dt * kDbToLn) : 1.0f; + op.sustain_lin = (op.sustain_db >= 90.0f) ? 0.0f : std::exp(-op.sustain_db * kDbToLn); + op.release_mul = std::exp(-op.release_rate * dt * kDbToLn); } void Opl3Synth::setup_operator(Operator& op, uint8_t reg20, uint8_t reg40, uint8_t reg60, uint8_t reg80, uint8_t regE0, float base_freq, float midi_note, float vel_scale, bool is_carrier) { - double mult = kMultTable[reg20 & 0x0Fu]; + op.mult = kMultTable[reg20 & 0x0Fu]; op.phase = 0.0; - op.phase_inc = (static_cast(base_freq) * mult) / static_cast(sample_rate_); + op.phase_inc = std::clamp((static_cast(base_freq) * op.mult) / static_cast(sample_rate_), + 0.0, 0.49); op.am = (reg20 & 0x80u) != 0; op.vib = (reg20 & 0x40u) != 0; op.sustain_hold = (reg20 & 0x20u) != 0; @@ -95,18 +132,16 @@ void Opl3Synth::setup_operator(Operator& op, uint8_t reg20, uint8_t reg40, uint8 op.env = 0.0f; op.env_db = 96.0f; op.stage = (op.attack_rate > 0.0f) ? EnvStage::Attack : EnvStage::Off; + update_operator_rates(op); } void Opl3Synth::update_voice_freq(Voice& v) { - float bend = channels_[v.channel].pitch_bend_semitones; - float f = v.base_freq * std::pow(2.0f, bend / 12.0f); - const assets::OplPatch* patch = bank_ ? bank_->find( - v.channel == 9 ? v.key : channels_[v.channel].program, - v.channel == 9 ? 127 : channels_[v.channel].bank) : nullptr; - double m0 = patch ? kMultTable[patch->regs[3] & 0x0Fu] : 1.0; - double m1 = patch ? kMultTable[patch->regs[9] & 0x0Fu] : 1.0; - v.op_mod.phase_inc = (static_cast(f) * m0) / static_cast(sample_rate_); - v.op_car.phase_inc = (static_cast(f) * m1) / static_cast(sample_rate_); + if (v.channel >= kNumChannels) return; + float f = v.base_freq * channels_[v.channel].bend_mul; + if (!std::isfinite(f) || f < 0.0f) f = 0.0f; + const double sr = static_cast(sample_rate_); + v.op_mod.phase_inc = std::clamp((static_cast(f) * v.op_mod.mult) / sr, 0.0, 0.49); + v.op_car.phase_inc = std::clamp((static_cast(f) * v.op_car.mult) / sr, 0.0, 0.49); } void Opl3Synth::note_on(uint8_t ch, uint8_t key, uint8_t vel) { @@ -207,7 +242,9 @@ void Opl3Synth::control_change(uint8_t ch, uint8_t cc, uint8_t val) { cs.volume_target = std::clamp(static_cast(val) / 127.0f, 0.0f, 1.0f); break; case 10: // Pan - cs.pan = (static_cast(val) - 64.0f) / 64.0f; + cs.pan = std::clamp((static_cast(val) - 64.0f) / 64.0f, -1.0f, 1.0f); + cs.pan_l = std::sqrt(0.5f * (1.0f - cs.pan)); + cs.pan_r = std::sqrt(0.5f * (1.0f + cs.pan)); break; case 11: // Expression cs.expr_target = std::clamp(static_cast(val) / 127.0f, 0.0f, 1.0f); @@ -233,6 +270,7 @@ void Opl3Synth::control_change(uint8_t ch, uint8_t cc, uint8_t val) { cs.expr_target = 1.0f; cs.expr_smooth = 1.0f; cs.pitch_bend_semitones = 0.0f; + cs.bend_mul = 1.0f; cs.sustain_pedal = false; for (auto& v : voices_) { if (v.active && v.channel == ch) { @@ -263,6 +301,7 @@ void Opl3Synth::control_change(uint8_t ch, uint8_t cc, uint8_t val) { void Opl3Synth::pitch_bend(uint8_t ch, int16_t bend14) { if (ch >= kNumChannels) return; channels_[ch].pitch_bend_semitones = (static_cast(bend14) / 8192.0f) * 2.0f; + channels_[ch].bend_mul = std::pow(2.0f, channels_[ch].pitch_bend_semitones / 12.0f); for (auto& v : voices_) { if (v.active && v.channel == ch) update_voice_freq(v); } @@ -274,52 +313,43 @@ void Opl3Synth::all_notes_off() { } } -void Opl3Synth::step_envelope(Operator& op, float dt) { - constexpr float kDbToLn = 0.11512925465f; // ln(10) / 20 +void Opl3Synth::step_envelope(Operator& op) { switch (op.stage) { case EnvStage::Off: op.env = 0.0f; - op.env_db = 96.0f; break; case EnvStage::Attack: - if (op.attack_rate <= 0.0f) { + if (op.attack_alpha <= 0.0f) { op.env = 0.0f; - op.env_db = 96.0f; op.stage = EnvStage::Off; } else { - op.env += (1.05f - op.env) * (1.0f - std::exp(-op.attack_rate * dt)); + op.env += (1.05f - op.env) * op.attack_alpha; if (op.env >= 1.0f) { op.env = 1.0f; - op.env_db = 0.0f; op.stage = EnvStage::Decay; } } break; case EnvStage::Decay: if (op.decay_rate > 0.0f) { - op.env_db += op.decay_rate * dt; - if (op.env_db >= op.sustain_db) { - op.env_db = op.sustain_db; + op.env *= op.decay_mul; + if (op.env <= op.sustain_lin || op.env <= 3.16228e-5f) { + op.env = op.sustain_lin; op.stage = op.sustain_hold ? EnvStage::Sustain : EnvStage::Release; } } else if (op.sustain_db <= 0.01f) { - op.env_db = 0.0f; + op.env = 1.0f; op.stage = op.sustain_hold ? EnvStage::Sustain : EnvStage::Release; } - op.env = (op.env_db >= 90.0f) ? 0.0f : std::exp(-op.env_db * kDbToLn); break; case EnvStage::Sustain: - op.env_db = op.sustain_db; - op.env = (op.sustain_db >= 90.0f) ? 0.0f : std::exp(-op.env_db * kDbToLn); + op.env = op.sustain_lin; break; case EnvStage::Release: - op.env_db += op.release_rate * dt; - if (op.env_db >= 84.0f) { + op.env *= op.release_mul; + if (op.env <= 6.309573e-5f) { op.env = 0.0f; - op.env_db = 96.0f; op.stage = EnvStage::Off; - } else { - op.env = std::exp(-op.env_db * kDbToLn); } break; } @@ -329,18 +359,17 @@ float Opl3Synth::eval_waveform(uint8_t wave, double phase) { double p = phase - std::floor(phase); switch (wave & 7u) { case 0: // Full sine - return static_cast(std::sin(p * kTwoPi)); + return fast_sin_phase(p); case 1: // Half-sine - return p < 0.5 ? static_cast(std::sin(p * kTwoPi)) : 0.0f; + return p < 0.5 ? fast_sin_phase(p) : 0.0f; case 2: // Abs-sine - return static_cast(std::abs(std::sin(p * kTwoPi))); + return std::abs(fast_sin_phase(p)); case 3: // Quarter-pulse sine - return (p < 0.25 || (p >= 0.5 && p < 0.75)) ? - static_cast(std::abs(std::sin(p * kTwoPi))) : 0.0f; + return (p < 0.25 || (p >= 0.5 && p < 0.75)) ? std::abs(fast_sin_phase(p)) : 0.0f; case 4: // Alternating double-freq sine - return p < 0.5 ? static_cast(std::sin(p * 2.0 * kTwoPi)) : 0.0f; + return p < 0.5 ? fast_sin_phase(p * 2.0) : 0.0f; case 5: // Alternating double-freq abs-sine - return p < 0.5 ? static_cast(std::abs(std::sin(p * 2.0 * kTwoPi))) : 0.0f; + return p < 0.5 ? std::abs(fast_sin_phase(p * 2.0)) : 0.0f; case 6: // Square return p < 0.5 ? 1.0f : -1.0f; case 7: // Derived exponential/saw @@ -351,6 +380,7 @@ float Opl3Synth::eval_waveform(uint8_t wave, double phase) { } void Opl3Synth::render(float* stereo_out, int frames) { + if (!stereo_out || frames <= 0) return; const float dt = 1.0f / static_cast(sample_rate_); const float cc_alpha = 1.0f - std::exp(-dt / 0.005f); const double lfo_inc = 6.0 / static_cast(sample_rate_); @@ -358,7 +388,7 @@ void Opl3Synth::render(float* stereo_out, int frames) { for (int f = 0; f < frames; ++f) { lfo_phase_ += lfo_inc; if (lfo_phase_ >= 1.0) lfo_phase_ -= 1.0; - float lfo = static_cast(std::sin(lfo_phase_ * kTwoPi)); + float lfo = fast_sin_phase(lfo_phase_); for (int c = 0; c < kNumChannels; ++c) { channels_[c].vol_smooth += (channels_[c].volume_target - channels_[c].vol_smooth) * cc_alpha; @@ -369,10 +399,10 @@ void Opl3Synth::render(float* stereo_out, int frames) { float right = 0.0f; for (auto& v : voices_) { - if (!v.active) continue; + if (!v.active || v.channel >= kNumChannels) continue; - step_envelope(v.op_mod, dt); - step_envelope(v.op_car, dt); + step_envelope(v.op_mod); + step_envelope(v.op_car); if (v.op_car.stage == EnvStage::Off && (!v.additive || v.op_mod.stage == EnvStage::Off)) { v.active = false; continue; @@ -407,11 +437,8 @@ void Opl3Synth::render(float* stereo_out, int frames) { const ChannelState& cs = channels_[v.channel]; float ch_gain = (cs.vol_smooth * cs.vol_smooth) * (cs.expr_smooth * cs.expr_smooth) * 0.28f; - float pan_norm = std::clamp(cs.pan, -1.0f, 1.0f); - float gl = std::sqrt(0.5f * (1.0f - pan_norm)); - float gr = std::sqrt(0.5f * (1.0f + pan_norm)); - left += sample * ch_gain * gl; - right += sample * ch_gain * gr; + left += sample * ch_gain * cs.pan_l; + right += sample * ch_gain * cs.pan_r; } stereo_out[f * 2 + 0] += soft_limit_safety(left, 0.85f); diff --git a/src/audio/opl3_synth.hpp b/src/audio/opl3_synth.hpp index 209684f..ebc6678 100644 --- a/src/audio/opl3_synth.hpp +++ b/src/audio/opl3_synth.hpp @@ -47,6 +47,7 @@ private: struct Operator { double phase = 0.0; double phase_inc = 0.0; + double mult = 1.0; float env = 0.0f; // 0..1 linear amplitude float env_db = 96.0f; // 0 dB = peak, 96 dB = silence EnvStage stage = EnvStage::Off; @@ -54,6 +55,10 @@ private: float decay_rate = 0.0f; // dB/s float sustain_db = 12.0f; // dB attenuation float release_rate = 0.0f; // dB/s + float attack_alpha = 0.0f; + float decay_mul = 1.0f; + float sustain_lin = 0.0f; + float release_mul = 1.0f; float total_level = 1.0f; // linear scale from TL + KSL + vel uint8_t wave = 0; bool am = false; @@ -85,14 +90,18 @@ private: float expr_target = 1.0f; float expr_smooth = 1.0f; float pan = 0.0f; // -1..+1 + float pan_l = 0.70710678f; + float pan_r = 0.70710678f; float pitch_bend_semitones = 0.0f; + float bend_mul = 1.0f; bool sustain_pedal = false; }; void setup_operator(Operator& op, uint8_t reg20, uint8_t reg40, uint8_t reg60, uint8_t reg80, uint8_t regE0, float base_freq, float midi_note, float vel_scale, bool is_carrier); - void step_envelope(Operator& op, float dt); + void update_operator_rates(Operator& op); + void step_envelope(Operator& op); static float eval_waveform(uint8_t wave, double phase); void update_voice_freq(Voice& v); diff --git a/src/audio/sf_synth.cpp b/src/audio/sf_synth.cpp index 59586be..ddc4304 100644 --- a/src/audio/sf_synth.cpp +++ b/src/audio/sf_synth.cpp @@ -2,12 +2,33 @@ #include "core/math.hpp" #include +#include #include namespace top_octane::audio { namespace { +constexpr int kSinLutSize = 2048; + +inline float fast_sin_phase(double p) { + static const std::array kLut = []() { + std::array t{}; + for (int i = 0; i <= kSinLutSize; ++i) { + t[static_cast(i)] = static_cast( + std::sin((static_cast(i) / static_cast(kSinLutSize)) * kTwoPi)); + } + return t; + }(); + if (!std::isfinite(p)) return 0.0f; + p -= std::floor(p); + double fp = p * static_cast(kSinLutSize); + int i0 = static_cast(fp) & (kSinLutSize - 1); + float frac = static_cast(fp - static_cast(i0)); + return kLut[static_cast(i0)] + + (kLut[static_cast(i0) + 1u] - kLut[static_cast(i0)]) * frac; +} + inline float polyblep(double t, double dt) { if (dt <= 0.0 || dt >= 0.5) return 0.0f; if (t < dt) { @@ -49,12 +70,12 @@ inline float soft_limit_safety(float x, float thresh) { return (x >= 0.0f) ? limited : -limited; } -inline float apply_svf_2x(float x, float fc_hz, float q_damp, int sample_rate, - float& lp, float& bp) { - const float sr_f = static_cast(sample_rate); - const float fc = std::clamp(fc_hz, 25.0f, 0.40f * sr_f); - const float damp = std::clamp(q_damp, 0.22f, 1.45f); - const float f = 2.0f * std::sin(static_cast(kPi) * fc / (2.0f * sr_f)); +inline float compute_svf_f(float fc_hz, float sr_f) { + const float fc = std::clamp(std::isfinite(fc_hz) ? fc_hz : 20000.0f, 25.0f, 0.40f * sr_f); + return 2.0f * std::sin(static_cast(kPi) * fc / (2.0f * sr_f)); +} + +inline float apply_svf_2x_coeff(float x, float f, float damp, float& lp, float& bp) { for (int sub = 0; sub < 2; ++sub) { lp += f * bp; float hp = x - lp - damp * bp; @@ -65,6 +86,8 @@ inline float apply_svf_2x(float x, float fc_hz, float q_damp, int sample_rate, bp = 0.0f; return 0.0f; } + if (std::abs(lp) < 1e-20f) lp = 0.0f; + if (std::abs(bp) < 1e-20f) bp = 0.0f; return std::clamp(lp, -4.0f, 4.0f); } @@ -72,14 +95,14 @@ inline float apply_svf_2x(float x, float fc_hz, float q_damp, int sample_rate, SfSynth::SfSynth(const assets::SoundFontBank* sf, const assets::OplTimbreBank* opl_fallback, int sample_rate) - : sf_(sf), sample_rate_(std::max(sample_rate, 8000)) { + : sf_(sf), sample_rate_(std::clamp(sample_rate, 8000, 192000)) { (void)opl_fallback; set_sample_rate(sample_rate_); reset(); } void SfSynth::set_sample_rate(int sample_rate) { - sample_rate_ = std::max(sample_rate, 8000); + sample_rate_ = std::clamp(sample_rate, 8000, 192000); // Primes scaled to sample_rate for stereo comb reverb (~29, 37 ms L / ~31, 41 ms R) const size_t l0 = static_cast(std::max(64, (sample_rate_ * 29) / 1000)); const size_t l1 = static_cast(std::max(64, (sample_rate_ * 37) / 1000)); @@ -93,6 +116,27 @@ void SfSynth::set_sample_rate(int sample_rate) { rev_idx_r_[0] = rev_idx_r_[1] = 0; rev_lp_l_[0] = rev_lp_l_[1] = 0.0f; rev_lp_r_[0] = rev_lp_r_[1] = 0.0f; + for (auto& v : voices_) { + if (v.active) finalize_voice_cache(v); + } +} + +void SfSynth::finalize_voice_cache(WtVoice& v) { + constexpr float kDbToLn = 0.11512925465f; + const float sr_f = static_cast(sample_rate_); + const float dt = 1.0f / sr_f; + const float p = std::clamp(v.pan, -1.0f, 1.0f); + v.pan_l = std::sqrt(0.5f * (1.0f - p)); + v.pan_r = std::sqrt(0.5f * (1.0f + p)); + const float atk_rate = 3.0445f / std::max(v.attack_sec, 0.001f); + v.attack_alpha = 1.0f - std::exp(-atk_rate * dt); + v.decay_mul = (v.decay_rate_db > 0.0005f) ? std::exp(-v.decay_rate_db * dt * kDbToLn) : 1.0f; + v.sustain_lin = (v.sustain_db >= 90.0f) ? 0.0f : std::exp(-v.sustain_db * kDbToLn); + v.release_mul = std::exp(-v.release_rate_db * dt * kDbToLn); + v.svf_damp = std::clamp(v.filter_q_damp, 0.22f, 1.45f); + v.svf_f_static = compute_svf_f(v.filter_fc_hz, sr_f); + v.svf_f_cached = v.svf_f_static; + v.filter_mod_counter = 0; } void SfSynth::reset() { @@ -196,7 +240,8 @@ void SfSynth::spawn_sf_zone(uint8_t ch, uint8_t key, uint8_t vel, const assets:: v.l_start = static_cast(ls); v.l_end = static_cast(le); v.pos = static_cast(v.s_start); - v.step = (static_cast(smp.sample_rate) / static_cast(sample_rate_)) * pitch_ratio; + double raw_step = (static_cast(smp.sample_rate) / static_cast(sample_rate_)) * pitch_ratio; + v.step = std::isfinite(raw_step) ? std::clamp(raw_step, 1e-5, 16.0) : 1.0; } else { v.rom_kind = classify_rom_sample(smp.name); double eff_key = (z.scale_tuning == 0) ? static_cast(root) : static_cast(key); @@ -247,6 +292,7 @@ void SfSynth::spawn_sf_zone(uint8_t ch, uint8_t key, uint8_t vel, const assets:: v.filter_q_damp = std::max(1.0f / q_lin, 0.22f); v.mod_env_to_filter_cents = z.mod_env_to_filter_cents; } + finalize_voice_cache(v); } void SfSynth::spawn_gm_voice(uint8_t ch, uint8_t key, uint8_t vel) { @@ -367,6 +413,7 @@ void SfSynth::spawn_gm_voice(uint8_t ch, uint8_t key, uint8_t vel) { } v.step = v.drum_pitch_hz / static_cast(sample_rate_); v.env_stage = EnvStage::Attack; + finalize_voice_cache(v); return; } @@ -498,6 +545,7 @@ void SfSynth::spawn_gm_voice(uint8_t ch, uint8_t key, uint8_t vel) { v.sustain_db = 18.0f; v.release_rate_db = 96.0f / 0.20f; } + finalize_voice_cache(v); } void SfSynth::note_on(uint8_t ch, uint8_t key, uint8_t vel) { @@ -605,6 +653,7 @@ void SfSynth::control_change(uint8_t ch, uint8_t cc, uint8_t val) { cs.expr_target = 1.0f; cs.expr_smooth = 1.0f; cs.pitch_bend_semitones = 0.0f; + cs.bend_mul = 1.0f; cs.sustain_pedal = false; cs.chorus_cc = 0.0f; cs.reverb_cc = 0.15f; @@ -632,6 +681,7 @@ void SfSynth::control_change(uint8_t ch, uint8_t cc, uint8_t val) { void SfSynth::pitch_bend(uint8_t ch, int16_t bend14) { if (ch < 16) { channels_[ch].pitch_bend_semitones = (static_cast(bend14) / 8192.0f) * 2.0f; + channels_[ch].bend_mul = std::pow(2.0f, channels_[ch].pitch_bend_semitones / 12.0f); } } @@ -640,28 +690,23 @@ void SfSynth::all_notes_off() { } void SfSynth::step_env(WtVoice& v, float dt) { - constexpr float kDbToLn = 0.11512925465f; switch (v.env_stage) { case EnvStage::Off: v.env = 0.0f; - v.env_db = 96.0f; v.active = false; break; case EnvStage::Delay: v.stage_timer += dt; v.env = 0.0f; - v.env_db = 96.0f; if (v.stage_timer >= v.delay_sec) { v.stage_timer = 0.0f; v.env_stage = EnvStage::Attack; } break; case EnvStage::Attack: { - float atk_rate = 3.0445f / std::max(v.attack_sec, 0.001f); - v.env += (1.05f - v.env) * (1.0f - std::exp(-atk_rate * dt)); + v.env += (1.05f - v.env) * v.attack_alpha; if (v.env >= 1.0f) { v.env = 1.0f; - v.env_db = 0.0f; v.stage_timer = 0.0f; v.env_stage = (v.hold_sec > 0.0005f) ? EnvStage::Hold : EnvStage::Decay; } @@ -669,7 +714,6 @@ void SfSynth::step_env(WtVoice& v, float dt) { } case EnvStage::Hold: v.env = 1.0f; - v.env_db = 0.0f; v.stage_timer += dt; if (v.stage_timer >= v.hold_sec) { v.env_stage = EnvStage::Decay; @@ -677,48 +721,51 @@ void SfSynth::step_env(WtVoice& v, float dt) { break; case EnvStage::Decay: if (v.decay_rate_db <= 0.0f || v.sustain_db <= 0.05f) { - v.env_db = v.sustain_db; + v.env = v.sustain_lin; v.env_stage = (v.sustain_db >= 90.0f) ? EnvStage::Off : EnvStage::Sustain; } else { - v.env_db += v.decay_rate_db * dt; - if (v.env_db >= v.sustain_db) { - v.env_db = v.sustain_db; + v.env *= v.decay_mul; + if (v.env <= v.sustain_lin || v.env <= 3.16228e-5f) { + v.env = v.sustain_lin; v.env_stage = (v.sustain_db >= 90.0f) ? EnvStage::Off : EnvStage::Sustain; } } - v.env = (v.env_db >= 90.0f) ? 0.0f : std::exp(-v.env_db * kDbToLn); if (v.env_stage == EnvStage::Off) v.active = false; break; case EnvStage::Sustain: - v.env_db = v.sustain_db; - v.env = (v.sustain_db >= 90.0f) ? 0.0f : std::exp(-v.env_db * kDbToLn); + v.env = v.sustain_lin; break; case EnvStage::Release: - v.env_db += v.release_rate_db * dt; - if (v.env_db >= 84.0f) { + v.env *= v.release_mul; + if (v.env <= 6.309573e-5f) { v.env = 0.0f; - v.env_db = 96.0f; v.env_stage = EnvStage::Off; v.active = false; - } else { - v.env = std::exp(-v.env_db * kDbToLn); } break; } } float SfSynth::sample_osc(WtVoice& v, float dt) { - float bend_mul = std::pow(2.0f, channels_[v.channel].pitch_bend_semitones / 12.0f); + const float bend_mul = channels_[v.channel].bend_mul; if (v.rom_kind == RomWaveKind::None) { - if (!sf_ || v.sample_idx < 0 || static_cast(v.sample_idx) >= sf_->samples.size()) { + if (!sf_ || v.sample_idx < 0 || static_cast(v.sample_idx) >= sf_->samples.size() || + sf_->sample_pool.empty() || !std::isfinite(v.pos) || v.pos < 0.0 || + !std::isfinite(v.step) || v.step <= 0.0) { v.active = false; return 0.0f; } + const uint32_t safe_end = std::min(v.s_end, static_cast(sf_->sample_pool.size())); uint32_t i0 = static_cast(v.pos); - if (i0 + 1 >= v.s_end) { - if (v.loop && v.l_end > v.l_start + 1 && v.l_end <= v.s_end) { - v.pos = static_cast(v.l_start); - i0 = v.l_start; + if (i0 + 1 >= safe_end) { + if (v.loop && v.l_end > v.l_start + 1 && v.l_end <= safe_end) { + const double span = static_cast(v.l_end - v.l_start); + v.pos = static_cast(v.l_start) + std::fmod(v.pos - static_cast(v.l_start), span); + i0 = static_cast(v.pos); + if (i0 + 1 >= safe_end) { + v.pos = static_cast(v.l_start); + i0 = v.l_start; + } } else { v.active = false; return 0.0f; @@ -730,8 +777,10 @@ float SfSynth::sample_osc(WtVoice& v, float dt) { float out = s0 + (s1 - s0) * frac; v.pos += v.step * bend_mul; - if (v.loop && v.l_end > v.l_start + 1 && v.pos >= static_cast(v.l_end)) { - v.pos -= static_cast(v.l_end - v.l_start); + if (v.loop && v.l_end > v.l_start + 1 && v.l_end <= safe_end && + v.pos >= static_cast(v.l_end)) { + const double span = static_cast(v.l_end - v.l_start); + v.pos = static_cast(v.l_start) + std::fmod(v.pos - static_cast(v.l_start), span); } return out; } @@ -754,7 +803,7 @@ float SfSynth::sample_osc(WtVoice& v, float dt) { if (v.chorus_send > 0.05f) { v.chorus_phase += 1.8 * static_cast(dt); if (v.chorus_phase >= 1.0) v.chorus_phase -= 1.0; - double detune = 1.0 + 0.0055 * (1.0 + 0.4 * std::sin(v.chorus_phase * kTwoPi)); + double detune = 1.0 + 0.0055 * (1.0 + 0.4 * fast_sin_phase(v.chorus_phase)); v.pos2 += inc * detune; v.pos2 -= std::floor(v.pos2); float sub_s = blep_saw(v.pos2, inc * detune); @@ -766,21 +815,22 @@ float SfSynth::sample_osc(WtVoice& v, float dt) { } case RomWaveKind::Bell: { float decay_harm = std::max(0.0f, v.env * v.env); - float body = static_cast(std::sin(ph * kTwoPi)); - float overtone = static_cast(std::sin(ph * 3.01 * kTwoPi + 0.45 * std::sin(ph * 2.0 * kTwoPi))); + float body = fast_sin_phase(ph); + float mod = 0.45f * fast_sin_phase(ph * 2.0) / static_cast(kTwoPi); + float overtone = fast_sin_phase(ph * 3.01 + static_cast(mod)); out = 0.78f * body + 0.28f * decay_harm * overtone; break; } case RomWaveKind::Perc: { float click = next_noise(v.noise_state) * std::max(0.0f, v.env * v.env * v.env); - float tone = static_cast(std::sin(ph * kTwoPi)); + float tone = fast_sin_phase(ph); out = 0.82f * tone + 0.18f * click; break; } case RomWaveKind::Sine: { // Woody *SineWave with brisk attack overtone for AgogoLoTone - float wood = static_cast(std::sin(ph * 4.18 * kTwoPi)) * (v.env * v.env); - out = 0.88f * static_cast(std::sin(ph * kTwoPi)) + 0.16f * wood; + float wood = fast_sin_phase(ph * 4.18) * (v.env * v.env); + out = 0.88f * fast_sin_phase(ph) + 0.16f * wood; break; } case RomWaveKind::GmKey: { @@ -796,10 +846,10 @@ float SfSynth::sample_osc(WtVoice& v, float dt) { break; } case RomWaveKind::GmOrgan: { - float f1 = static_cast(std::sin(ph * kTwoPi)); - float f2 = static_cast(std::sin(ph * 2.0 * kTwoPi)); - float f3 = static_cast(std::sin(ph * 3.0 * kTwoPi)); - float f4 = static_cast(std::sin(ph * 4.0 * kTwoPi)); + float f1 = fast_sin_phase(ph); + float f2 = fast_sin_phase(ph * 2.0); + float f3 = fast_sin_phase(ph * 3.0); + float f4 = fast_sin_phase(ph * 4.0); out = 0.48f * f1 + 0.28f * f2 + 0.16f * f3 * v.gm_bright + 0.10f * f4 * v.gm_bright; break; } @@ -815,7 +865,7 @@ float SfSynth::sample_osc(WtVoice& v, float dt) { case RomWaveKind::GmBass: { float saw_w = blep_saw(ph, inc); float tri_w = 1.0f - 4.0f * static_cast(std::abs(ph - 0.5)); - float sub_w = static_cast(std::sin(ph * 0.5 * kTwoPi)); + float sub_w = fast_sin_phase(ph * 0.5); out = 0.55f * tri_w + 0.35f * v.gm_bright * saw_w + 0.25f * sub_w; break; } @@ -833,11 +883,11 @@ float SfSynth::sample_osc(WtVoice& v, float dt) { v.drum_pitch_hz += (v.drum_end_hz - v.drum_pitch_hz) * std::min(1.0f, v.drum_sweep_rate * dt); v.step = v.drum_pitch_hz / static_cast(sample_rate_); - float tone = static_cast(std::sin(ph * kTwoPi)); + float tone = fast_sin_phase(ph); if (v.drum_pitch_hz > 500.0f) { // Metallic cymbal / hi-hat partials - float m1 = (std::sin(ph * 1.47 * kTwoPi) > 0.0) ? 0.5f : -0.5f; - float m2 = (std::sin(ph * 2.13 * kTwoPi) > 0.0) ? 0.5f : -0.5f; + float m1 = (fast_sin_phase(ph * 1.47) > 0.0f) ? 0.5f : -0.5f; + float m2 = (fast_sin_phase(ph * 2.13) > 0.0f) ? 0.5f : -0.5f; tone = 0.5f * (m1 + m2); } float n = next_noise(v.noise_state); @@ -845,14 +895,16 @@ float SfSynth::sample_osc(WtVoice& v, float dt) { break; } default: - out = static_cast(std::sin(ph * kTwoPi)); + out = fast_sin_phase(ph); break; } return out; } void SfSynth::render(float* stereo_out, int frames) { - const float dt = 1.0f / static_cast(sample_rate_); + if (!stereo_out || frames <= 0) return; + const float sr_f = static_cast(sample_rate_); + const float dt = 1.0f / sr_f; const float cc_alpha = 1.0f - std::exp(-dt / 0.005f); for (int f = 0; f < frames; ++f) { @@ -865,7 +917,7 @@ void SfSynth::render(float* stereo_out, int frames) { float rev_in_l = 0.0f, rev_in_r = 0.0f; for (auto& v : voices_) { - if (!v.active) continue; + if (!v.active || v.channel >= 16) continue; step_env(v, dt); if (!v.active) continue; @@ -873,11 +925,16 @@ void SfSynth::render(float* stereo_out, int frames) { if (!v.active) continue; if (v.has_filter) { - float fc = v.filter_fc_hz; if (v.mod_env_to_filter_cents != 0.0f) { - fc *= std::pow(2.0f, (v.env * v.mod_env_to_filter_cents) / 1200.0f); + if (v.filter_mod_counter == 0) { + float fc = v.filter_fc_hz * std::pow(2.0f, (v.env * v.mod_env_to_filter_cents) / 1200.0f); + v.svf_f_cached = compute_svf_f(fc, sr_f); + } + v.filter_mod_counter = (v.filter_mod_counter + 1u) & 7u; + sig = apply_svf_2x_coeff(sig, v.svf_f_cached, v.svf_damp, v.svf_lp, v.svf_bp); + } else { + sig = apply_svf_2x_coeff(sig, v.svf_f_static, v.svf_damp, v.svf_lp, v.svf_bp); } - sig = apply_svf_2x(sig, fc, v.filter_q_damp, sample_rate_, v.svf_lp, v.svf_bp); } sig *= v.env; @@ -885,10 +942,8 @@ void SfSynth::render(float* stereo_out, int frames) { const ChState& cs = channels_[v.channel]; float cc_dyn = (cs.vol_smooth * cs.vol_smooth) * (cs.expr_smooth * cs.expr_smooth); float g = v.base_gain * cc_dyn; - float gl = std::sqrt(0.5f * (1.0f - v.pan)); - float gr = std::sqrt(0.5f * (1.0f + v.pan)); - float vl = sig * g * gl; - float vr = sig * g * gr; + float vl = sig * g * v.pan_l; + float vr = sig * g * v.pan_r; l += vl; r += vr; rev_in_l += vl * v.reverb_send; @@ -904,6 +959,8 @@ void SfSynth::render(float* stereo_out, int frames) { float dr = rev_buf_r_[i][rev_idx_r_[i]]; rev_lp_l_[i] += 0.35f * (dl - rev_lp_l_[i]); rev_lp_r_[i] += 0.35f * (dr - rev_lp_r_[i]); + if (std::abs(rev_lp_l_[i]) < 1e-20f) rev_lp_l_[i] = 0.0f; + if (std::abs(rev_lp_r_[i]) < 1e-20f) rev_lp_r_[i] = 0.0f; rev_buf_l_[i][rev_idx_l_[i]] = rev_in_l * 0.5f + rev_lp_r_[i] * 0.52f; rev_buf_r_[i][rev_idx_r_[i]] = rev_in_r * 0.5f + rev_lp_l_[i] * 0.52f; if (++rev_idx_l_[i] >= rev_buf_l_[i].size()) rev_idx_l_[i] = 0; diff --git a/src/audio/sf_synth.hpp b/src/audio/sf_synth.hpp index afb8479..4c60fcb 100644 --- a/src/audio/sf_synth.hpp +++ b/src/audio/sf_synth.hpp @@ -74,6 +74,8 @@ private: float base_gain = 0.0f; float pan = 0.0f; + float pan_l = 0.70710678f; + float pan_r = 0.70710678f; float chorus_send = 0.0f; float reverb_send = 0.0f; double chorus_phase = 0.0; @@ -89,12 +91,20 @@ private: float decay_rate_db = 0.0f; float sustain_db = 0.0f; float release_rate_db = 600.0f; + float attack_alpha = 0.0f; + float decay_mul = 1.0f; + float sustain_lin = 0.0f; + float release_mul = 1.0f; // 2x-oversampled SVF resonant low-pass filter bool has_filter = false; float filter_fc_hz = 20000.0f; float filter_q_damp = 1.414f; float mod_env_to_filter_cents = 0.0f; + float svf_f_static = 0.5f; + float svf_damp = 1.414f; + float svf_f_cached = 0.5f; + uint8_t filter_mod_counter = 0; float svf_lp = 0.0f; float svf_bp = 0.0f; @@ -117,6 +127,7 @@ private: float expr_smooth = 1.0f; float pan = 0.0f; float pitch_bend_semitones = 0.0f; + float bend_mul = 1.0f; float reverb_cc = 0.15f; float chorus_cc = 0.0f; bool sustain_pedal = false; @@ -124,6 +135,7 @@ private: static RomWaveKind classify_rom_sample(const std::string& name); int alloc_voice(); + void finalize_voice_cache(WtVoice& v); void spawn_sf_zone(uint8_t ch, uint8_t key, uint8_t vel, const assets::SoundFontZone& z); void spawn_gm_voice(uint8_t ch, uint8_t key, uint8_t vel); void step_env(WtVoice& v, float dt); diff --git a/src/audio/xmidi_player.cpp b/src/audio/xmidi_player.cpp index 8f95e2a..a267b6c 100644 --- a/src/audio/xmidi_player.cpp +++ b/src/audio/xmidi_player.cpp @@ -36,7 +36,8 @@ void XmidiPlayer::process_tick(IMidiSynth& synth) { const auto& evs = seq_->events; // Fast-forward controller/program/pitch-bend setup before requested start_tick if (pending_start_tick_ > 0) { - while (event_cursor_ < evs.size() && evs[event_cursor_].tick < pending_start_tick_) { + while (event_cursor_ < evs.size() && + static_cast(evs[event_cursor_].tick) < pending_start_tick_) { const auto& ev = evs[event_cursor_++]; if (ev.status == 0xFFu) continue; uint8_t hi = ev.status & 0xF0u; @@ -73,7 +74,8 @@ void XmidiPlayer::process_tick(IMidiSynth& synth) { }; // Fire events at or before current_tick_ - while (event_cursor_ < evs.size() && evs[event_cursor_].tick <= current_tick_) { + while (event_cursor_ < evs.size() && + static_cast(evs[event_cursor_].tick) <= current_tick_) { const auto& ev = evs[event_cursor_++]; if (ev.status == 0xFFu) { continue; @@ -100,15 +102,25 @@ void XmidiPlayer::process_tick(IMidiSynth& synth) { } synth.note_on(ch, ev.data1, ev.data2); if (ev.duration_ticks > 0) { + PendingNoteOff* slot = nullptr; + PendingNoteOff* oldest = ¬e_offs_[0]; for (auto& n : note_offs_) { if (!n.active) { - n.active = true; - n.off_tick = current_tick_ + ev.duration_ticks; - n.channel = ch; - n.key = ev.data1; + slot = &n; break; } + if (n.off_tick < oldest->off_tick) { + oldest = &n; + } } + if (!slot) { + synth.note_off(oldest->channel, oldest->key); + slot = oldest; + } + slot->active = true; + slot->off_tick = current_tick_ + static_cast(ev.duration_ticks); + slot->channel = ch; + slot->key = ev.data1; } } break; @@ -163,7 +175,7 @@ void XmidiPlayer::process_tick(IMidiSynth& synth) { } ++current_tick_; - if (event_cursor_ >= evs.size() && current_tick_ > seq_->total_ticks) { + if (event_cursor_ >= evs.size() && current_tick_ > static_cast(seq_->total_ticks)) { if (loop_) { synth.all_notes_off(); event_cursor_ = 0; @@ -177,7 +189,7 @@ void XmidiPlayer::process_tick(IMidiSynth& synth) { } void XmidiPlayer::render(float* stereo_out, int frames, IMidiSynth& synth) { - if (!playing_ || !seq_) return; + if (!stereo_out || frames <= 0 || !playing_ || !seq_) return; int offset = 0; while (offset < frames && playing_) { diff --git a/src/audio/xmidi_player.hpp b/src/audio/xmidi_player.hpp index 348dc51..4582963 100644 --- a/src/audio/xmidi_player.hpp +++ b/src/audio/xmidi_player.hpp @@ -24,14 +24,14 @@ public: private: struct PendingNoteOff { bool active = false; - uint32_t off_tick = 0; + uint64_t off_tick = 0; uint8_t channel = 0; uint8_t key = 0; }; struct XmiLoopFrame { size_t event_idx = 0; - uint32_t tick = 0; + uint64_t tick = 0; uint8_t remaining = 0; bool infinite = true; }; @@ -44,8 +44,8 @@ private: int sample_rate_ = 48000; size_t event_cursor_ = 0; - uint32_t current_tick_ = 0; - uint32_t pending_start_tick_ = 0; + uint64_t current_tick_ = 0; + uint64_t pending_start_tick_ = 0; double samples_per_tick_ = 400.0; // 48000 / 120 Hz default double sample_accum_ = 0.0; diff --git a/src/core/config.cpp b/src/core/config.cpp index 15d31d4..60b0c07 100644 --- a/src/core/config.cpp +++ b/src/core/config.cpp @@ -1,7 +1,9 @@ #include "core/config.hpp" +#include #include #include +#include #include #include #include @@ -28,12 +30,31 @@ int parse_int(const std::string& v, int def) { float parse_float(const std::string& v, float def) { try { - return std::stof(v); + float val = std::stof(v); + return std::isfinite(val) ? val : def; } catch (...) { return def; } } +int parse_scancode(const std::string& v, int def) { + int code = parse_int(v, def); + return (code >= 0 && code < SDL_NUM_SCANCODES) ? code : def; +} + +std::string sanitize_path_value(const std::string& raw) { + std::string out; + out.reserve(std::min(raw.size(), 512)); + for (unsigned char c : trim(raw)) { + if (c < 0x20 || c == 0x7F) { + return {}; + } + out.push_back(static_cast(c)); + if (out.size() >= 512) break; + } + return out; +} + bool parse_bool(const std::string& v, bool def) { std::string l = v; for (char& c : l) c = static_cast(std::tolower(static_cast(c))); @@ -101,33 +122,35 @@ bool GameConfig::load(const std::filesystem::path& path) { if (auto* v = get("audio.sfx_volume")) sfx_volume = std::clamp(parse_float(*v, sfx_volume), 0.0f, 1.0f); if (auto* v = get("audio.music_volume")) music_volume = std::clamp(parse_float(*v, music_volume), 0.0f, 1.0f); if (auto* v = get("audio.mute_on_focus_loss")) mute_on_focus_loss = parse_bool(*v, mute_on_focus_loss); - if (auto* v = get("audio.custom_soundfont_path")) custom_soundfont_path = *v; + if (auto* v = get("audio.custom_soundfont_path")) custom_soundfont_path = sanitize_path_value(*v); if (auto* v = get("controls.gamepad_deadzone")) gamepad_deadzone = std::clamp(parse_float(*v, gamepad_deadzone), 0.0f, 0.5f); if (auto* v = get("controls.steering_sensitivity")) steering_sensitivity = std::clamp(parse_float(*v, steering_sensitivity), 0.25f, 3.0f); if (auto* v = get("controls.steering_curve")) steering_curve = std::clamp(parse_float(*v, steering_curve), 0.5f, 3.0f); if (auto* v = get("controls.rumble_enabled")) rumble_enabled = parse_bool(*v, rumble_enabled); if (auto* v = get("controls.mouse_steering")) mouse_steering = parse_bool(*v, mouse_steering); - if (auto* v = get("controls.p1_gamepad_index")) p1_gamepad_index = parse_int(*v, p1_gamepad_index); - if (auto* v = get("controls.p2_gamepad_index")) p2_gamepad_index = parse_int(*v, p2_gamepad_index); + if (auto* v = get("controls.p1_gamepad_index")) p1_gamepad_index = std::clamp(parse_int(*v, p1_gamepad_index), -1, 32); + if (auto* v = get("controls.p2_gamepad_index")) p2_gamepad_index = std::clamp(parse_int(*v, p2_gamepad_index), -1, 32); - if (auto* v = get("keys.steer_left")) keys.steer_left = parse_int(*v, keys.steer_left); - if (auto* v = get("keys.steer_right")) keys.steer_right = parse_int(*v, keys.steer_right); - if (auto* v = get("keys.accelerate")) keys.accelerate = parse_int(*v, keys.accelerate); - if (auto* v = get("keys.brake")) keys.brake = parse_int(*v, keys.brake); - if (auto* v = get("keys.boost")) keys.boost = parse_int(*v, keys.boost); - if (auto* v = get("keys.fire_minigun")) keys.fire_minigun = parse_int(*v, keys.fire_minigun); - if (auto* v = get("keys.fire_missile")) keys.fire_missile = parse_int(*v, keys.fire_missile); - if (auto* v = get("keys.autopilot")) keys.autopilot = parse_int(*v, keys.autopilot); - if (auto* v = get("keys.camera_view")) keys.camera_view = parse_int(*v, keys.camera_view); - if (auto* v = get("keys.hud_toggle")) keys.hud_toggle = parse_int(*v, keys.hud_toggle); - if (auto* v = get("keys.p2_steer_left")) keys.p2_steer_left = parse_int(*v, keys.p2_steer_left); - if (auto* v = get("keys.p2_steer_right")) keys.p2_steer_right = parse_int(*v, keys.p2_steer_right); - if (auto* v = get("keys.p2_accelerate")) keys.p2_accelerate = parse_int(*v, keys.p2_accelerate); - if (auto* v = get("keys.p2_brake")) keys.p2_brake = parse_int(*v, keys.p2_brake); - if (auto* v = get("keys.p2_boost")) keys.p2_boost = parse_int(*v, keys.p2_boost); - if (auto* v = get("keys.p2_fire_minigun")) keys.p2_fire_minigun = parse_int(*v, keys.p2_fire_minigun); - if (auto* v = get("keys.p2_fire_missile")) keys.p2_fire_missile = parse_int(*v, keys.p2_fire_missile); + if (auto* v = get("keys.steer_left")) keys.steer_left = parse_scancode(*v, keys.steer_left); + if (auto* v = get("keys.steer_right")) keys.steer_right = parse_scancode(*v, keys.steer_right); + if (auto* v = get("keys.accelerate")) keys.accelerate = parse_scancode(*v, keys.accelerate); + if (auto* v = get("keys.brake")) keys.brake = parse_scancode(*v, keys.brake); + if (auto* v = get("keys.boost")) keys.boost = parse_scancode(*v, keys.boost); + if (auto* v = get("keys.fire_minigun")) keys.fire_minigun = parse_scancode(*v, keys.fire_minigun); + if (auto* v = get("keys.fire_missile")) keys.fire_missile = parse_scancode(*v, keys.fire_missile); + if (auto* v = get("keys.autopilot")) keys.autopilot = parse_scancode(*v, keys.autopilot); + if (auto* v = get("keys.camera_view")) keys.camera_view = parse_scancode(*v, keys.camera_view); + if (auto* v = get("keys.hud_toggle")) keys.hud_toggle = parse_scancode(*v, keys.hud_toggle); + if (auto* v = get("keys.recover")) keys.recover = parse_scancode(*v, keys.recover); + if (auto* v = get("keys.p2_steer_left")) keys.p2_steer_left = parse_scancode(*v, keys.p2_steer_left); + if (auto* v = get("keys.p2_steer_right")) keys.p2_steer_right = parse_scancode(*v, keys.p2_steer_right); + if (auto* v = get("keys.p2_accelerate")) keys.p2_accelerate = parse_scancode(*v, keys.p2_accelerate); + if (auto* v = get("keys.p2_brake")) keys.p2_brake = parse_scancode(*v, keys.p2_brake); + if (auto* v = get("keys.p2_boost")) keys.p2_boost = parse_scancode(*v, keys.p2_boost); + if (auto* v = get("keys.p2_fire_minigun")) keys.p2_fire_minigun = parse_scancode(*v, keys.p2_fire_minigun); + if (auto* v = get("keys.p2_fire_missile")) keys.p2_fire_missile = parse_scancode(*v, keys.p2_fire_missile); + if (auto* v = get("keys.p2_recover")) keys.p2_recover = parse_scancode(*v, keys.p2_recover); if (auto* v = get("game.player_name")) player_name = sanitize_pilot_name(*v, "PLAYER"); if (auto* v = get("game.player2_name")) player2_name = sanitize_pilot_name(*v, "PLAYER 2"); @@ -177,7 +200,7 @@ bool GameConfig::save(const std::filesystem::path& path) const { << "sfx_volume=" << sfx_volume << "\n" << "music_volume=" << music_volume << "\n" << "mute_on_focus_loss=" << (mute_on_focus_loss ? 1 : 0) << "\n" - << "custom_soundfont_path=" << custom_soundfont_path << "\n\n" + << "custom_soundfont_path=" << sanitize_path_value(custom_soundfont_path) << "\n\n" << "[controls]\n" << "gamepad_deadzone=" << gamepad_deadzone << "\n" @@ -199,13 +222,15 @@ bool GameConfig::save(const std::filesystem::path& path) const { << "autopilot=" << keys.autopilot << "\n" << "camera_view=" << keys.camera_view << "\n" << "hud_toggle=" << keys.hud_toggle << "\n" + << "recover=" << keys.recover << "\n" << "p2_steer_left=" << keys.p2_steer_left << "\n" << "p2_steer_right=" << keys.p2_steer_right << "\n" << "p2_accelerate=" << keys.p2_accelerate << "\n" << "p2_brake=" << keys.p2_brake << "\n" << "p2_boost=" << keys.p2_boost << "\n" << "p2_fire_minigun=" << keys.p2_fire_minigun << "\n" - << "p2_fire_missile=" << keys.p2_fire_missile << "\n\n" + << "p2_fire_missile=" << keys.p2_fire_missile << "\n" + << "p2_recover=" << keys.p2_recover << "\n\n" << "[game]\n" << "player_name=" << player_name << "\n" diff --git a/src/core/config.hpp b/src/core/config.hpp index 256923b..3091ced 100644 --- a/src/core/config.hpp +++ b/src/core/config.hpp @@ -36,8 +36,9 @@ struct KeyBindings { int autopilot = 20; // SDL_SCANCODE_Q int camera_view = 6; // SDL_SCANCODE_C int hud_toggle = 11; // SDL_SCANCODE_H + int recover = 21; // SDL_SCANCODE_R - // Player 2 default split-screen keys (Arrows + RCtrl/RShift/Enter) + // Player 2 default split-screen keys (Arrows + RCtrl/RShift/Enter/Backspace) int p2_steer_left = 80; // SDL_SCANCODE_LEFT int p2_steer_right = 79; // SDL_SCANCODE_RIGHT int p2_accelerate = 82; // SDL_SCANCODE_UP @@ -45,6 +46,7 @@ struct KeyBindings { int p2_boost = 229; // SDL_SCANCODE_RSHIFT int p2_fire_minigun = 228; // SDL_SCANCODE_RCTRL int p2_fire_missile = 40; // SDL_SCANCODE_RETURN + int p2_recover = 42; // SDL_SCANCODE_BACKSPACE }; struct GameConfig { diff --git a/src/core/log.hpp b/src/core/log.hpp index f31a314..189388d 100644 --- a/src/core/log.hpp +++ b/src/core/log.hpp @@ -17,6 +17,9 @@ inline Level& min_level() { return lvl; } +#if defined(__GNUC__) || defined(__clang__) +__attribute__((format(printf, 3, 4))) +#endif inline void write(Level lvl, const char* tag, const char* fmt, ...) { if (static_cast(lvl) < static_cast(min_level())) { return; diff --git a/src/core/math.hpp b/src/core/math.hpp index 18177c5..fe488ff 100644 --- a/src/core/math.hpp +++ b/src/core/math.hpp @@ -14,9 +14,8 @@ inline float deg_to_rad(float deg) { return deg * (kPi / 180.0f); } inline float rad_to_deg(float rad) { return rad * (180.0f / kPi); } inline float wrap_angle(float a) { - while (a > kPi) a -= kTwoPi; - while (a < -kPi) a += kTwoPi; - return a; + if (!std::isfinite(a)) return 0.0f; + return std::remainder(a, kTwoPi); } inline float lerp(float a, float b, float t) { return a + (b - a) * t; } @@ -128,6 +127,11 @@ struct Mat4 { static Mat4 perspective(float fovy_rad, float aspect, float znear, float zfar) { Mat4 r; + if (!std::isfinite(fovy_rad)) fovy_rad = 1.0f; + fovy_rad = std::clamp(fovy_rad, 0.05f, kPi - 0.05f); + if (!std::isfinite(aspect) || aspect <= 1e-4f) aspect = 1.0f; + if (!std::isfinite(znear) || znear < 1e-4f) znear = 0.1f; + if (!std::isfinite(zfar) || zfar <= znear + 1e-3f) zfar = znear + 1.0f; float f = 1.0f / std::tan(fovy_rad * 0.5f); r.m[0] = f / std::max(aspect, 0.001f); r.m[5] = f; diff --git a/src/core/vfs.cpp b/src/core/vfs.cpp index 926d6b0..ceb2835 100644 --- a/src/core/vfs.cpp +++ b/src/core/vfs.cpp @@ -52,6 +52,21 @@ void append_unique(std::vector& out, const std::filesyste } } +bool is_within_root(const std::filesystem::path& canon_root, const std::filesystem::path& candidate) { + if (canon_root.empty()) return false; + std::error_code ec; + auto canon_cand = std::filesystem::weakly_canonical(candidate, ec); + if (ec) return false; + auto it_r = canon_root.begin(); + auto it_c = canon_cand.begin(); + for (; it_r != canon_root.end(); ++it_r, ++it_c) { + if (it_c == canon_cand.end() || *it_r != *it_c) { + return false; + } + } + return true; +} + bool is_valid_hioctane_dir(const std::filesystem::path& p) { std::error_code ec; if (!std::filesystem::is_directory(p, ec)) { @@ -175,6 +190,7 @@ bool Vfs::init(const std::string& explicit_data_dir) { const auto candidates = build_search_paths(explicit_data_dir, cwd, base_dir, pref_dir_); data_root_.clear(); + index_.clear(); for (const auto& c : candidates) { if (is_valid_hioctane_dir(c)) { data_root_ = std::filesystem::weakly_canonical(c, ec); @@ -187,40 +203,64 @@ bool Vfs::init(const std::string& explicit_data_dir) { LOG_ERROR("Could not locate Top-Octane asset directory (checked --data-dir, HIOCTANE_DATA, ./data, and XDG data dirs)"); return false; } + rebuild_index(); LOG_INFO("Using read-only asset directory: %s", data_root_.string().c_str()); LOG_INFO("Using user save/config directory: %s", pref_dir_.string().c_str()); return true; } -bool Vfs::resolve(const std::string& rel_path, std::filesystem::path& out_path) const { - if (data_root_.empty()) return false; - std::filesystem::path cur = data_root_; +void Vfs::rebuild_index() { + index_.clear(); + if (data_root_.empty()) return; std::error_code ec; - - for (const std::string& part : split_rel_path(rel_path)) { - std::filesystem::path direct = cur / part; - if (std::filesystem::exists(direct, ec)) { - cur = direct; - continue; + for (std::filesystem::recursive_directory_iterator it( + data_root_, std::filesystem::directory_options::skip_permission_denied, ec), + end; + !ec && it != end; it.increment(ec)) { + if (!it->is_regular_file(ec)) continue; + if (!is_within_root(data_root_, it->path())) continue; + std::filesystem::path rel = it->path().lexically_relative(data_root_); + std::string key; + for (const auto& part : rel) { + std::string s = to_lower_ascii(part.string()); + if (s.empty() || s == ".") continue; + if (!key.empty()) key.push_back('/'); + key += s; } - std::string target = to_lower_ascii(part); - bool matched = false; - if (std::filesystem::is_directory(cur, ec)) { - for (const auto& ent : std::filesystem::directory_iterator(cur, ec)) { - if (to_lower_ascii(ent.path().filename().string()) == target) { - cur = ent.path(); - matched = true; - break; - } - } - } - if (!matched) { - return false; + if (!key.empty()) { + index_.emplace(std::move(key), it->path()); } } +} - out_path = cur; - return std::filesystem::is_regular_file(out_path, ec); +bool Vfs::resolve(const std::string& rel_path, std::filesystem::path& out_path) const { + if (data_root_.empty() || rel_path.empty()) return false; + if (rel_path.find('\0') != std::string::npos) return false; + if (rel_path[0] == '/' || rel_path[0] == '\\') return false; + if (rel_path.find(':') != std::string::npos) return false; + + const auto parts = split_rel_path(rel_path); + if (parts.empty()) return false; + + std::string key; + for (const std::string& part : parts) { + if (part == "." || part == "..") { + return false; + } + if (!key.empty()) key.push_back('/'); + key += to_lower_ascii(part); + } + + auto it = index_.find(key); + if (it == index_.end()) { + return false; + } + std::error_code ec; + if (!is_within_root(data_root_, it->second) || !std::filesystem::is_regular_file(it->second, ec)) { + return false; + } + out_path = it->second; + return true; } bool Vfs::exists(const std::string& rel_path) const { @@ -236,17 +276,28 @@ bool Vfs::read_file(const std::string& rel_path, std::vector& out_data) return read_raw_file(p, out_data); } -bool Vfs::read_raw_file(const std::filesystem::path& path, std::vector& out_data) { - std::ifstream ifs(path, std::ios::binary | std::ios::ate); - if (!ifs) return false; - const auto sz = ifs.tellg(); - if (sz < 0) return false; - out_data.resize(static_cast(sz)); - ifs.seekg(0, std::ios::beg); - if (sz > 0 && !ifs.read(reinterpret_cast(out_data.data()), sz)) { - out_data.clear(); +bool Vfs::read_raw_file(const std::filesystem::path& path, std::vector& out_data, + size_t max_bytes) { + out_data.clear(); + std::error_code ec; + if (!std::filesystem::is_regular_file(path, ec)) { return false; } + const uintmax_t fsz = std::filesystem::file_size(path, ec); + if (ec || fsz > static_cast(max_bytes)) { + return false; + } + std::ifstream ifs(path, std::ios::binary); + if (!ifs) return false; + const size_t sz = static_cast(fsz); + out_data.resize(sz); + if (sz > 0) { + ifs.read(reinterpret_cast(out_data.data()), static_cast(sz)); + if (!ifs || static_cast(ifs.gcount()) != sz) { + out_data.clear(); + return false; + } + } return true; } diff --git a/src/core/vfs.hpp b/src/core/vfs.hpp index 2d4d5f1..1aae6f5 100644 --- a/src/core/vfs.hpp +++ b/src/core/vfs.hpp @@ -3,12 +3,15 @@ #include #include #include +#include #include namespace top_octane { class Vfs { public: + static constexpr size_t kMaxReadBytes = 64u * 1024u * 1024u; + // Initializes read-only asset lookup from explicit path, HIOCTANE_DATA env, ./data, ./HiOctane, or installed/XDG data dirs bool init(const std::string& explicit_data_dir = ""); @@ -28,12 +31,16 @@ public: bool read_file(const std::string& rel_path, std::vector& out_data) const; // Static binary helper for reading arbitrary paths - static bool read_raw_file(const std::filesystem::path& path, std::vector& out_data); + static bool read_raw_file(const std::filesystem::path& path, std::vector& out_data, + size_t max_bytes = kMaxReadBytes); static bool write_raw_file(const std::filesystem::path& path, const void* data, size_t size); private: + void rebuild_index(); + std::filesystem::path data_root_; std::filesystem::path pref_dir_; + std::unordered_map index_; }; } // namespace top_octane diff --git a/src/game/game_app.cpp b/src/game/game_app.cpp index 7f57363..d9b5164 100644 --- a/src/game/game_app.cpp +++ b/src/game/game_app.cpp @@ -88,7 +88,7 @@ bool project_world_to_screen(const Vec3& wp, const Mat4& vp, int vx, int vy, int if (cw <= 0.1f) return false; float ndcx = cx / cw; float ndcy = cy / cw; - if (ndcx < -1.1f || ndcx > 1.1f || ndcy < -1.1f || ndcy > 1.1f) return false; + if (ndcx < -1.0f || ndcx > 1.0f || ndcy < -1.0f || ndcy > 1.0f) return false; out_sx = static_cast(vx) + (ndcx * 0.5f + 0.5f) * static_cast(vw); // Convert GL bottom-up vy into top-down UI Y float gl_y = static_cast(vy) + (ndcy * 0.5f + 0.5f) * static_cast(vh); @@ -133,20 +133,22 @@ void append_charger_lights(const assets::LevelData& level, double time_s, Vec3 col(0.22f, 0.70f, 1.00f); // Fuel blue if (pad.type == assets::ChargerType::Shield) col = Vec3(0.15f, 1.00f, 0.48f); else if (pad.type == assets::ChargerType::Ammo) col = Vec3(1.00f, 0.82f, 0.20f); - float y = level.sample_height_world(pad.cx, pad.cz) + 0.90f; + float y = level.sample_entity_surface_y(pad.cx, pad.cz) + 0.90f; float rad = std::max(pad.half_x, pad.half_z) + 3.4f; out.push_back({Vec3(pad.cx, y, pad.cz), rad, col, 0.72f * pulse}); } } -std::vector select_viewport_lights( - const std::vector& candidates, const Vec3& focus, float max_dist) { +void select_viewport_lights( + const std::vector& candidates, const Vec3& focus, float max_dist, + std::vector& out) { + out.clear(); struct Scored { float score = 0.0f; size_t idx = 0; }; - std::vector ranked; - ranked.reserve(candidates.size()); + static std::vector ranked; + ranked.clear(); for (size_t i = 0; i < candidates.size(); ++i) { const auto& l = candidates[i]; float d2 = (l.pos - focus).len_sq(); @@ -160,28 +162,36 @@ std::vector select_viewport_lights( [](const Scored& a, const Scored& b) { return a.score > b.score; }); ranked.resize(kMaxLights); } - std::vector out; out.reserve(ranked.size()); for (const auto& s : ranked) { out.push_back(candidates[s.idx]); } - return out; } bool write_backbuffer_ppm(const std::string& path, int w, int h) { if (w <= 0 || h <= 0 || path.empty()) return false; std::vector rgb(static_cast(w) * static_cast(h) * 3u); + GLint prev_pack = 4; + glGetIntegerv(GL_PACK_ALIGNMENT, &prev_pack); glPixelStorei(GL_PACK_ALIGNMENT, 1); glReadPixels(0, 0, w, h, GL_RGB, GL_UNSIGNED_BYTE, rgb.data()); + glPixelStorei(GL_PACK_ALIGNMENT, prev_pack); + if (glGetError() != GL_NO_ERROR) { + return false; + } std::FILE* f = std::fopen(path.c_str(), "wb"); if (!f) return false; - std::fprintf(f, "P6\n%d %d\n255\n", w, h); + bool ok = (std::fprintf(f, "P6\n%d %d\n255\n", w, h) > 0); const size_t row_bytes = static_cast(w) * 3u; - for (int y = h - 1; y >= 0; --y) { - std::fwrite(rgb.data() + static_cast(y) * row_bytes, 1, row_bytes, f); + for (int y = h - 1; y >= 0 && ok; --y) { + if (std::fwrite(rgb.data() + static_cast(y) * row_bytes, 1, row_bytes, f) != row_bytes) { + ok = false; + } } - std::fclose(f); - return true; + if (std::fclose(f) != 0) { + ok = false; + } + return ok; } struct MenuLayout { @@ -272,6 +282,7 @@ bool GameApp::init(const LaunchOptions& opts) { LOG_ERROR("SDL_Init failed: %s", SDL_GetError()); return false; } + sdl_initialized_ = true; SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); @@ -328,11 +339,13 @@ bool GameApp::init(const LaunchOptions& opts) { world_ren_.ensure_model(vfs_, sim::model_key_for(v, t), palette_); } } - const char* extra_models[] = {"BAREL0-0", "CONE0-0", "SIGN0-0", "MARSH0-0", "RECOV0-0"}; + const char* extra_models[] = {"BAREL0-0", "CONE0-0", "CONE0-1", "SIGN0-0", "MARSH0-0", "RECOV0-0"}; for (const char* em : extra_models) { world_ren_.ensure_model(vfs_, em, palette_); } + initialized_ = true; + if (!opts.smoke_menu.empty()) { selected_track_ = (opts.start_track >= 1 && opts.start_track <= available_tracks_) ? opts.start_track @@ -365,11 +378,16 @@ bool GameApp::init(const LaunchOptions& opts) { return true; } +GameApp::~GameApp() { + shutdown(); +} + void GameApp::shutdown() { cancel_name_edit(); - if (opts_.smoke_test_frames == 0) { + if (initialized_ && opts_.smoke_test_frames == 0) { save_all_user_data(); } + flic_.close(); audio_.shutdown(); input_.shutdown(); ui_ren_.shutdown(); @@ -382,7 +400,17 @@ void GameApp::shutdown() { SDL_DestroyWindow(window_); window_ = nullptr; } - SDL_Quit(); + if (sdl_initialized_) { + SDL_Quit(); + sdl_initialized_ = false; + } + initialized_ = false; +} + +void GameApp::refresh_champ_slot_cache() { + for (size_t i = 0; i < champ_slot_saved_.size(); ++i) { + champ_slot_saved_[i] = ChampionshipState::slot_exists(vfs_.pref_dir(), static_cast(i)); + } } void GameApp::save_all_user_data() { @@ -503,11 +531,19 @@ void GameApp::update_name_edit() { void GameApp::enter_state(ScreenState s) { cancel_name_edit(); + const ScreenState prev_state = state_; + if (prev_state == ScreenState::Intro && s != ScreenState::Intro) { + flic_.close(); + } state_ = s; menu_cursor_ = (s == ScreenState::VehicleSelect) ? 1 : 0; rebind_slot_ = -1; input_.cancel_rebind(); + if (s == ScreenState::ChampionshipMenu) { + refresh_champ_slot_cache(); + } + if (s == ScreenState::Intro) { in_race_session_ = false; flic_.reset(); @@ -679,17 +715,6 @@ void GameApp::handle_sim_events() { } } race_sim_.clear_events(); - - std::vector dirty_rects; - bool columns_dirty = false; - if (race_sim_.consume_world_dirty(dirty_rects, columns_dirty)) { - for (const auto& r : dirty_rects) { - world_ren_.update_terrain_region(race_sim_.level(), r.x0, r.z0, r.x1, r.z1); - } - if (columns_dirty) { - world_ren_.rebuild_columns(race_sim_.level()); - } - } } void GameApp::update_racing_step(float dt) { @@ -780,7 +805,6 @@ void GameApp::update_track_viewer(float dt) { } void GameApp::update_menu(float dt) { - ui_time_ += dt; if (status_toast_timer_ > 0.0f) { status_toast_timer_ = std::max(0.0f, status_toast_timer_ - dt); } @@ -788,15 +812,19 @@ void GameApp::update_menu(float dt) { if (state_ == ScreenState::Intro) { intro_accum_ += static_cast(dt) * static_cast(flic_.fps()); + bool decoded_frame = false; while (intro_accum_ >= 1.0) { intro_accum_ -= 1.0; if (!flic_.step_frame()) { enter_state(ScreenState::Title); return; } - ui_ren_.update_stream_rgba(flic_.width(), flic_.height(), flic_.rgba().data()); + decoded_frame = true; dispatch_intro_cues(flic_.current_frame()); } + if (decoded_frame) { + ui_ren_.update_stream_rgba(flic_.width(), flic_.height(), flic_.rgba().data()); + } if (m.any_pressed) { audio_.stop_intro_sfx(-1); audio_.play_sfx("SELECT.WAV", 0.38f); @@ -871,6 +899,7 @@ void GameApp::update_menu(float dt) { } } else if (menu_cursor_ == 4) { if (champ_.save_slot(vfs_.pref_dir(), champ_slot_cursor_)) { + refresh_champ_slot_cache(); status_toast_ = "SAVED SLOT " + std::to_string(champ_slot_cursor_ + 1); status_toast_timer_ = 2.0f; } @@ -976,16 +1005,16 @@ void GameApp::update_menu(float dt) { if (rebind_slot_ >= 0) { int new_sc = 0; if (input_.consume_rebound_scancode(new_sc)) { - int* targets[17] = { + int* targets[19] = { &cfg_.keys.steer_left, &cfg_.keys.steer_right, &cfg_.keys.accelerate, &cfg_.keys.brake, &cfg_.keys.boost, &cfg_.keys.fire_minigun, &cfg_.keys.fire_missile, &cfg_.keys.autopilot, &cfg_.keys.camera_view, - &cfg_.keys.hud_toggle, + &cfg_.keys.hud_toggle, &cfg_.keys.recover, &cfg_.keys.p2_steer_left, &cfg_.keys.p2_steer_right, &cfg_.keys.p2_accelerate, &cfg_.keys.p2_brake, &cfg_.keys.p2_boost, &cfg_.keys.p2_fire_minigun, - &cfg_.keys.p2_fire_missile + &cfg_.keys.p2_fire_missile, &cfg_.keys.p2_recover }; - if (rebind_slot_ < 17) *targets[rebind_slot_] = new_sc; + if (rebind_slot_ < 19) *targets[rebind_slot_] = new_sc; rebind_slot_ = -1; audio_.play_sfx("SELECT.WAV", 0.38f); cfg_.save(vfs_.pref_dir() / "config.ini"); @@ -996,7 +1025,7 @@ void GameApp::update_menu(float dt) { } constexpr int kNumTabs = 7; - const int row_counts[kNumTabs] = {10, 7, 11, 8, 8, 8, 9}; + const int row_counts[kNumTabs] = {10, 7, 12, 9, 8, 8, 9}; int rows = row_counts[static_cast(opt_tab_)]; if (m.up) { menu_cursor_ = (menu_cursor_ + rows - 1) % rows; audio_.play_sfx("CHANGE.WAV", 0.32f); } if (m.down) { menu_cursor_ = (menu_cursor_ + 1) % rows; audio_.play_sfx("CHANGE.WAV", 0.32f); } @@ -1076,14 +1105,14 @@ void GameApp::update_menu(float dt) { } audio_.apply_config(cfg_, window_focused_); } else if (opt_tab_ == OptionsTab::ControlsP1) { - if (menu_cursor_ >= 1 && menu_cursor_ <= 10 && m.confirm) { + if (menu_cursor_ >= 1 && menu_cursor_ <= 11 && m.confirm) { rebind_slot_ = menu_cursor_ - 1; input_.start_rebind(); audio_.play_sfx("SELECT.WAV", 0.38f); } } else if (opt_tab_ == OptionsTab::ControlsP2) { - if (menu_cursor_ >= 1 && menu_cursor_ <= 7 && m.confirm) { - rebind_slot_ = 10 + (menu_cursor_ - 1); + if (menu_cursor_ >= 1 && menu_cursor_ <= 8 && m.confirm) { + rebind_slot_ = 11 + (menu_cursor_ - 1); input_.start_rebind(); audio_.play_sfx("SELECT.WAV", 0.38f); } @@ -1162,7 +1191,8 @@ void GameApp::update_menu(float dt) { } if (state_ == ScreenState::Paused) { - constexpr int kItems = 4; + const bool split_mode = (selected_mode_ == sim::GameMode::SplitScreen); + const int kItems = split_mode ? 6 : 5; if (m.up) { menu_cursor_ = (menu_cursor_ + kItems - 1) % kItems; audio_.play_sfx("CHANGE.WAV", 0.32f); } if (m.down) { menu_cursor_ = (menu_cursor_ + 1) % kItems; audio_.play_sfx("CHANGE.WAV", 0.32f); } if (m.pause || m.back) { @@ -1171,10 +1201,22 @@ void GameApp::update_menu(float dt) { } if (m.confirm) { audio_.play_sfx("SELECT.WAV", 0.38f); - if (menu_cursor_ == 0) state_ = ScreenState::Racing; - else if (menu_cursor_ == 1) start_race_session(); - else if (menu_cursor_ == 2) { opt_tab_ = OptionsTab::Video; enter_state(ScreenState::Options); } - else enter_state(ScreenState::MainMenu); + if (menu_cursor_ == 0) { + state_ = ScreenState::Racing; + } else if (menu_cursor_ == 1) { + race_sim_.request_track_recovery(0); + state_ = ScreenState::Racing; + } else if (split_mode && menu_cursor_ == 2) { + race_sim_.request_track_recovery(1); + state_ = ScreenState::Racing; + } else if (menu_cursor_ == (split_mode ? 3 : 2)) { + start_race_session(); + } else if (menu_cursor_ == (split_mode ? 4 : 3)) { + opt_tab_ = OptionsTab::Video; + enter_state(ScreenState::Options); + } else { + enter_state(ScreenState::MainMenu); + } } return; } @@ -1187,7 +1229,7 @@ void GameApp::update_menu(float dt) { if (m.confirm || m.back) { audio_.play_sfx("SELECT.WAV", 0.38f); if (selected_mode_ == sim::GameMode::Championship && !champ_.is_complete()) { - selected_track_ = champ_.current_track; + selected_track_ = std::clamp(champ_.current_track, 1, std::max(available_tracks_, 1)); start_race_session(); } else { enter_state(ScreenState::MainMenu); @@ -1250,6 +1292,7 @@ int GameApp::run() { if (want_fs) toggle_fullscreen(); int steps = clock_.advance(SDL_GetPerformanceCounter()); + ui_time_ += clock_.last_frame_dt(); if (state_ == ScreenState::Racing) { if (input_.menu_input().pause) { audio_.set_engine_state(false, 0.0f, false, 0.0f); @@ -1299,19 +1342,18 @@ int GameApp::run() { } void GameApp::render_frame(float alpha) { - world_ren_.begin_frame(win_w_, win_h_, cfg_); - if (state_ == ScreenState::TrackViewer) { + world_ren_.begin_frame(win_w_, win_h_, cfg_); render::RenderCamera cam; cam.eye = viewer_pos_; Vec3 look(std::sin(viewer_yaw_) * std::cos(viewer_pitch_), std::sin(viewer_pitch_), std::cos(viewer_yaw_) * std::cos(viewer_pitch_)); cam.target = cam.eye + look; - std::vector tv_all; - append_charger_lights(viewer_level_, ui_time_, tv_all); - auto tv_lights = select_viewport_lights(tv_all, cam.eye, cfg_.draw_distance); - world_ren_.render_world_view(cam, {}, {}, 0, 1, cfg_, tv_lights, {}); + frame_all_lights_.clear(); + append_charger_lights(viewer_level_, ui_time_, frame_all_lights_); + select_viewport_lights(frame_all_lights_, cam.eye, cfg_.draw_distance, frame_vp_lights_); + world_ren_.render_world_view(cam, {}, {}, 0, 1, cfg_, frame_vp_lights_, {}); world_ren_.end_classic_world_pass(win_w_, win_h_, cfg_); MenuLayout ml = compute_menu_layout(win_w_, win_h_); @@ -1327,13 +1369,22 @@ void GameApp::render_frame(float alpha) { } if (state_ == ScreenState::Racing || state_ == ScreenState::Paused) { - std::vector models; - models.reserve(race_sim_.crafts().size() + race_sim_.pickups().size() + - race_sim_.props().size() + race_sim_.projectiles().size() + 4); - std::vector craft_shadows; - craft_shadows.reserve(race_sim_.crafts().size()); - std::vector all_lights; - all_lights.reserve(race_sim_.level().pads.size() + race_sim_.crafts().size() + 16); + // Coalesce any world morphs accumulated during this frame's physics sub-steps into one GPU upload + frame_dirty_rects_.clear(); + bool columns_dirty = false; + if (race_sim_.consume_world_dirty(frame_dirty_rects_, columns_dirty)) { + for (const auto& r : frame_dirty_rects_) { + world_ren_.update_terrain_region(race_sim_.level(), r.x0, r.z0, r.x1, r.z1); + } + if (columns_dirty) { + world_ren_.rebuild_columns(race_sim_.level()); + } + } + + world_ren_.begin_frame(win_w_, win_h_, cfg_); + frame_models_.clear(); + frame_craft_shadows_.clear(); + frame_all_lights_.clear(); for (const auto& c : race_sim_.crafts()) { sim::CraftPose p = sim::interpolate_pose(c, alpha); @@ -1348,41 +1399,38 @@ void GameApp::render_frame(float alpha) { tint.w = 0.32f; } float vscale = sim::kVehicleSpecs[std::clamp(c.vehicle_idx, 0, 5)].visual_scale; - models.push_back({sim::model_key_for(c.vehicle_idx, c.team_idx), p.pos, - p.yaw, p.pitch, p.roll, vscale, tint}); - if (c.recovery_state == sim::RecoveryState::Active || - c.recovery_state == sim::RecoveryState::Repairing || - c.recovery_state == sim::RecoveryState::Destroyed) { - craft_shadows.push_back({p.pos, 0.82f + 0.35f * vscale}); - } + frame_models_.push_back({sim::model_key_for(c.vehicle_idx, c.team_idx), p.pos, + p.yaw, p.pitch, p.roll, vscale, tint}); + float c_floor = p.pos.y, c_ceil = 1e6f; + race_sim_.level().sample_surface_and_ceiling(p.pos.x, p.pos.z, p.pos.y, c_floor, c_ceil); + frame_craft_shadows_.push_back({p.pos, 0.82f + 0.35f * vscale, c_floor}); if (c.recovery_state == sim::RecoveryState::Active) { Vec3 fwd(std::sin(p.yaw), 0.0f, std::cos(p.yaw)); Vec3 jet_pos = p.pos - fwd * 0.55f + Vec3(0.0f, 0.14f, 0.0f); if (c.boost_timer > 0.0f) { - all_lights.push_back({jet_pos, 6.5f, Vec3(0.40f, 0.88f, 1.00f), 1.35f}); + frame_all_lights_.push_back({jet_pos, 6.5f, Vec3(0.40f, 0.88f, 1.00f), 1.35f}); } else if (c.speed_horizontal() > 2.5f) { - all_lights.push_back({jet_pos, 3.8f, Vec3(0.28f, 0.68f, 1.00f), 0.45f}); + frame_all_lights_.push_back({jet_pos, 3.8f, Vec3(0.28f, 0.68f, 1.00f), 0.45f}); } } } if (race_sim_.has_clone_ghost()) { sim::CraftPose gp = race_sim_.interpolated_clone_pose(alpha); - const auto& rec = race_sim_.current_recording(); + const auto& rec = race_sim_.playback_clone(); float gscale = sim::kVehicleSpecs[std::clamp(rec.vehicle_idx, 0, 5)].visual_scale; - models.push_back({sim::model_key_for(rec.vehicle_idx, rec.team_idx), gp.pos, - gp.yaw, gp.pitch, gp.roll, gscale, Vec4(0.45f, 0.85f, 1.0f, 0.45f)}); + frame_models_.push_back({sim::model_key_for(rec.vehicle_idx, rec.team_idx), gp.pos, + gp.yaw, gp.pitch, gp.roll, gscale, Vec4(0.45f, 0.85f, 1.0f, 0.45f)}); } for (const auto& rv : sim::get_recovery_visuals(race_sim_.crafts())) { - models.push_back({"RECOV0-0", rv.pos, rv.yaw, 0.0f, 0.0f, - sim::kRecoveryVisualScale, Vec4(1, 1, 1, 1)}); + frame_models_.push_back({"RECOV0-0", rv.pos, rv.yaw, 0.0f, 0.0f, + sim::kRecoveryVisualScale, Vec4(1, 1, 1, 1)}); } for (const auto& pr : race_sim_.props()) { if (!pr.alive) continue; float pscale = (pr.model_key.rfind("BAREL", 0) == 0) ? 0.42f : 0.68f; - models.push_back({pr.model_key, pr.pos, pr.yaw, 0.0f, 0.0f, pscale, Vec4(1, 1, 1, 1)}); + frame_models_.push_back({pr.model_key, pr.pos, pr.yaw, 0.0f, 0.0f, pscale, Vec4(1, 1, 1, 1)}); } - std::vector billboards; - billboards.reserve(race_sim_.pickups().size()); + frame_billboards_.clear(); const bool use_tmap_pickups = world_ren_.has_tmaps(); for (const auto& pk : race_sim_.pickups()) { if (!pk.active) continue; @@ -1400,52 +1448,51 @@ void GameApp::render_frame(float alpha) { Vec3 ppos = pk.pos + Vec3(0, bob, 0); if (use_tmap_pickups) { float alpha_p = (pk.subtype == 1) ? 0.78f : 1.0f; - billboards.push_back({ppos + Vec3(0.0f, 0.15f, 0.0f), 1.05f, - assets::pickup_tmap_index(pk.subtype), - Vec4(1.0f, 1.0f, 1.0f, alpha_p)}); + frame_billboards_.push_back({ppos + Vec3(0.0f, 0.15f, 0.0f), 1.05f, + assets::pickup_tmap_index(pk.subtype), + Vec4(1.0f, 1.0f, 1.0f, alpha_p)}); } else { - models.push_back({"CONE0-0", ppos, rot, 0.0f, 0.0f, 0.65f, - Vec4(lcol.x, lcol.y, lcol.z, 1.0f)}); + frame_models_.push_back({"CONE0-0", ppos, rot, 0.0f, 0.0f, 0.65f, + Vec4(lcol.x, lcol.y, lcol.z, 1.0f)}); } - all_lights.push_back({ppos + Vec3(0.0f, 0.25f, 0.0f), 3.4f, lcol, 0.46f}); + frame_all_lights_.push_back({ppos + Vec3(0.0f, 0.25f, 0.0f), 3.4f, lcol, 0.46f}); } for (const auto& pj : race_sim_.projectiles()) { if (!pj.active) continue; if (pj.is_missile) { - models.push_back({"CONE0-1", pj.pos, pj.yaw, -kHalfPi, 0.0f, 0.5f, Vec4(1.0f, 0.3f, 0.2f, 1)}); - all_lights.push_back({pj.pos, 5.8f, Vec3(1.0f, 0.44f, 0.14f), 1.15f}); + frame_models_.push_back({"CONE0-1", pj.pos, pj.yaw, -kHalfPi, 0.0f, 0.5f, Vec4(1.0f, 0.3f, 0.2f, 1)}); + frame_all_lights_.push_back({pj.pos, 5.8f, Vec3(1.0f, 0.44f, 0.14f), 1.15f}); } else { - all_lights.push_back({pj.pos, 2.8f, Vec3(1.0f, 0.85f, 0.32f), 0.55f}); + frame_all_lights_.push_back({pj.pos, 2.8f, Vec3(1.0f, 0.85f, 0.32f), 0.55f}); } } - std::vector parts; - parts.reserve(race_sim_.particles().size() + race_sim_.projectiles().size()); - std::vector fire_clusters; + frame_parts_.clear(); + frame_fire_clusters_.clear(); for (const auto& pb : race_sim_.particles()) { bool additive = (pb.kind == sim::ParticleKind::AdditiveGlow || pb.kind == sim::ParticleKind::Fireball); - parts.push_back({pb.pos, pb.size, pb.color, static_cast(pb.kind), pb.seed, additive}); + frame_parts_.push_back({pb.pos, pb.size, pb.color, static_cast(pb.kind), pb.seed, additive}); if (pb.kind == sim::ParticleKind::Fireball && pb.color.w > 0.15f) { bool merged = false; - for (const auto& fp : fire_clusters) { + for (const auto& fp : frame_fire_clusters_) { if ((pb.pos - fp).len_sq() < 4.84f) { merged = true; break; } } if (!merged) { - fire_clusters.push_back(pb.pos); - all_lights.push_back({pb.pos, 10.5f, Vec3(1.0f, 0.54f, 0.14f), - 1.65f * std::clamp(pb.color.w, 0.25f, 1.0f)}); + frame_fire_clusters_.push_back(pb.pos); + frame_all_lights_.push_back({pb.pos, 10.5f, Vec3(1.0f, 0.54f, 0.14f), + 1.65f * std::clamp(pb.color.w, 0.25f, 1.0f)}); } } } for (const auto& pj : race_sim_.projectiles()) { if (!pj.active || pj.is_missile) continue; - parts.push_back({pj.pos, 0.28f, Vec4(1.0f, 0.9f, 0.35f, 1.0f), 0.0f, 0.0f, true}); + frame_parts_.push_back({pj.pos, 0.28f, Vec4(1.0f, 0.9f, 0.35f, 1.0f), 0.0f, 0.0f, true}); } - append_charger_lights(race_sim_.level(), ui_time_, all_lights); + append_charger_lights(race_sim_.level(), ui_time_, frame_all_lights_); float draw_dist = cfg_.classic_mode ? 38.0f : cfg_.draw_distance; int split_count = (selected_mode_ == sim::GameMode::SplitScreen && race_sim_.crafts().size() >= 2) ? 2 : 1; @@ -1495,9 +1542,9 @@ void GameApp::render_frame(float alpha) { } float min_cam_y = race_sim_.level().sample_height_world(cams[vp].eye.x, cams[vp].eye.z) + 0.4f; if (cams[vp].eye.y < min_cam_y) cams[vp].eye.y = min_cam_y; - auto vp_lights = select_viewport_lights(all_lights, cams[vp].target, draw_dist); - world_ren_.render_world_view(cams[vp], models, parts, vp, split_count, cfg_, - vp_lights, craft_shadows, billboards); + select_viewport_lights(frame_all_lights_, cams[vp].target, draw_dist, frame_vp_lights_); + world_ren_.render_world_view(cams[vp], frame_models_, frame_parts_, vp, split_count, cfg_, + frame_vp_lights_, frame_craft_shadows_, frame_billboards_); } world_ren_.end_classic_world_pass(win_w_, win_h_, cfg_); @@ -1523,7 +1570,7 @@ void GameApp::render_frame(float alpha) { : frame_y_gl; if (hud_visible_) { render_hud_viewport(race_sim_.crafts()[vp], cams[vp], frame_x, gl_vy, frame_w, vh, - vp == 0 && cfg_.show_minimap); + vp == 0 && cfg_.show_minimap, alpha); } else if (race_sim_.countdown_active() || race_sim_.crafts()[vp].race_time < 0.85f) { float hs = std::clamp(static_cast(vh) / 480.0f, 0.55f, 1.8f); int top_y = win_h_ - (gl_vy + vh); @@ -1575,7 +1622,7 @@ void GameApp::render_frame(float alpha) { } void GameApp::render_hud_viewport(const sim::CraftState& craft, const render::RenderCamera& cam, - int vx, int vy, int vw, int vh, bool show_minimap) { + int vx, int vy, int vw, int vh, bool show_minimap, float alpha) { const auto& str = get_strings(cfg_.language); int top_y = win_h_ - (vy + vh); bool split_view = (selected_mode_ == sim::GameMode::SplitScreen && race_sim_.crafts().size() >= 2); @@ -1595,13 +1642,18 @@ void GameApp::render_hud_viewport(const sim::CraftState& craft, const render::Re if (craft.lock_target_id >= 0 && craft.lock_target_id < static_cast(race_sim_.crafts().size())) { const auto& tgt = race_sim_.crafts()[craft.lock_target_id]; if (tgt.recovery_state == sim::RecoveryState::Active) { - float aspect = static_cast(vw) / static_cast(std::max(vh, 1)); - if (split_view) aspect = std::max(aspect, 1.0f); + sim::CraftPose tp = sim::interpolate_pose(tgt, alpha); + float aspect = cfg_.classic_mode + ? ((4.0f / 3.0f) * static_cast(split_view ? 2 : 1)) + : (static_cast(vw) / static_cast(std::max(vh, 1))); + if (!cfg_.classic_mode && split_view) aspect = std::max(aspect, 1.0f); float fov = cfg_.classic_mode ? 62.0f : cfg_.fov_deg; Mat4 vp_mat = Mat4::perspective(deg_to_rad(fov), aspect, cam.z_near, cam.z_far) * Mat4::look_at(cam.eye, cam.target, cam.up); float sx = 0.0f, sy = 0.0f; - if (project_world_to_screen(tgt.curr_pose.pos, vp_mat, vx, vy, vw, vh, win_h_, sx, sy)) { + if (project_world_to_screen(tp.pos, vp_mat, vx, vy, vw, vh, win_h_, sx, sy) && + sx >= static_cast(vx) + 16.0f && sx <= static_cast(vx + vw) - 16.0f && + sy >= static_cast(top_y) + 16.0f && sy <= static_cast(top_y + vh) - 16.0f) { bool locked = (craft.lock_progress >= 1.0f); float pulse = locked ? (0.75f + 0.25f * std::sin(static_cast(ui_time_) * 16.0f)) : 0.92f; Vec4 tint(1.0f, 1.0f, 1.0f, pulse); @@ -1634,12 +1686,8 @@ void GameApp::render_hud_viewport(const sim::CraftState& craft, const render::Re const Vec4& lit_tint, float back_alpha) { Vec4 dim_tint(0.14f, 0.17f, 0.24f, back_alpha); for (int i = 0; i < count; ++i) { - draw_panel(segs[i].spr, static_cast(segs[i].x), static_cast(segs[i].y), dim_tint); - } - for (int i = 0; i < count; ++i) { - if (val_10000 > segs[i].thr) { - draw_panel(segs[i].spr, static_cast(segs[i].x), static_cast(segs[i].y), lit_tint); - } + draw_panel(segs[i].spr, static_cast(segs[i].x), static_cast(segs[i].y), + (val_10000 > segs[i].thr) ? lit_tint : dim_tint); } }; @@ -1705,13 +1753,22 @@ void GameApp::render_hud_viewport(const sim::CraftState& craft, const render::Re float spd_frac = std::clamp(craft.speed_horizontal() / sim::kGlobalSpeedGaugeMax, 0.0f, 1.0f); draw_arc(kFuelArc, 17, static_cast(fuel_frac * 10000.0f), status_tint(fuel_frac, 2u), 0.26f); - draw_arc(kSpeedWaveDim, 19, static_cast(spd_frac * 10000.0f), Vec4(1.0f, 1.0f, 1.0f, 0.95f), 0.22f); - if (craft.boost_timer > 0.0f) { - int wave_val = static_cast(std::clamp(spd_frac + 0.25f, 0.35f, 1.0f) * 10000.0f); + { + const int wave_dim_val = static_cast(spd_frac * 10000.0f); + const int wave_lit_val = (craft.boost_timer > 0.0f) + ? static_cast(std::clamp(spd_frac + 0.25f, 0.35f, 1.0f) * 10000.0f) + : -1; + const Vec4 dim_tint(0.14f, 0.17f, 0.24f, 0.22f); + const Vec4 spd_tint(1.0f, 1.0f, 1.0f, 0.95f); + const Vec4 bst_tint(1.0f, 1.0f, 1.0f, 0.98f); for (int i = 0; i < 19; ++i) { - if (wave_val > kSpeedWaveLit[i].thr) { + if (wave_lit_val > kSpeedWaveLit[i].thr) { draw_panel(kSpeedWaveLit[i].spr, static_cast(kSpeedWaveLit[i].x), - static_cast(kSpeedWaveLit[i].y), Vec4(1.0f, 1.0f, 1.0f, 0.98f)); + static_cast(kSpeedWaveLit[i].y), bst_tint); + } else { + draw_panel(kSpeedWaveDim[i].spr, static_cast(kSpeedWaveDim[i].x), + static_cast(kSpeedWaveDim[i].y), + (wave_dim_val > kSpeedWaveDim[i].thr) ? spd_tint : dim_tint); } } } @@ -1847,6 +1904,13 @@ void GameApp::render_hud_viewport(const sim::CraftState& craft, const render::Re ui_ren_.draw_text_centered_fit(cx, cy + 26.0f * s, static_cast(vw) * 0.75f, 2.4f * s, hud_banner_[pi], Vec4(1.0f, 0.92f, 0.25f, 1.0f), true, render::UiFont::MenuLarge); + } else if (craft.stuck_in_pit_hint && craft.recovery_state == sim::RecoveryState::Active) { + int sc = (pi == 1) ? cfg_.keys.p2_recover : cfg_.keys.recover; + std::string hint = "STUCK? PRESS [" + InputManager::scancode_name(sc) + "] TO RECOVER"; + float pulse = 0.72f + 0.28f * std::sin(static_cast(ui_time_) * 7.5f); + ui_ren_.draw_text_centered_fit(cx, cy + 32.0f * s, static_cast(vw) * 0.78f, 1.85f * s, + hint, Vec4(1.0f, 0.85f, 0.25f, pulse), + true, render::UiFont::MenuSmall); } } } @@ -1886,7 +1950,8 @@ void GameApp::render_minimap(const sim::CraftState& focus, float mx, float my, f float oy = my + (size - (max_z - min_z) * scale) * 0.5f; auto to_mm = [&](float wx, float wz) -> Vec2 { - return Vec2(ox + (wx - min_x) * scale, oy + (wz - min_z) * scale); + return Vec2(std::clamp(ox + (wx - min_x) * scale, mx + 4.0f, mx + size - 4.0f), + std::clamp(oy + (wz - min_z) * scale, my + 4.0f, my + size - 4.0f)); }; // Dark outer casing + bright slate track ribbon @@ -1968,13 +2033,20 @@ void GameApp::render_menus() { ui_ren_.draw_rect(0, 0, vw, vh, Vec4(0.03f, 0.05f, 0.11f, 0.55f)); if (state_ == ScreenState::Paused) { - ui_ren_.draw_rect(cx - 230.0f, oy + 145.0f, 460.0f, 290.0f, Vec4(0.03f, 0.05f, 0.12f, 0.92f)); - ui_ren_.draw_rect_outline(cx - 230.0f, oy + 145.0f, 460.0f, 290.0f, 2.0f, Vec4(0.3f, 0.7f, 1.0f, 1)); - ui_ren_.draw_text_centered(cx, oy + 168.0f, 3.1f, "PAUSED", Vec4(1.0f, 0.85f, 0.2f, 1)); - const char* pitems[] = {str.continue_game, "RESTART RACE", str.options, str.abort_game}; - for (int i = 0; i < 4; ++i) { + const bool split_mode = (selected_mode_ == sim::GameMode::SplitScreen); + const int kItems = split_mode ? 6 : 5; + const float panel_y = oy + (split_mode ? 105.0f : 125.0f); + const float panel_h = 120.0f + static_cast(kItems) * 44.0f; + ui_ren_.draw_rect(cx - 240.0f, panel_y, 480.0f, panel_h, Vec4(0.03f, 0.05f, 0.12f, 0.92f)); + ui_ren_.draw_rect_outline(cx - 240.0f, panel_y, 480.0f, panel_h, 2.0f, Vec4(0.3f, 0.7f, 1.0f, 1)); + ui_ren_.draw_text_centered(cx, panel_y + 22.0f, 3.1f, "PAUSED", Vec4(1.0f, 0.85f, 0.2f, 1)); + const char* pitems_1p[5] = {str.continue_game, "RECOVER TO TRACK", "RESTART RACE", str.options, str.abort_game}; + const char* pitems_2p[6] = {str.continue_game, "RECOVER P1 TO TRACK", "RECOVER P2 TO TRACK", + "RESTART RACE", str.options, str.abort_game}; + const char* const* pitems = split_mode ? pitems_2p : pitems_1p; + for (int i = 0; i < kItems; ++i) { Vec4 col = (i == menu_cursor_) ? Vec4(1, 0.95f, 0.2f, 1) : Vec4(0.8f, 0.88f, 1, 1); - ui_ren_.draw_text_centered(cx, oy + 232.0f + i * 44.0f, 2.25f, pitems[i], col); + ui_ren_.draw_text_centered_fit(cx, panel_y + 84.0f + i * 44.0f, 440.0f, 2.25f, pitems[i], col); } return; } @@ -2023,7 +2095,7 @@ void GameApp::render_menus() { ? ("CONTINUE CHAMPIONSHIP (TRACK " + std::to_string(champ_.current_track) + "/" + std::to_string(champ_.total_tracks) + ")") : "CONTINUE CHAMPIONSHIP (NONE)", "LOAD SLOT " + std::to_string(champ_slot_cursor_ + 1) + - (ChampionshipState::slot_exists(vfs_.pref_dir(), champ_slot_cursor_) ? " [SAVED]" : " [EMPTY]"), + (champ_slot_saved_[std::clamp(champ_slot_cursor_, 0, 3)] ? " [SAVED]" : " [EMPTY]"), "SAVE SLOT " + std::to_string(champ_slot_cursor_ + 1), "BACK TO MAIN MENU" }; @@ -2234,24 +2306,25 @@ void GameApp::render_menus() { : std::filesystem::path(cfg_.custom_soundfont_path).filename().string(); rows.push_back("SOUNDFONT: " + sf_lbl); } else if (opt_tab_ == OptionsTab::ControlsP1) { - const char* klabels[10] = {"STEER LEFT", "STEER RIGHT", "ACCELERATE", "BRAKE", "BOOST", - "FIRE MINIGUN", "FIRE MISSILE", "AUTO PILOT", "CAMERA VIEW", "HUD TOGGLE"}; - int kvals[10] = {cfg_.keys.steer_left, cfg_.keys.steer_right, cfg_.keys.accelerate, + const char* klabels[11] = {"STEER LEFT", "STEER RIGHT", "ACCELERATE", "BRAKE", "BOOST", + "FIRE MINIGUN", "FIRE MISSILE", "AUTO PILOT", "CAMERA VIEW", + "HUD TOGGLE", "RECOVER TO TRACK"}; + int kvals[11] = {cfg_.keys.steer_left, cfg_.keys.steer_right, cfg_.keys.accelerate, cfg_.keys.brake, cfg_.keys.boost, cfg_.keys.fire_minigun, cfg_.keys.fire_missile, cfg_.keys.autopilot, cfg_.keys.camera_view, - cfg_.keys.hud_toggle}; - for (int i = 0; i < 10; ++i) { + cfg_.keys.hud_toggle, cfg_.keys.recover}; + for (int i = 0; i < 11; ++i) { std::string kname = (rebind_slot_ == i) ? "[PRESS KEY...]" : InputManager::scancode_name(kvals[i]); rows.push_back(std::string(klabels[i]) + ": " + kname); } } else if (opt_tab_ == OptionsTab::ControlsP2) { - const char* klabels[7] = {"P2 STEER LEFT", "P2 STEER RIGHT", "P2 ACCELERATE", "P2 BRAKE", - "P2 BOOST", "P2 FIRE MINIGUN", "P2 FIRE MISSILE"}; - int kvals[7] = {cfg_.keys.p2_steer_left, cfg_.keys.p2_steer_right, cfg_.keys.p2_accelerate, + const char* klabels[8] = {"P2 STEER LEFT", "P2 STEER RIGHT", "P2 ACCELERATE", "P2 BRAKE", + "P2 BOOST", "P2 FIRE MINIGUN", "P2 FIRE MISSILE", "P2 RECOVER"}; + int kvals[8] = {cfg_.keys.p2_steer_left, cfg_.keys.p2_steer_right, cfg_.keys.p2_accelerate, cfg_.keys.p2_brake, cfg_.keys.p2_boost, cfg_.keys.p2_fire_minigun, - cfg_.keys.p2_fire_missile}; - for (int i = 0; i < 7; ++i) { - std::string kname = (rebind_slot_ == 10 + i) ? "[PRESS KEY...]" : InputManager::scancode_name(kvals[i]); + cfg_.keys.p2_fire_missile, cfg_.keys.p2_recover}; + for (int i = 0; i < 8; ++i) { + std::string kname = (rebind_slot_ == 11 + i) ? "[PRESS KEY...]" : InputManager::scancode_name(kvals[i]); rows.push_back(std::string(klabels[i]) + ": " + kname); } } else if (opt_tab_ == OptionsTab::InputPad) { @@ -2436,7 +2509,8 @@ void GameApp::render_menus() { : Vec4(0.9f, 0.95f, 1, 1); ui_ren_.draw_text_fit(c0, ry, tbl_w * 0.09f, 1.75f, std::to_string(i + 1) + ".", col); ui_ren_.draw_text_fit(c1, ry, tbl_w * 0.29f, 1.75f, ds[i].name, col); - ui_ren_.draw_text_fit(c2, ry, tbl_w * 0.29f, 1.75f, sim::kTeamNames[ds[i].team_idx], col); + ui_ren_.draw_text_fit(c2, ry, tbl_w * 0.29f, 1.75f, + sim::kTeamNames[std::clamp(ds[i].team_idx, 0, 7)], col); ui_ren_.draw_text_fit(c3, ry, tbl_w * 0.13f, 1.75f, std::to_string(ds[i].points) + " PTS", col); ui_ren_.draw_text_fit(c4, ry, tbl_w * 0.16f, 1.75f, std::to_string(ds[i].wins) + " W", col); } diff --git a/src/game/game_app.hpp b/src/game/game_app.hpp index 949fddb..a03f61c 100644 --- a/src/game/game_app.hpp +++ b/src/game/game_app.hpp @@ -35,6 +35,9 @@ struct LaunchOptions { class GameApp { public: + GameApp() = default; + ~GameApp(); + bool init(const LaunchOptions& opts); int run(); void shutdown(); @@ -76,12 +79,13 @@ private: void render_frame(float alpha); void render_hud_viewport(const sim::CraftState& craft, const render::RenderCamera& cam, - int vx, int vy, int vw, int vh, bool show_minimap); + int vx, int vy, int vw, int vh, bool show_minimap, float alpha); void render_countdown_lights(float cx, float ly, float hs); void render_minimap(const sim::CraftState& focus, float mx, float my, float size); void render_menus(); void handle_sim_events(); + void refresh_champ_slot_cache(); void apply_video_settings(); void toggle_fullscreen(); void save_all_user_data(); @@ -156,6 +160,20 @@ private: int editing_name_target_ = 0; // 0=none, 1=P1, 2=P2 std::string name_edit_buf_; std::vector available_soundfonts_; + + bool initialized_ = false; + bool sdl_initialized_ = false; + std::array champ_slot_saved_{}; + + // Reusable per-frame render scratch buffers + std::vector frame_models_; + std::vector frame_craft_shadows_; + std::vector frame_all_lights_; + std::vector frame_vp_lights_; + std::vector frame_billboards_; + std::vector frame_parts_; + std::vector frame_fire_clusters_; + std::vector frame_dirty_rects_; }; } // namespace top_octane::game diff --git a/src/game/game_modes.cpp b/src/game/game_modes.cpp index bc84fc1..66966b9 100644 --- a/src/game/game_modes.cpp +++ b/src/game/game_modes.cpp @@ -1,10 +1,12 @@ #include "game/game_modes.hpp" #include +#include #include #include #include #include +#include #include namespace top_octane::game { @@ -100,37 +102,55 @@ bool ChampionshipState::load_slot(const std::filesystem::path& pref_dir, int slo std::string magic; if (!std::getline(ifs, magic)) return false; + ChampionshipState tmp; int act = 0; if (magic == "TOPOCTANE_CHAMP_V1") { - if (!(ifs >> act >> current_track >> difficulty >> player_vehicle >> player_team >> overall_rating_pts)) { + if (!(ifs >> act >> tmp.current_track >> tmp.difficulty >> tmp.player_vehicle >> tmp.player_team >> tmp.overall_rating_pts)) { return false; } - total_tracks = std::max(6, current_track); + tmp.total_tracks = std::max(6, tmp.current_track); } else if (magic == "TOPOCTANE_CHAMP_V2") { - if (!(ifs >> act >> current_track >> total_tracks >> difficulty >> player_vehicle >> player_team >> overall_rating_pts)) { + if (!(ifs >> act >> tmp.current_track >> tmp.total_tracks >> tmp.difficulty >> tmp.player_vehicle >> tmp.player_team >> tmp.overall_rating_pts)) { return false; } - total_tracks = std::clamp(total_tracks, 1, assets::kMaxTracks); } else { return false; } - active = (act != 0); - ifs.ignore(256, '\n'); - if (!std::getline(ifs, player_name)) return false; + tmp.active = (act != 0); + tmp.total_tracks = std::clamp(tmp.total_tracks, 1, assets::kMaxTracks); + // Allow current_track == total_tracks + 1 only for completed championships + tmp.current_track = std::clamp(tmp.current_track, 1, assets::kMaxTracks + 1); + tmp.difficulty = std::clamp(tmp.difficulty, 0, 2); + tmp.player_vehicle = std::clamp(tmp.player_vehicle, 0, 5); + tmp.player_team = std::clamp(tmp.player_team, 0, 7); + tmp.overall_rating_pts = std::max(0, tmp.overall_rating_pts); + + ifs.ignore(std::numeric_limits::max(), '\n'); + if (!std::getline(ifs, tmp.player_name)) return false; + if (tmp.player_name.empty()) tmp.player_name = "PLAYER"; + if (tmp.player_name.size() > 16) tmp.player_name.resize(16); for (int i = 0; i < 8; ++i) { - if (!(ifs >> drivers[i].team_idx >> drivers[i].vehicle_idx >> drivers[i].points - >> drivers[i].kills >> drivers[i].wins)) { + if (!(ifs >> tmp.drivers[i].team_idx >> tmp.drivers[i].vehicle_idx >> tmp.drivers[i].points + >> tmp.drivers[i].kills >> tmp.drivers[i].wins)) { return false; } + tmp.drivers[i].team_idx = std::clamp(tmp.drivers[i].team_idx, 0, 7); + tmp.drivers[i].vehicle_idx = std::clamp(tmp.drivers[i].vehicle_idx, 0, 5); + tmp.drivers[i].points = std::max(0, tmp.drivers[i].points); + tmp.drivers[i].kills = std::max(0, tmp.drivers[i].kills); + tmp.drivers[i].wins = std::max(0, tmp.drivers[i].wins); + std::string rest; std::getline(ifs, rest); size_t first = rest.find_first_not_of(' '); - drivers[i].name = (first == std::string::npos) ? "PILOT" : rest.substr(first); + tmp.drivers[i].name = (first == std::string::npos) ? "PILOT" : rest.substr(first, 16); } for (int i = 0; i < 8; ++i) { - if (!(ifs >> team_points[i])) return false; + if (!(ifs >> tmp.team_points[i])) return false; + tmp.team_points[i] = std::max(0, tmp.team_points[i]); } + *this = std::move(tmp); return true; } @@ -179,13 +199,23 @@ bool HighscoreTable::load(const std::filesystem::path& path) { } else { return false; } - clear(); + HighscoreTable tmp; + tmp.clear(); for (int i = 0; i < count; ++i) { - if (!(ifs >> tracks[i].best_lap >> tracks[i].best_race)) return false; - ifs.ignore(256, '\n'); - if (!std::getline(ifs, tracks[i].best_lap_driver)) return false; - if (!std::getline(ifs, tracks[i].best_race_driver)) return false; + float lap = 0.0f, race = 0.0f; + if (!(ifs >> lap >> race)) return false; + if (!std::isfinite(lap) || lap < 0.0f || !std::isfinite(race) || race < 0.0f) { + return false; + } + tmp.tracks[i].best_lap = lap; + tmp.tracks[i].best_race = race; + ifs.ignore(std::numeric_limits::max(), '\n'); + if (!std::getline(ifs, tmp.tracks[i].best_lap_driver)) return false; + if (!std::getline(ifs, tmp.tracks[i].best_race_driver)) return false; + if (tmp.tracks[i].best_lap_driver.size() > 24) tmp.tracks[i].best_lap_driver.resize(24); + if (tmp.tracks[i].best_race_driver.size() > 24) tmp.tracks[i].best_race_driver.resize(24); } + *this = std::move(tmp); return true; } @@ -228,20 +258,34 @@ bool load_clone_recording(const std::filesystem::path& pref_dir, int track_num, std::ifstream ifs(clone_path(pref_dir, track_num), std::ios::binary); if (!ifs) return false; uint32_t magic = 0, count = 0; + sim::CloneRecording tmp; ifs.read(reinterpret_cast(&magic), sizeof(magic)); if (magic != 0x434C4E31u) return false; - ifs.read(reinterpret_cast(&out_rec.track_number), sizeof(out_rec.track_number)); - ifs.read(reinterpret_cast(&out_rec.vehicle_idx), sizeof(out_rec.vehicle_idx)); - ifs.read(reinterpret_cast(&out_rec.team_idx), sizeof(out_rec.team_idx)); - ifs.read(reinterpret_cast(&out_rec.best_race_time), sizeof(out_rec.best_race_time)); + ifs.read(reinterpret_cast(&tmp.track_number), sizeof(tmp.track_number)); + ifs.read(reinterpret_cast(&tmp.vehicle_idx), sizeof(tmp.vehicle_idx)); + ifs.read(reinterpret_cast(&tmp.team_idx), sizeof(tmp.team_idx)); + ifs.read(reinterpret_cast(&tmp.best_race_time), sizeof(tmp.best_race_time)); ifs.read(reinterpret_cast(&count), sizeof(count)); - if (!ifs || count > 36000) return false; - out_rec.frames.resize(count); - if (count > 0) { - ifs.read(reinterpret_cast(out_rec.frames.data()), - static_cast(count * sizeof(sim::CraftPose))); + constexpr uint32_t kMaxCloneFrames = 60u * 60u * 15u; + if (!ifs || count == 0 || count > kMaxCloneFrames) return false; + if (tmp.track_number < 1 || tmp.track_number > assets::kMaxTracks || + tmp.vehicle_idx < 0 || tmp.vehicle_idx > 5 || + tmp.team_idx < 0 || tmp.team_idx > 7 || + !std::isfinite(tmp.best_race_time) || tmp.best_race_time <= 0.0f || tmp.best_race_time >= 86400.0f) { + return false; } - return ifs.good(); + tmp.frames.resize(count); + ifs.read(reinterpret_cast(tmp.frames.data()), + static_cast(count * sizeof(sim::CraftPose))); + if (!ifs.good()) return false; + for (const auto& f : tmp.frames) { + if (!std::isfinite(f.pos.x) || !std::isfinite(f.pos.y) || !std::isfinite(f.pos.z) || + !std::isfinite(f.yaw) || !std::isfinite(f.pitch) || !std::isfinite(f.roll)) { + return false; + } + } + out_rec = std::move(tmp); + return true; } } // namespace top_octane::game diff --git a/src/input/input_manager.cpp b/src/input/input_manager.cpp index 175b8a3..3759da2 100644 --- a/src/input/input_manager.cpp +++ b/src/input/input_manager.cpp @@ -52,7 +52,12 @@ void InputManager::shutdown() { void InputManager::open_gamepad_by_device_index(int device_index) { SDL_GameController* gc = SDL_GameControllerOpen(device_index); if (!gc) return; - SDL_JoystickID id = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(gc)); + SDL_Joystick* joy = SDL_GameControllerGetJoystick(gc); + if (!joy) { + SDL_GameControllerClose(gc); + return; + } + SDL_JoystickID id = SDL_JoystickInstanceID(joy); for (int i = 0; i < kMaxGamepads; ++i) { if (gamepads_[i] && gamepad_ids_[i] == id) { SDL_GameControllerClose(gc); @@ -63,7 +68,8 @@ void InputManager::open_gamepad_by_device_index(int device_index) { if (!gamepads_[i]) { gamepads_[i] = gc; gamepad_ids_[i] = id; - LOG_INFO("Gamepad connected [slot %d]: %s", i, SDL_GameControllerName(gc)); + const char* cname = SDL_GameControllerName(gc); + LOG_INFO("Gamepad connected [slot %d]: %s", i, cname ? cname : "Unknown"); return; } } @@ -111,6 +117,7 @@ void InputManager::stop_text_input() { void InputManager::begin_frame() { prev_keys_ = curr_keys_; prev_gp_buttons_ = curr_gp_buttons_; + prev_player_gp_buttons_ = curr_player_gp_buttons_; menu_ = MenuInput{}; text_chars_.clear(); text_backspace_ = false; @@ -230,6 +237,15 @@ void InputManager::end_frame(const GameConfig& cfg) { curr_gp_buttons_[b] = SDL_GameControllerGetButton(gp, static_cast(b)) != 0; } } + for (int p = 0; p < 2; ++p) { + curr_player_gp_buttons_[p].fill(false); + if (SDL_GameController* pgp = get_player_gamepad(p, cfg)) { + for (int b = 0; b < 15; ++b) { + curr_player_gp_buttons_[p][b] = + SDL_GameControllerGetButton(pgp, static_cast(b)) != 0; + } + } + } auto gp_just = [&](SDL_GameControllerButton b) -> bool { int idx = static_cast(b); return curr_gp_buttons_[idx] && !prev_gp_buttons_[idx]; @@ -279,6 +295,7 @@ CraftInput InputManager::craft_input(int player_idx, const GameConfig& cfg, out.toggle_autopilot_pressed = key_just(kb.autopilot); out.cycle_camera_pressed = key_just(kb.camera_view); out.toggle_hud_pressed = key_just(kb.hud_toggle); + out.recover_pressed = key_just(kb.recover); // In 1P mode, support Arrow keys as ergonomic backup alongside WASD if (allow_arrow_fallback) { @@ -300,9 +317,15 @@ CraftInput InputManager::craft_input(int player_idx, const GameConfig& cfg, out.boost = key_down(kb.p2_boost); out.fire_minigun = key_down(kb.p2_fire_minigun); out.fire_missile = key_down(kb.p2_fire_missile); + out.recover_pressed = key_just(kb.p2_recover); } if (SDL_GameController* gc = get_player_gamepad(player_idx, cfg)) { + int pi = (player_idx == 1) ? 1 : 0; + if (curr_player_gp_buttons_[pi][SDL_CONTROLLER_BUTTON_BACK] && + !prev_player_gp_buttons_[pi][SDL_CONTROLLER_BUTTON_BACK]) { + out.recover_pressed = true; + } float ax = shape_axis(SDL_GameControllerGetAxis(gc, SDL_CONTROLLER_AXIS_LEFTX), cfg.gamepad_deadzone, cfg.steering_curve, cfg.steering_sensitivity); if (SDL_GameControllerGetButton(gc, SDL_CONTROLLER_BUTTON_DPAD_LEFT)) ax = -1.0f; @@ -345,6 +368,7 @@ bool InputManager::consume_rebound_scancode(int& out_scancode) { void InputManager::trigger_rumble(int player_idx, float low_freq, float high_freq, uint32_t duration_ms, const GameConfig& cfg) { if (!cfg.rumble_enabled) return; + if (!std::isfinite(low_freq) || !std::isfinite(high_freq)) return; if (SDL_GameController* gc = get_player_gamepad(player_idx, cfg)) { uint16_t lo = static_cast(std::clamp(low_freq, 0.0f, 1.0f) * 65535.0f); uint16_t hi = static_cast(std::clamp(high_freq, 0.0f, 1.0f) * 65535.0f); diff --git a/src/input/input_manager.hpp b/src/input/input_manager.hpp index 265a498..a4ee2fe 100644 --- a/src/input/input_manager.hpp +++ b/src/input/input_manager.hpp @@ -19,6 +19,7 @@ struct CraftInput { bool toggle_autopilot_pressed = false; bool cycle_camera_pressed = false; bool toggle_hud_pressed = false; + bool recover_pressed = false; }; struct MenuInput { @@ -83,6 +84,8 @@ private: std::array curr_keys_{}; std::array prev_gp_buttons_{}; std::array curr_gp_buttons_{}; + std::array, 2> prev_player_gp_buttons_{}; + std::array, 2> curr_player_gp_buttons_{}; float mouse_steer_accum_ = 0.0f; MenuInput menu_{}; diff --git a/src/main.cpp b/src/main.cpp index a113cb8..36b4d7d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,6 +1,7 @@ #include "core/log.hpp" #include "game/game_app.hpp" +#include #include #include #include @@ -9,6 +10,17 @@ using namespace top_octane; namespace { +bool parse_int_arg(const char* s, int min_v, int max_v, int& out_v) { + if (!s || *s == '\0') return false; + errno = 0; + char* end = nullptr; + long v = std::strtol(s, &end, 10); + if (errno != 0 || end == s || *end != '\0') return false; + if (v < static_cast(min_v) || v > static_cast(max_v)) return false; + out_v = static_cast(v); + return true; +} + void print_usage(const char* argv0) { std::cout << "Top-Octane (Modern Cross-Platform SDL2 + OpenGL 3.3 Port of Hi-Octane)\n" << "Usage: " << argv0 << " [options]\n" @@ -37,9 +49,15 @@ int main(int argc, char** argv) { } else if (std::strcmp(argv[i], "--data-dir") == 0 && i + 1 < argc) { opts.data_dir = argv[++i]; } else if (std::strcmp(argv[i], "--track") == 0 && i + 1 < argc) { - opts.start_track = std::atoi(argv[++i]); + if (!parse_int_arg(argv[++i], 1, 9, opts.start_track)) { + LOG_ERROR("Invalid --track value (expected 1..9)"); + return 1; + } } else if (std::strcmp(argv[i], "--track-viewer") == 0 && i + 1 < argc) { - opts.start_track = std::atoi(argv[++i]); + if (!parse_int_arg(argv[++i], 1, 9, opts.start_track)) { + LOG_ERROR("Invalid --track-viewer value (expected 1..9)"); + return 1; + } opts.track_viewer = true; } else if (std::strcmp(argv[i], "--classic") == 0) { opts.force_classic = true; @@ -52,10 +70,17 @@ int main(int argc, char** argv) { if (std::strcmp(b, "opl3") == 0) opts.force_backend = 0; else if (std::strcmp(b, "sf") == 0 || std::strcmp(b, "soundfont") == 0) opts.force_backend = 1; else if (std::strcmp(b, "custom") == 0) opts.force_backend = 2; + else { + LOG_ERROR("Invalid --music-backend value: %s", b); + return 1; + } } else if (std::strcmp(argv[i], "--skip-intro") == 0) { opts.skip_intro = true; } else if (std::strcmp(argv[i], "--smoke-test") == 0 && i + 1 < argc) { - opts.smoke_test_frames = std::atoi(argv[++i]); + if (!parse_int_arg(argv[++i], 1, 3600, opts.smoke_test_frames)) { + LOG_ERROR("Invalid --smoke-test frame count (expected 1..3600)"); + return 1; + } } else if (std::strcmp(argv[i], "--screenshot") == 0 && i + 1 < argc) { opts.screenshot_path = argv[++i]; } else if (std::strcmp(argv[i], "--menu") == 0 && i + 1 < argc) { @@ -67,6 +92,7 @@ int main(int argc, char** argv) { game::GameApp app; if (!app.init(opts)) { + app.shutdown(); return 1; } int rc = app.run(); diff --git a/src/render/gl_api.cpp b/src/render/gl_api.cpp index dcdddc7..5fba8f2 100644 --- a/src/render/gl_api.cpp +++ b/src/render/gl_api.cpp @@ -43,6 +43,7 @@ PFNGLUNIFORM3FPROC Uniform3f = nullptr; PFNGLUNIFORM4FPROC Uniform4f = nullptr; PFNGLUNIFORM3FVPROC Uniform3fv = nullptr; PFNGLUNIFORM4FVPROC Uniform4fv = nullptr; +PFNGLUNIFORM1FVPROC Uniform1fv = nullptr; PFNGLUNIFORMMATRIX4FVPROC UniformMatrix4fv = nullptr; PFNGLGENFRAMEBUFFERSPROC GenFramebuffers = nullptr; @@ -114,6 +115,7 @@ bool init() { ok &= load_fn(Uniform4f, "glUniform4f"); ok &= load_fn(Uniform3fv, "glUniform3fv"); ok &= load_fn(Uniform4fv, "glUniform4fv"); + ok &= load_fn(Uniform1fv, "glUniform1fv"); ok &= load_fn(UniformMatrix4fv, "glUniformMatrix4fv"); ok &= load_fn(GenFramebuffers, "glGenFramebuffers"); diff --git a/src/render/gl_api.hpp b/src/render/gl_api.hpp index df7263b..d5684ef 100644 --- a/src/render/gl_api.hpp +++ b/src/render/gl_api.hpp @@ -49,6 +49,7 @@ extern PFNGLUNIFORM3FPROC Uniform3f; extern PFNGLUNIFORM4FPROC Uniform4f; extern PFNGLUNIFORM3FVPROC Uniform3fv; extern PFNGLUNIFORM4FVPROC Uniform4fv; +extern PFNGLUNIFORM1FVPROC Uniform1fv; extern PFNGLUNIFORMMATRIX4FVPROC UniformMatrix4fv; extern PFNGLGENFRAMEBUFFERSPROC GenFramebuffers; diff --git a/src/render/shader.cpp b/src/render/shader.cpp index 08e351b..1557b7b 100644 --- a/src/render/shader.cpp +++ b/src/render/shader.cpp @@ -1,6 +1,7 @@ #include "render/shader.hpp" #include "core/log.hpp" +#include #include namespace top_octane::render { @@ -62,6 +63,7 @@ bool ShaderProgram::build(const char* vs_src, const char* fs_src, const char* de return false; } program_ = prog; + uniform_cache_.clear(); return true; } @@ -70,51 +72,69 @@ void ShaderProgram::destroy() { gl::DeleteProgram(program_); } program_ = 0; + uniform_cache_.clear(); } void ShaderProgram::use() const { gl::UseProgram(program_); } -void ShaderProgram::set_int(const char* name, int val) const { +GLint ShaderProgram::get_uniform_location(const char* name) const { + if (!name || program_ == 0) return -1; + const std::string_view sv(name); + for (const auto& kv : uniform_cache_) { + if (kv.first == sv) return kv.second; + } GLint loc = gl::GetUniformLocation(program_, name); + uniform_cache_.emplace_back(std::string(sv), loc); + return loc; +} + +void ShaderProgram::set_int(const char* name, int val) const { + GLint loc = get_uniform_location(name); if (loc >= 0) gl::Uniform1i(loc, val); } void ShaderProgram::set_float(const char* name, float val) const { - GLint loc = gl::GetUniformLocation(program_, name); + GLint loc = get_uniform_location(name); if (loc >= 0) gl::Uniform1f(loc, val); } void ShaderProgram::set_vec2(const char* name, float x, float y) const { - GLint loc = gl::GetUniformLocation(program_, name); + GLint loc = get_uniform_location(name); if (loc >= 0) gl::Uniform2f(loc, x, y); } void ShaderProgram::set_vec3(const char* name, const Vec3& v) const { - GLint loc = gl::GetUniformLocation(program_, name); + GLint loc = get_uniform_location(name); if (loc >= 0) gl::Uniform3f(loc, v.x, v.y, v.z); } void ShaderProgram::set_vec4(const char* name, const Vec4& v) const { - GLint loc = gl::GetUniformLocation(program_, name); + GLint loc = get_uniform_location(name); if (loc >= 0) gl::Uniform4f(loc, v.x, v.y, v.z, v.w); } +void ShaderProgram::set_float_array(const char* name, const float* vals, int count) const { + if (!vals || count <= 0) return; + GLint loc = get_uniform_location(name); + if (loc >= 0) gl::Uniform1fv(loc, count, vals); +} + void ShaderProgram::set_vec3_array(const char* name, const Vec3* vals, int count) const { if (!vals || count <= 0) return; - GLint loc = gl::GetUniformLocation(program_, name); + GLint loc = get_uniform_location(name); if (loc >= 0) gl::Uniform3fv(loc, count, &vals[0].x); } void ShaderProgram::set_vec4_array(const char* name, const Vec4* vals, int count) const { if (!vals || count <= 0) return; - GLint loc = gl::GetUniformLocation(program_, name); + GLint loc = get_uniform_location(name); if (loc >= 0) gl::Uniform4fv(loc, count, &vals[0].x); } void ShaderProgram::set_mat4(const char* name, const Mat4& m) const { - GLint loc = gl::GetUniformLocation(program_, name); + GLint loc = get_uniform_location(name); if (loc >= 0) gl::UniformMatrix4fv(loc, 1, GL_FALSE, m.m); } diff --git a/src/render/shader.hpp b/src/render/shader.hpp index bc73dac..d989013 100644 --- a/src/render/shader.hpp +++ b/src/render/shader.hpp @@ -4,6 +4,8 @@ #include "render/gl_api.hpp" #include +#include +#include namespace top_octane::render { @@ -26,12 +28,16 @@ public: void set_vec2(const char* name, float x, float y) const; void set_vec3(const char* name, const Vec3& v) const; void set_vec4(const char* name, const Vec4& v) const; + void set_float_array(const char* name, const float* vals, int count) const; void set_vec3_array(const char* name, const Vec3* vals, int count) const; void set_vec4_array(const char* name, const Vec4* vals, int count) const; void set_mat4(const char* name, const Mat4& m) const; private: + GLint get_uniform_location(const char* name) const; + GLuint program_ = 0; + mutable std::vector> uniform_cache_; }; } // namespace top_octane::render diff --git a/src/render/ui_renderer.cpp b/src/render/ui_renderer.cpp index a182373..b1db47a 100644 --- a/src/render/ui_renderer.cpp +++ b/src/render/ui_renderer.cpp @@ -120,6 +120,50 @@ const Glyph5x7& get_glyph(char ch) { return kBlank; } +void blit_with_rgb_bleed(std::vector& atlas, int atlas_w, int atlas_h, + int px, int py, const assets::SpriteImage& sp) { + const int w = sp.width; + const int h = sp.height; + for (int sy = 0; sy < h; ++sy) { + const uint8_t* src = &sp.rgba[static_cast(sy) * w * 4u]; + uint8_t* dst = &atlas[(static_cast(py + sy) * atlas_w + px) * 4u]; + std::copy(src, src + static_cast(w) * 4u, dst); + } + static constexpr int kDx[4] = {-1, 1, 0, 0}; + static constexpr int kDy[4] = {0, 0, -1, 1}; + for (int sy = -1; sy <= h; ++sy) { + int ay = py + sy; + if (ay < 0 || ay >= atlas_h) continue; + for (int sx = -1; sx <= w; ++sx) { + int ax = px + sx; + if (ax < 0 || ax >= atlas_w) continue; + if (sx >= 0 && sx < w && sy >= 0 && sy < h && + sp.rgba[(static_cast(sy) * w + sx) * 4u + 3u] > 0) { + continue; + } + int sr = 0, sg = 0, sb = 0, cnt = 0; + for (int k = 0; k < 4; ++k) { + int nx = sx + kDx[k]; + int ny = sy + kDy[k]; + if (nx < 0 || nx >= w || ny < 0 || ny >= h) continue; + size_t si = (static_cast(ny) * w + nx) * 4u; + if (sp.rgba[si + 3u] > 0) { + sr += sp.rgba[si + 0u]; + sg += sp.rgba[si + 1u]; + sb += sp.rgba[si + 2u]; + ++cnt; + } + } + if (cnt > 0) { + size_t di = (static_cast(ay) * atlas_w + ax) * 4u; + atlas[di + 0u] = static_cast(sr / cnt); + atlas[di + 1u] = static_cast(sg / cnt); + atlas[di + 2u] = static_cast(sb / cnt); + } + } + } +} + } // namespace UiRenderer::~UiRenderer() { @@ -144,16 +188,74 @@ void UiRenderer::load_bank(const Vfs& vfs, const assets::Palette& pal, LOG_WARN("Optional sprite bank failed to load: %s", stem.c_str()); return; } - auto& vec = banks_[key]; - vec.resize(sb.sprites.size()); + auto& bank = banks_[key]; + if (bank.tex) { + glDeleteTextures(1, &bank.tex); + bank.tex = 0; + } + bank.sprites.assign(sb.sprites.size(), BankSpriteRect{}); + + struct Placement { + size_t idx = 0; + int x = 0; + int y = 0; + int w = 0; + int h = 0; + }; + int max_w = 0; + std::vector order; + order.reserve(sb.sprites.size()); for (size_t i = 0; i < sb.sprites.size(); ++i) { const auto& sp = sb.sprites[i]; if (sp.width > 0 && sp.height > 0 && !sp.rgba.empty()) { - vec[i].width = sp.width; - vec[i].height = sp.height; - upload_rgba(vec[i].tex, sp.width, sp.height, sp.rgba.data(), true); + max_w = std::max(max_w, sp.width); + order.push_back(i); } } + if (order.empty()) return; + + std::sort(order.begin(), order.end(), [&](size_t a, size_t b) { + return sb.sprites[a].height > sb.sprites[b].height; + }); + + constexpr int kPad = 2; + const int atlas_w = std::max(1024, max_w + kPad * 2); + int cur_x = kPad; + int cur_y = kPad; + int row_h = 0; + std::vector placed; + placed.reserve(order.size()); + for (size_t idx : order) { + const auto& sp = sb.sprites[idx]; + if (cur_x + sp.width + kPad > atlas_w) { + cur_x = kPad; + cur_y += row_h + kPad; + row_h = 0; + } + placed.push_back({idx, cur_x, cur_y, sp.width, sp.height}); + cur_x += sp.width + kPad; + row_h = std::max(row_h, sp.height); + } + int needed_h = cur_y + row_h + kPad; + int atlas_h = std::max(64, ((needed_h + 15) / 16) * 16); + std::vector pixels(static_cast(atlas_w) * static_cast(atlas_h) * 4u, 0); + + for (const auto& pl : placed) { + const auto& sp = sb.sprites[pl.idx]; + blit_with_rgb_bleed(pixels, atlas_w, atlas_h, pl.x, pl.y, sp); + BankSpriteRect r; + r.valid = true; + r.width = pl.w; + r.height = pl.h; + float u_in = (pl.w > 1) ? 0.5f : 0.0f; + float v_in = (pl.h > 1) ? 0.5f : 0.0f; + r.u0 = (static_cast(pl.x) + u_in) / static_cast(atlas_w); + r.v0 = (static_cast(pl.y) + v_in) / static_cast(atlas_h); + r.u1 = (static_cast(pl.x + pl.w) - u_in) / static_cast(atlas_w); + r.v1 = (static_cast(pl.y + pl.h) - v_in) / static_cast(atlas_h); + bank.sprites[pl.idx] = r; + } + upload_rgba(bank.tex, atlas_w, atlas_h, pixels.data(), true); } bool UiRenderer::init(const Vfs& vfs, const assets::Palette& pal) { @@ -275,16 +377,7 @@ bool UiRenderer::load_font_atlas(const Vfs& vfs, const assets::Palette& pal, const auto& sp = sb.sprites[static_cast(ch + 1)]; const int gx = px_x[ch]; const int gy = px_y[ch]; - for (int y = 0; y < sp.height; ++y) { - for (int x = 0; x < sp.width; ++x) { - size_t src = (static_cast(y) * sp.width + x) * 4u; - size_t dst = (static_cast(gy + y) * atlas_w + (gx + x)) * 4u; - pixels[dst + 0] = sp.rgba[src + 0]; - pixels[dst + 1] = sp.rgba[src + 1]; - pixels[dst + 2] = sp.rgba[src + 2]; - pixels[dst + 3] = sp.rgba[src + 3]; - } - } + blit_with_rgb_bleed(pixels, atlas_w, atlas_h, gx, gy, sp); FontGlyph& fg = out.glyphs[ch]; fg.valid = true; fg.u0 = static_cast(gx) / static_cast(atlas_w); @@ -298,7 +391,6 @@ bool UiRenderer::load_font_atlas(const Vfs& vfs, const assets::Palette& pal, } void UiRenderer::shutdown() { - if (!initialized_) return; if (white_tex_) glDeleteTextures(1, &white_tex_); if (stream_tex_) glDeleteTextures(1, &stream_tex_); if (font_large_.tex) glDeleteTextures(1, &font_large_.tex); @@ -310,10 +402,8 @@ void UiRenderer::shutdown() { for (auto& [k, s] : screens_) { if (s.tex) glDeleteTextures(1, &s.tex); } - for (auto& [k, vec] : banks_) { - for (auto& s : vec) { - if (s.tex) glDeleteTextures(1, &s.tex); - } + for (auto& [k, atlas] : banks_) { + if (atlas.tex) glDeleteTextures(1, &atlas.tex); } screens_.clear(); banks_.clear(); @@ -322,6 +412,10 @@ void UiRenderer::shutdown() { if (vbo_) gl::DeleteBuffers(1, &vbo_); } white_tex_ = stream_tex_ = vao_ = vbo_ = 0; + vbo_cap_ = 0; + stream_w_ = stream_h_ = 0; + verts_.clear(); + batches_.clear(); ui_shader_.destroy(); initialized_ = false; } @@ -372,9 +466,13 @@ void UiRenderer::end() { gl::BindVertexArray(vao_); gl::BindBuffer(GL_ARRAY_BUFFER, vbo_); - gl::BufferData(GL_ARRAY_BUFFER, - static_cast(verts_.size() * sizeof(UiVertex)), - verts_.data(), GL_DYNAMIC_DRAW); + const size_t bytes = verts_.size() * sizeof(UiVertex); + if (bytes <= vbo_cap_) { + gl::BufferSubData(GL_ARRAY_BUFFER, 0, static_cast(bytes), verts_.data()); + } else { + gl::BufferData(GL_ARRAY_BUFFER, static_cast(bytes), verts_.data(), GL_DYNAMIC_DRAW); + vbo_cap_ = bytes; + } gl::ActiveTexture(GL_TEXTURE0); for (const auto& b : batches_) { @@ -421,26 +519,36 @@ void UiRenderer::draw_line(float x0, float y0, float x1, float y1, float thickne } } -const UiRenderer::FontAtlas* UiRenderer::resolve_font(float scale, UiFont font) const { +UiFont UiRenderer::resolve_concrete_font(float scale, UiFont font) const { switch (font) { case UiFont::Pixel5x7: - return nullptr; + return UiFont::Pixel5x7; case UiFont::Panel: - if (font_panel_.tex) return &font_panel_; - if (font_large_.tex) return &font_large_; - return font_small_.tex ? &font_small_ : nullptr; + if (font_panel_.tex) return UiFont::Panel; + if (font_large_.tex) return UiFont::MenuLarge; + return font_small_.tex ? UiFont::MenuSmall : UiFont::Pixel5x7; case UiFont::MenuLarge: - if (font_large_.tex) return &font_large_; - return font_small_.tex ? &font_small_ : nullptr; + if (font_large_.tex) return UiFont::MenuLarge; + return font_small_.tex ? UiFont::MenuSmall : UiFont::Pixel5x7; case UiFont::MenuSmall: - if (font_small_.tex) return &font_small_; - return font_large_.tex ? &font_large_ : nullptr; + if (font_small_.tex) return UiFont::MenuSmall; + return font_large_.tex ? UiFont::MenuLarge : UiFont::Pixel5x7; case UiFont::Auto: default: - if (scale >= 2.15f && font_large_.tex) return &font_large_; - if (font_small_.tex) return &font_small_; - if (font_large_.tex) return &font_large_; - return nullptr; + if (scale >= 2.15f && font_large_.tex) return UiFont::MenuLarge; + if (font_small_.tex) return UiFont::MenuSmall; + if (font_large_.tex) return UiFont::MenuLarge; + return UiFont::Pixel5x7; + } +} + +const UiRenderer::FontAtlas* UiRenderer::resolve_font(float scale, UiFont font) const { + switch (resolve_concrete_font(scale, font)) { + case UiFont::Panel: return font_panel_.tex ? &font_panel_ : nullptr; + case UiFont::MenuLarge: return font_large_.tex ? &font_large_ : nullptr; + case UiFont::MenuSmall: return font_small_.tex ? &font_small_ : nullptr; + case UiFont::Pixel5x7: + default: return nullptr; } } @@ -540,25 +648,27 @@ void UiRenderer::draw_text_centered(float cx, float y, float scale, const std::s void UiRenderer::draw_text_fit(float x, float y, float max_w, float scale, const std::string& text, const Vec4& color, bool shadow, UiFont font) { - float w = measure_text_w(text, scale, font); + const UiFont locked_font = resolve_concrete_font(scale, font); + float w = measure_text_w(text, scale, locked_font); float eff = scale; if (w > max_w && max_w > 1.0f) { eff = scale * (max_w / w); - y += (measure_text_h(scale, font) - measure_text_h(eff, font)) * 0.5f; + y += (measure_text_h(scale, locked_font) - measure_text_h(eff, locked_font)) * 0.5f; } - draw_text(x, y, eff, text, color, shadow, font); + draw_text(x, y, eff, text, color, shadow, locked_font); } void UiRenderer::draw_text_centered_fit(float cx, float y, float max_w, float scale, const std::string& text, const Vec4& color, bool shadow, UiFont font) { - float w = measure_text_w(text, scale, font); + const UiFont locked_font = resolve_concrete_font(scale, font); + float w = measure_text_w(text, scale, locked_font); float eff = scale; if (w > max_w && max_w > 1.0f) { eff = scale * (max_w / w); - y += (measure_text_h(scale, font) - measure_text_h(eff, font)) * 0.5f; + y += (measure_text_h(scale, locked_font) - measure_text_h(eff, locked_font)) * 0.5f; } - draw_text_centered(cx, y, eff, text, color, shadow, font); + draw_text_centered(cx, y, eff, text, color, shadow, locked_font); } void UiRenderer::draw_screen_cover(const std::string& screen_key, float alpha) { @@ -589,21 +699,27 @@ void UiRenderer::draw_screen_4_3(const std::string& screen_key, float alpha) { void UiRenderer::draw_bank_sprite(const std::string& bank_key, int index, float x, float y, float scale, const Vec4& tint) { auto it = banks_.find(bank_key); - if (it == banks_.end() || index < 0 || static_cast(index) >= it->second.size()) return; - const auto& sp = it->second[index]; - if (!sp.tex || sp.width <= 0 || sp.height <= 0) return; - push_quad(sp.tex, x, y, x + sp.width * scale, y + sp.height * scale, 0, 0, 1, 1, tint); + if (it == banks_.end() || !it->second.tex || index < 0 || + static_cast(index) >= it->second.sprites.size()) { + return; + } + const auto& sp = it->second.sprites[static_cast(index)]; + if (!sp.valid || sp.width <= 0 || sp.height <= 0) return; + push_quad(it->second.tex, x, y, x + sp.width * scale, y + sp.height * scale, + sp.u0, sp.v0, sp.u1, sp.v1, tint); } bool UiRenderer::get_bank_sprite_size(const std::string& bank_key, int index, int& out_w, int& out_h) const { auto it = banks_.find(bank_key); - if (it == banks_.end() || index < 0 || static_cast(index) >= it->second.size()) { + if (it == banks_.end() || index < 0 || + static_cast(index) >= it->second.sprites.size()) { return false; } - out_w = it->second[index].width; - out_h = it->second[index].height; - return out_w > 0 && out_h > 0; + const auto& sp = it->second.sprites[static_cast(index)]; + out_w = sp.width; + out_h = sp.height; + return sp.valid && out_w > 0 && out_h > 0; } void UiRenderer::update_stream_rgba(int w, int h, const uint8_t* rgba) { diff --git a/src/render/ui_renderer.hpp b/src/render/ui_renderer.hpp index 58174a6..cf77b34 100644 --- a/src/render/ui_renderer.hpp +++ b/src/render/ui_renderer.hpp @@ -103,6 +103,18 @@ private: std::array glyphs{}; // indexed by ASCII code (0..95) }; + struct BankSpriteRect { + bool valid = false; + int width = 0; + int height = 0; + float u0 = 0.0f, v0 = 0.0f, u1 = 0.0f, v1 = 0.0f; + }; + + struct SpriteBankAtlas { + GLuint tex = 0; + std::vector sprites; + }; + void upload_rgba(GLuint& tex, int w, int h, const uint8_t* rgba, bool linear); void push_quad(GLuint tex, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, const Vec4& c); @@ -110,6 +122,7 @@ private: const std::string& key, const std::string& stem); bool load_font_atlas(const Vfs& vfs, const assets::Palette& pal, const std::string& stem, FontAtlas& out); + UiFont resolve_concrete_font(float scale, UiFont font) const; const FontAtlas* resolve_font(float scale, UiFont font) const; void draw_fallback_glyph(char ch, float x, float y, float cell_h, float cell_w, const Vec4& color); @@ -117,6 +130,7 @@ private: bool initialized_ = false; ShaderProgram ui_shader_; GLuint vao_ = 0, vbo_ = 0; + size_t vbo_cap_ = 0; GLuint white_tex_ = 0; GLuint stream_tex_ = 0; int stream_w_ = 0, stream_h_ = 0; @@ -131,7 +145,7 @@ private: FontAtlas font_panel_{}; std::unordered_map screens_; - std::unordered_map> banks_; + std::unordered_map banks_; std::vector verts_; std::vector batches_; diff --git a/src/render/world_geometry.cpp b/src/render/world_geometry.cpp index b92131c..b3e8637 100644 --- a/src/render/world_geometry.cpp +++ b/src/render/world_geometry.cpp @@ -59,9 +59,9 @@ float terrain_vertex_ao(const assets::LevelData& level, int vx, int vz) { int cidx = -m.tex_or_col; if (cidx <= 0 || cidx >= assets::kMaxColumns) continue; uint16_t mask = level.columns[cidx].shape_mask; - if ((mask & 0x03u) != 0) { + if ((mask & 0x01u) != 0) { ++solid_base; - } else if ((mask & 0x3Cu) != 0) { + } else if ((mask & 0xFEu) != 0) { overpass = true; } } @@ -157,14 +157,49 @@ WorldGeometry build_level_geometry(const assets::LevelData& level) { size_t cidx = static_cast(z) * gw + x; uint32_t base = static_cast(cidx * 4u); build_cell_quad(level, x, z, &geo.terrain_verts[base]); + } + } - // Counter-clockwise upward-facing winding (+Y normal) - geo.terrain_indices.push_back(base + 0); - geo.terrain_indices.push_back(base + 3); - geo.terrain_indices.push_back(base + 2); - geo.terrain_indices.push_back(base + 0); - geo.terrain_indices.push_back(base + 2); - geo.terrain_indices.push_back(base + 1); + const int cs = WorldGeometry::kTerrainChunkSize; + const int chunks_x = (gw + cs - 1) / cs; + const int chunks_z = (gh + cs - 1) / cs; + geo.terrain_chunks.reserve(static_cast(chunks_x) * static_cast(chunks_z)); + for (int cz = 0; cz < chunks_z; ++cz) { + int z0 = cz * cs; + int z1 = std::min(z0 + cs, gh); + for (int cx = 0; cx < chunks_x; ++cx) { + int x0 = cx * cs; + int x1 = std::min(x0 + cs, gw); + TerrainChunk chunk; + chunk.first_index = static_cast(geo.terrain_indices.size()); + Vec3 min_b(1e9f, 1e9f, 1e9f); + Vec3 max_b(-1e9f, -1e9f, -1e9f); + for (int z = z0; z < z1; ++z) { + for (int x = x0; x < x1; ++x) { + size_t cidx = static_cast(z) * gw + x; + uint32_t base = static_cast(cidx * 4u); + // Counter-clockwise upward-facing winding (+Y normal), split along (00)-(11) + geo.terrain_indices.push_back(base + 0); + geo.terrain_indices.push_back(base + 3); + geo.terrain_indices.push_back(base + 2); + geo.terrain_indices.push_back(base + 0); + geo.terrain_indices.push_back(base + 2); + geo.terrain_indices.push_back(base + 1); + for (uint32_t k = 0; k < 4; ++k) { + const Vec3& p = geo.terrain_verts[base + k].pos; + min_b.x = std::min(min_b.x, p.x); + min_b.y = std::min(min_b.y, p.y); + min_b.z = std::min(min_b.z, p.z); + max_b.x = std::max(max_b.x, p.x); + max_b.y = std::max(max_b.y, p.y); + max_b.z = std::max(max_b.z, p.z); + } + } + } + chunk.index_count = static_cast(geo.terrain_indices.size()) - chunk.first_index; + chunk.min_b = min_b; + chunk.max_b = max_b; + geo.terrain_chunks.push_back(chunk); } } @@ -255,16 +290,27 @@ void rebuild_column_geometry(const assets::LevelData& level, top_corner_ao(level, x + 1, z + 1, x, z, slot), top_corner_ao(level, x, z + 1, x, z, slot)); } - // 5: Bottom (-Y) - needed for elevated overpass/gantry blocks + // 5: Bottom (-Y) - needed for elevated overpass/gantry blocks; split along (00)-(11) matching Top/Terrain if (slot > 0 && !has_block_at(level, x, z, slot - 1)) { Vec3 p0(fx, b01, fz + 1), p1(fx + 1, b11, fz + 1); Vec3 p2(fx + 1, b10, fz), p3(fx, b00, fz); - Vec3 bot_n = (p3 - p0).cross(p2 - p0) + (p2 - p0).cross(p1 - p0); + Vec3 bot_n = (p2 - p3).cross(p1 - p3) + (p1 - p3).cross(p0 - p3); bot_n = (bot_n.len_sq() > 1e-6f) ? bot_n.normalized() : Vec3(0, -1, 0); - emit_quad(column_verts, column_indices, - p0, p1, p2, p3, - bot_n, blk.tex[5], blk.attrs[5] & 7u, lgt * 0.70f, - 0.85f, 0.85f, 0.85f, 0.85f); + float u[4], v[4]; + dihedral_uvs(blk.attrs[5] & 7u, u, v); + uint32_t base = static_cast(column_verts.size()); + float tile = static_cast(blk.tex[5]); + float bl = lgt * 0.70f; + column_verts.push_back({p0, bot_n, u[0], v[0], tile, bl, 0.85f}); + column_verts.push_back({p1, bot_n, u[1], v[1], tile, bl, 0.85f}); + column_verts.push_back({p2, bot_n, u[2], v[2], tile, bl, 0.85f}); + column_verts.push_back({p3, bot_n, u[3], v[3], tile, bl, 0.85f}); + column_indices.push_back(base + 3); + column_indices.push_back(base + 2); + column_indices.push_back(base + 1); + column_indices.push_back(base + 3); + column_indices.push_back(base + 1); + column_indices.push_back(base + 0); } } } @@ -275,6 +321,7 @@ void update_terrain_region(const assets::LevelData& level, int x0, int z0, int x std::vector& terrain_verts) { const int gw = assets::kMapWidth - 1; const int gh = assets::kMapHeight - 1; + if (x0 > x1 || z0 > z1 || x1 < 0 || z1 < 0 || x0 >= gw || z0 >= gh) return; x0 = std::clamp(x0, 0, gw - 1); z0 = std::clamp(z0, 0, gh - 1); x1 = std::clamp(x1, 0, gw - 1); @@ -289,6 +336,51 @@ void update_terrain_region(const assets::LevelData& level, int x0, int z0, int x } } +void refresh_terrain_chunk_bounds(WorldGeometry& geo, int x0, int z0, int x1, int z1) { + const int gw = assets::kMapWidth - 1; + const int gh = assets::kMapHeight - 1; + const int cs = WorldGeometry::kTerrainChunkSize; + const int chunks_x = (gw + cs - 1) / cs; + const int chunks_z = (gh + cs - 1) / cs; + if (x0 > x1 || z0 > z1 || x1 < 0 || z1 < 0 || x0 >= gw || z0 >= gh) return; + if (geo.terrain_verts.size() < static_cast(gw) * gh * 4u || + geo.terrain_chunks.size() != static_cast(chunks_x) * chunks_z) { + return; + } + + int cx0 = std::clamp(x0 / cs, 0, chunks_x - 1); + int cx1 = std::clamp(x1 / cs, 0, chunks_x - 1); + int cz0 = std::clamp(z0 / cs, 0, chunks_z - 1); + int cz1 = std::clamp(z1 / cs, 0, chunks_z - 1); + for (int cz = cz0; cz <= cz1; ++cz) { + int rz0 = cz * cs; + int rz1 = std::min(rz0 + cs, gh); + for (int cx = cx0; cx <= cx1; ++cx) { + int rx0 = cx * cs; + int rx1 = std::min(rx0 + cs, gw); + Vec3 min_b(1e9f, 1e9f, 1e9f); + Vec3 max_b(-1e9f, -1e9f, -1e9f); + for (int z = rz0; z < rz1; ++z) { + for (int x = rx0; x < rx1; ++x) { + size_t base = (static_cast(z) * gw + x) * 4u; + for (size_t k = 0; k < 4; ++k) { + const Vec3& p = geo.terrain_verts[base + k].pos; + min_b.x = std::min(min_b.x, p.x); + min_b.y = std::min(min_b.y, p.y); + min_b.z = std::min(min_b.z, p.z); + max_b.x = std::max(max_b.x, p.x); + max_b.y = std::max(max_b.y, p.y); + max_b.z = std::max(max_b.z, p.z); + } + } + } + auto& ch = geo.terrain_chunks[static_cast(cz) * chunks_x + cx]; + ch.min_b = min_b; + ch.max_b = max_b; + } + } +} + ModelGeometry build_model_geometry(const assets::ModelMesh& mesh, const assets::Palette& pal) { ModelGeometry out; out.verts.reserve(mesh.triangles.size() * 3u); diff --git a/src/render/world_geometry.hpp b/src/render/world_geometry.hpp index de65f24..15d2025 100644 --- a/src/render/world_geometry.hpp +++ b/src/render/world_geometry.hpp @@ -30,9 +30,19 @@ struct ModelGpuVertex { float shade = 1.0f; }; +struct TerrainChunk { + uint32_t first_index = 0; + uint32_t index_count = 0; + Vec3 min_b{0.0f, 0.0f, 0.0f}; + Vec3 max_b{0.0f, 0.0f, 0.0f}; +}; + struct WorldGeometry { + static constexpr int kTerrainChunkSize = 16; + std::vector terrain_verts; std::vector terrain_indices; + std::vector terrain_chunks; std::vector column_verts; std::vector column_indices; @@ -50,6 +60,9 @@ WorldGeometry build_level_geometry(const assets::LevelData& level); void update_terrain_region(const assets::LevelData& level, int x0, int z0, int x1, int z1, std::vector& terrain_verts); +// Refreshes AABB bounds for terrain chunks intersecting [x0..x1] x [z0..z1] +void refresh_terrain_chunk_bounds(WorldGeometry& geo, int x0, int z0, int x1, int z1); + // Rebuilds 3D column mesh from current level map & column definitions (for live morphs) void rebuild_column_geometry(const assets::LevelData& level, std::vector& column_verts, diff --git a/src/render/world_renderer.cpp b/src/render/world_renderer.cpp index 25785cd..09634bf 100644 --- a/src/render/world_renderer.cpp +++ b/src/render/world_renderer.cpp @@ -2,8 +2,10 @@ #include "core/log.hpp" #include +#include #include #include +#include namespace top_octane::render { @@ -54,6 +56,7 @@ uniform vec3 uCamPos; uniform vec3 uFogColor; uniform float uDrawDist; uniform float uModernLighting; +uniform float uUseShadowMap; uniform vec3 uSunDir; uniform vec3 uSunColor; uniform vec3 uSkyColor; @@ -63,6 +66,7 @@ uniform vec4 uLightPosRad[12]; uniform vec4 uLightColInt[12]; uniform int uCraftShadowCount; uniform vec4 uCraftShadows[10]; +uniform float uCraftShadowFloorY[10]; out vec4 FragColor; @@ -133,16 +137,16 @@ void main() { vec3 V = normalize(uCamPos - vWorldPos); float ndl = max(dot(N, sunDir), 0.0); - float shadow = sampleShadow(vWorldPos, normalize(vNormal), ndl); + float shadow = (uUseShadowMap > 0.5) ? sampleShadow(vWorldPos, normalize(vNormal), ndl) : 1.0; float sunVis = mix(0.32, 1.0, shadow); - // Soft hovercraft contact shadow projected onto upward-facing road/deck surfaces + // Soft hovercraft contact shadow projected onto upward-facing same-layer road/deck surfaces float craftShadow = 1.0; if (N.y > 0.30 && uCraftShadowCount > 0) { for (int i = 0; i < uCraftShadowCount; ++i) { vec4 cs = uCraftShadows[i]; float dy = cs.y - vWorldPos.y; - if (dy >= -0.25 && dy <= 3.2) { + if (dy >= -0.25 && dy <= 3.2 && abs(vWorldPos.y - uCraftShadowFloorY[i]) <= 0.75) { vec2 d = vWorldPos.xz - cs.xz; float r2 = dot(d, d); float rad = cs.w * (1.0 + max(dy, 0.0) * 0.25); @@ -616,24 +620,16 @@ constexpr const char* kClassicFS = R"glsl( in vec2 vUv; uniform sampler2D uSceneTex; uniform sampler2D uPaletteTex; +uniform sampler3D uPaletteLut; uniform float uScanlines; uniform float uHeightPx; out vec4 FragColor; void main() { - vec3 col = texture(uSceneTex, vUv).rgb; - vec3 best = col; - float bestDist = 1e9; - // Quantize against authentic 256-color PALET0-0.DAT lookup texture - for (int i = 1; i < 256; ++i) { - vec3 p = texelFetch(uPaletteTex, ivec2(i, 0), 0).rgb; - vec3 d = col - p; - float d2 = dot(d, d); - if (d2 < bestDist) { - bestDist = d2; - best = p; - } - } + vec3 col = clamp(texture(uSceneTex, vUv).rgb, 0.0, 1.0); + vec3 lutCoord = (floor(col * 31.0 + 0.5) + 0.5) / 32.0; + int palIdx = clamp(int(texture(uPaletteLut, lutCoord).r * 255.0 + 0.5), 0, 255); + vec3 best = texelFetch(uPaletteTex, ivec2(palIdx, 0), 0).rgb; if (uScanlines > 0.5) { float row = mod(floor(vUv.y * uHeightPx), 2.0); if (row < 0.5) best *= 0.80; @@ -642,6 +638,44 @@ void main() { } )glsl"; +struct FrustumPlanes { + std::array p{}; +}; + +FrustumPlanes extract_frustum_planes(const Mat4& vp) { + const float* m = vp.m; + auto row = [&](int r) -> Vec4 { + return Vec4(m[r], m[4 + r], m[8 + r], m[12 + r]); + }; + Vec4 r0 = row(0), r1 = row(1), r2 = row(2), r3 = row(3); + auto add = [](const Vec4& a, const Vec4& b) { + return Vec4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); + }; + auto sub = [](const Vec4& a, const Vec4& b) { + return Vec4(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); + }; + FrustumPlanes fp; + fp.p[0] = add(r3, r0); // left + fp.p[1] = sub(r3, r0); // right + fp.p[2] = add(r3, r1); // bottom + fp.p[3] = sub(r3, r1); // top + fp.p[4] = add(r3, r2); // near + fp.p[5] = sub(r3, r2); // far + return fp; +} + +bool aabb_in_frustum(const FrustumPlanes& fp, const Vec3& bmin, const Vec3& bmax) { + for (const auto& pl : fp.p) { + float px = (pl.x >= 0.0f) ? bmax.x : bmin.x; + float py = (pl.y >= 0.0f) ? bmax.y : bmin.y; + float pz = (pl.z >= 0.0f) ? bmax.z : bmin.z; + if (pl.x * px + pl.y * py + pl.z * pz + pl.w < 0.0f) { + return false; + } + } + return true; +} + Mat4 build_model_matrix(const ModelInstance& inst) { return Mat4::translate(inst.pos) * Mat4::rotate_y(inst.yaw) * @@ -776,13 +810,13 @@ bool WorldRenderer::init(const Vfs& vfs, const assets::Palette& pal) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - // Shelf-pack world billboard sprites (DATA/TMAPS.DAT) with 1px transparent padding + // Shelf-pack world billboard sprites (DATA/TMAPS.DAT) with 2px gutter + 1px RGB bleed tmap_rects_.clear(); if (vfs.exists("DATA/TMAPS.DAT") && vfs.exists("DATA/TMAPS.TAB")) { assets::TmapBank tmaps; if (tmaps.load(vfs, pal) && !tmaps.sprites.empty()) { constexpr int kAtlasW = 512; - constexpr int kPad = 1; + constexpr int kPad = 2; struct Placement { size_t idx = 0; int x = 0; @@ -826,11 +860,47 @@ bool WorldRenderer::init(const Vfs& vfs, const assets::Palette& pal) { uint8_t* dst_row = &atlas_rgba[(static_cast(pl.y + sy) * kAtlasW + pl.x) * 4u]; std::copy(src_row, src_row + static_cast(pl.w) * 4u, dst_row); } + // 1px RGB dilation into transparent borders & gutter so GL_LINEAR doesn't bleed dark fringes + static constexpr int kDx[4] = {-1, 1, 0, 0}; + static constexpr int kDy[4] = {0, 0, -1, 1}; + for (int sy = -1; sy <= pl.h; ++sy) { + int ay = pl.y + sy; + if (ay < 0 || ay >= atlas_h) continue; + for (int sx = -1; sx <= pl.w; ++sx) { + int ax = pl.x + sx; + if (ax < 0 || ax >= kAtlasW) continue; + if (sx >= 0 && sx < pl.w && sy >= 0 && sy < pl.h && + sp.rgba[(static_cast(sy) * pl.w + sx) * 4u + 3u] > 0) { + continue; + } + int sr = 0, sg = 0, sb = 0, cnt = 0; + for (int k = 0; k < 4; ++k) { + int nx = sx + kDx[k]; + int ny = sy + kDy[k]; + if (nx < 0 || nx >= pl.w || ny < 0 || ny >= pl.h) continue; + size_t si = (static_cast(ny) * pl.w + nx) * 4u; + if (sp.rgba[si + 3u] > 0) { + sr += sp.rgba[si + 0u]; + sg += sp.rgba[si + 1u]; + sb += sp.rgba[si + 2u]; + ++cnt; + } + } + if (cnt > 0) { + size_t di = (static_cast(ay) * kAtlasW + ax) * 4u; + atlas_rgba[di + 0u] = static_cast(sr / cnt); + atlas_rgba[di + 1u] = static_cast(sg / cnt); + atlas_rgba[di + 2u] = static_cast(sb / cnt); + } + } + } TmapUvRect r; - r.u0 = static_cast(pl.x) / static_cast(kAtlasW); - r.v0 = static_cast(pl.y) / static_cast(atlas_h); - r.u1 = static_cast(pl.x + pl.w) / static_cast(kAtlasW); - r.v1 = static_cast(pl.y + pl.h) / static_cast(atlas_h); + float u_in = (pl.w > 1) ? 0.5f : 0.0f; + float v_in = (pl.h > 1) ? 0.5f : 0.0f; + r.u0 = (static_cast(pl.x) + u_in) / static_cast(kAtlasW); + r.v0 = (static_cast(pl.y) + v_in) / static_cast(atlas_h); + r.u1 = (static_cast(pl.x + pl.w) - u_in) / static_cast(kAtlasW); + r.v1 = (static_cast(pl.y + pl.h) - v_in) / static_cast(atlas_h); r.aspect = static_cast(pl.w) / static_cast(pl.h); r.valid = true; tmap_rects_[pl.idx] = r; @@ -849,7 +919,7 @@ bool WorldRenderer::init(const Vfs& vfs, const assets::Palette& pal) { } } - // Upload 256 x 1 palette texture for Classic Mode quantization + // Upload 256 x 1 palette texture + 32x32x32 3D LUT for O(1) Classic Mode quantization uint8_t pal_rgba[256 * 4]; for (int i = 0; i < 256; ++i) { pal_rgba[i * 4 + 0] = pal.colors[i].r; @@ -865,6 +935,33 @@ bool WorldRenderer::init(const Vfs& vfs, const assets::Palette& pal) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + constexpr int kLutSize = 32; + std::vector pal_lut(kLutSize * kLutSize * kLutSize); + for (int bz = 0; bz < kLutSize; ++bz) { + uint8_t b8 = static_cast((bz * 255 + 15) / 31); + for (int gy = 0; gy < kLutSize; ++gy) { + uint8_t g8 = static_cast((gy * 255 + 15) / 31); + for (int rx = 0; rx < kLutSize; ++rx) { + uint8_t r8 = static_cast((rx * 255 + 15) / 31); + pal_lut[(bz * kLutSize + gy) * kLutSize + rx] = pal.find_nearest(r8, g8, b8); + } + } + } + GLint prev_unpack = 4; + glGetIntegerv(GL_UNPACK_ALIGNMENT, &prev_unpack); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glGenTextures(1, &tex_palette_lut_); + glBindTexture(GL_TEXTURE_3D, tex_palette_lut_); + gl::TexImage3D(GL_TEXTURE_3D, 0, GL_R8, kLutSize, kLutSize, kLutSize, 0, + GL_RED, GL_UNSIGNED_BYTE, pal_lut.data()); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); + glBindTexture(GL_TEXTURE_3D, 0); + glPixelStorei(GL_UNPACK_ALIGNMENT, prev_unpack); + // Build cylindrical skybox mesh with zenith and nadir caps constexpr int kSegs = 32; constexpr float kSkyVTop = 112.0f / 256.0f; // 0.4375: true zenith row in SKY0-x @@ -980,7 +1077,6 @@ bool WorldRenderer::init(const Vfs& vfs, const assets::Palette& pal) { } void WorldRenderer::shutdown() { - if (!initialized_) return; destroy_mesh(terrain_mesh_); destroy_mesh(column_mesh_); for (auto& [k, m] : model_cache_) { @@ -1006,15 +1102,24 @@ void WorldRenderer::shutdown() { if (tex_obj_atlas_) glDeleteTextures(1, &tex_obj_atlas_); if (tex_tmaps_atlas_) glDeleteTextures(1, &tex_tmaps_atlas_); if (tex_palette_) glDeleteTextures(1, &tex_palette_); + if (tex_palette_lut_) glDeleteTextures(1, &tex_palette_lut_); if (classic_color_tex_) glDeleteTextures(1, &classic_color_tex_); if (shadow_depth_tex_) glDeleteTextures(1, &shadow_depth_tex_); sky_vao_ = sky_vbo_ = quad_vao_ = quad_vbo_ = part_vao_ = part_vbo_ = 0; billboard_vao_ = billboard_vbo_ = 0; + column_vbo_cap_ = column_ebo_cap_ = part_vbo_cap_ = billboard_vbo_cap_ = 0; classic_fbo_ = classic_depth_rbo_ = classic_color_tex_ = 0; shadow_fbo_ = shadow_depth_tex_ = 0; - tex_terrain_array_ = tex_sky_ = tex_obj_atlas_ = tex_tmaps_atlas_ = tex_palette_ = 0; + tex_terrain_array_ = tex_sky_ = tex_obj_atlas_ = tex_tmaps_atlas_ = tex_palette_ = tex_palette_lut_ = 0; tmap_rects_.clear(); + opaque_models_.clear(); + translucent_models_.clear(); + translucent_bb_idx_.clear(); + billboard_verts_.clear(); + part_alpha_idx_.clear(); + part_add_idx_.clear(); + part_verts_.clear(); classic_w_ = classic_h_ = 0; world_shader_.destroy(); @@ -1097,9 +1202,13 @@ bool WorldRenderer::load_level(const Vfs& vfs, const assets::LevelData& level, apply_texture_filtering(active_filter_); + destroy_mesh(terrain_mesh_); + destroy_mesh(column_mesh_); world_geo_ = build_level_geometry(level); upload_world_mesh(terrain_mesh_, world_geo_.terrain_verts, world_geo_.terrain_indices, true); upload_world_mesh(column_mesh_, world_geo_.column_verts, world_geo_.column_indices, true); + column_vbo_cap_ = world_geo_.column_verts.size() * sizeof(WorldVertex); + column_ebo_cap_ = world_geo_.column_indices.size() * sizeof(uint32_t); LOG_INFO("Loaded level %d GPU geometry: terrain_tris=%d, column_tris=%d", level.level_number, terrain_mesh_.index_count / 3, column_mesh_.index_count / 3); @@ -1108,16 +1217,18 @@ bool WorldRenderer::load_level(const Vfs& vfs, const assets::LevelData& level, void WorldRenderer::update_terrain_region(const assets::LevelData& level, int x0, int z0, int x1, int z1) { - render::update_terrain_region(level, x0, z0, x1, z1, world_geo_.terrain_verts); - if (!terrain_mesh_.vbo) return; - const int gw = assets::kMapWidth - 1; const int gh = assets::kMapHeight - 1; + if (x0 > x1 || z0 > z1 || x1 < 0 || z1 < 0 || x0 >= gw || z0 >= gh) return; x0 = std::clamp(x0, 0, gw - 1); z0 = std::clamp(z0, 0, gh - 1); x1 = std::clamp(x1, 0, gw - 1); z1 = std::clamp(z1, 0, gh - 1); + render::update_terrain_region(level, x0, z0, x1, z1, world_geo_.terrain_verts); + refresh_terrain_chunk_bounds(world_geo_, x0, z0, x1, z1); + if (!terrain_mesh_.vbo) return; + gl::BindBuffer(GL_ARRAY_BUFFER, terrain_mesh_.vbo); for (int z = z0; z <= z1; ++z) { size_t first_vert = (static_cast(z) * gw + x0) * 4u; @@ -1136,19 +1247,31 @@ void WorldRenderer::rebuild_columns(const assets::LevelData& level) { column_mesh_.index_count = 0; return; } + size_t vbytes = world_geo_.column_verts.size() * sizeof(WorldVertex); + size_t ibytes = world_geo_.column_indices.size() * sizeof(uint32_t); if (!column_mesh_.vao) { upload_world_mesh(column_mesh_, world_geo_.column_verts, world_geo_.column_indices, true); + column_vbo_cap_ = vbytes; + column_ebo_cap_ = ibytes; return; } gl::BindVertexArray(column_mesh_.vao); gl::BindBuffer(GL_ARRAY_BUFFER, column_mesh_.vbo); - gl::BufferData(GL_ARRAY_BUFFER, - static_cast(world_geo_.column_verts.size() * sizeof(WorldVertex)), - world_geo_.column_verts.data(), GL_DYNAMIC_DRAW); + if (vbytes <= column_vbo_cap_) { + gl::BufferSubData(GL_ARRAY_BUFFER, 0, static_cast(vbytes), world_geo_.column_verts.data()); + } else { + gl::BufferData(GL_ARRAY_BUFFER, static_cast(vbytes), + world_geo_.column_verts.data(), GL_DYNAMIC_DRAW); + column_vbo_cap_ = vbytes; + } gl::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, column_mesh_.ebo); - gl::BufferData(GL_ELEMENT_ARRAY_BUFFER, - static_cast(world_geo_.column_indices.size() * sizeof(uint32_t)), - world_geo_.column_indices.data(), GL_DYNAMIC_DRAW); + if (ibytes <= column_ebo_cap_) { + gl::BufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, static_cast(ibytes), world_geo_.column_indices.data()); + } else { + gl::BufferData(GL_ELEMENT_ARRAY_BUFFER, static_cast(ibytes), + world_geo_.column_indices.data(), GL_DYNAMIC_DRAW); + column_ebo_cap_ = ibytes; + } gl::BindVertexArray(0); gl::BindBuffer(GL_ARRAY_BUFFER, 0); column_mesh_.index_count = static_cast(world_geo_.column_indices.size()); @@ -1203,11 +1326,12 @@ bool WorldRenderer::ensure_model(const Vfs& vfs, const std::string& key, const a return true; } -void WorldRenderer::ensure_classic_fbo(int w, int h) { - if (classic_fbo_ != 0 && classic_w_ == w && classic_h_ == h) return; +bool WorldRenderer::ensure_classic_fbo(int w, int h) { + if (classic_fbo_ != 0 && classic_w_ == w && classic_h_ == h) return true; if (classic_fbo_) gl::DeleteFramebuffers(1, &classic_fbo_); if (classic_depth_rbo_) gl::DeleteRenderbuffers(1, &classic_depth_rbo_); if (classic_color_tex_) glDeleteTextures(1, &classic_color_tex_); + classic_fbo_ = classic_depth_rbo_ = classic_color_tex_ = 0; classic_w_ = w; classic_h_ = h; @@ -1228,7 +1352,18 @@ void WorldRenderer::ensure_classic_fbo(int w, int h) { gl::BindFramebuffer(GL_FRAMEBUFFER, classic_fbo_); gl::FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, classic_color_tex_, 0); gl::FramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, classic_depth_rbo_); + GLenum status = gl::CheckFramebufferStatus(GL_FRAMEBUFFER); gl::BindFramebuffer(GL_FRAMEBUFFER, 0); + if (status != GL_FRAMEBUFFER_COMPLETE) { + LOG_WARN("Classic FBO incomplete (0x%x); falling back to default framebuffer", status); + gl::DeleteFramebuffers(1, &classic_fbo_); + gl::DeleteRenderbuffers(1, &classic_depth_rbo_); + glDeleteTextures(1, &classic_color_tex_); + classic_fbo_ = classic_depth_rbo_ = classic_color_tex_ = 0; + classic_w_ = classic_h_ = 0; + return false; + } + return true; } void WorldRenderer::apply_texture_filtering(TextureFilterMode mode) { @@ -1268,9 +1403,13 @@ void WorldRenderer::begin_frame(int backbuffer_w, int backbuffer_h, const GameCo if (cfg.classic_mode) { int cw = cfg.classic_hires ? 640 : 320; int ch = cfg.classic_hires ? 480 : 200; - ensure_classic_fbo(cw, ch); - gl::BindFramebuffer(GL_FRAMEBUFFER, classic_fbo_); - glViewport(0, 0, cw, ch); + if (ensure_classic_fbo(cw, ch)) { + gl::BindFramebuffer(GL_FRAMEBUFFER, classic_fbo_); + glViewport(0, 0, cw, ch); + } else { + gl::BindFramebuffer(GL_FRAMEBUFFER, 0); + glViewport(0, 0, backbuffer_w_, backbuffer_h_); + } } else { gl::BindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, backbuffer_w_, backbuffer_h_); @@ -1286,11 +1425,26 @@ void WorldRenderer::render_world_view(const RenderCamera& cam, const std::vector const std::vector& lights, const std::vector& craft_shadows, const std::vector& billboards) { - int target_w = cfg.classic_mode ? classic_w_ : backbuffer_w_; - int target_h = cfg.classic_mode ? classic_h_ : backbuffer_h_; + const bool classic_fbo_active = cfg.classic_mode && classic_fbo_ != 0 && classic_w_ > 0 && classic_h_ > 0; + int target_w = classic_fbo_active ? classic_w_ : backbuffer_w_; + int target_h = classic_fbo_active ? classic_h_ : backbuffer_h_; const bool modern = !cfg.classic_mode; const WorldLightingTheme theme = theme_for_world(current_world_index_); + // Pre-resolve model pointers & transforms once per view for shadow + main + translucent passes + opaque_models_.clear(); + translucent_models_.clear(); + for (const auto& inst : models) { + auto it = model_cache_.find(inst.model_key); + if (it == model_cache_.end() || !it->second.vao) continue; + ResolvedModelDraw draw{&it->second, build_model_matrix(inst), inst.tint}; + if (inst.tint.w >= 0.99f) { + opaque_models_.push_back(draw); + } else { + translucent_models_.push_back(draw); + } + } + // 0. Directional Shadow Map Pass (Modern Mode only) Mat4 light_space = Mat4::identity(); const bool use_shadows = modern && shadow_fbo_ != 0 && shadow_depth_tex_ != 0; @@ -1326,7 +1480,20 @@ void WorldRenderer::render_world_view(const RenderCamera& cam, const std::vector shadow_world_shader_.set_mat4("uLightSpace", light_space); if (terrain_mesh_.vao && terrain_mesh_.index_count > 0) { gl::BindVertexArray(terrain_mesh_.vao); - glDrawElements(GL_TRIANGLES, terrain_mesh_.index_count, GL_UNSIGNED_INT, nullptr); + if (!world_geo_.terrain_chunks.empty()) { + constexpr float kShadowRange = 46.0f; + for (const auto& ch : world_geo_.terrain_chunks) { + if (ch.index_count == 0) continue; + if (ch.max_b.x < focus.x - kShadowRange || ch.min_b.x > focus.x + kShadowRange || + ch.max_b.z < focus.z - kShadowRange || ch.min_b.z > focus.z + kShadowRange) { + continue; + } + glDrawElements(GL_TRIANGLES, static_cast(ch.index_count), GL_UNSIGNED_INT, + reinterpret_cast(static_cast(ch.first_index) * sizeof(uint32_t))); + } + } else { + glDrawElements(GL_TRIANGLES, terrain_mesh_.index_count, GL_UNSIGNED_INT, nullptr); + } } if (column_mesh_.vao && column_mesh_.index_count > 0) { gl::BindVertexArray(column_mesh_.vao); @@ -1339,18 +1506,15 @@ void WorldRenderer::render_world_view(const RenderCamera& cam, const std::vector gl::ActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, tex_obj_atlas_); shadow_model_shader_.set_int("uAtlas", 0); - for (const auto& inst : models) { - if (inst.tint.w < 0.99f) continue; - auto it = model_cache_.find(inst.model_key); - if (it == model_cache_.end() || !it->second.vao) continue; - shadow_model_shader_.set_mat4("uModel", build_model_matrix(inst)); - gl::BindVertexArray(it->second.vao); - glDrawElements(GL_TRIANGLES, it->second.index_count, GL_UNSIGNED_INT, nullptr); + for (const auto& draw : opaque_models_) { + shadow_model_shader_.set_mat4("uModel", draw.model); + gl::BindVertexArray(draw.mesh->vao); + glDrawElements(GL_TRIANGLES, draw.mesh->index_count, GL_UNSIGNED_INT, nullptr); } glDisable(GL_POLYGON_OFFSET_FILL); } - if (cfg.classic_mode) { + if (classic_fbo_active) { gl::BindFramebuffer(GL_FRAMEBUFFER, classic_fbo_); } else { gl::BindFramebuffer(GL_FRAMEBUFFER, 0); @@ -1364,9 +1528,11 @@ void WorldRenderer::render_world_view(const RenderCamera& cam, const std::vector } glViewport(vx, vy, vw, vh); - float aspect = static_cast(vw) / static_cast(std::max(vh, 1)); + float aspect = classic_fbo_active + ? ((4.0f / 3.0f) * static_cast(std::max(split_count, 1))) + : (static_cast(vw) / static_cast(std::max(vh, 1))); float fov = cfg.classic_mode ? 62.0f : cfg.fov_deg; - if (split_count == 2) { + if (!classic_fbo_active && split_count == 2) { // Hor+ adjustment for wide split viewports aspect = std::max(aspect, 1.0f); } @@ -1375,6 +1541,7 @@ void WorldRenderer::render_world_view(const RenderCamera& cam, const std::vector Mat4 proj = Mat4::perspective(deg_to_rad(fov), aspect, cam.z_near, std::max(cam.z_far, draw_dist + 40.0f)); Mat4 view = Mat4::look_at(cam.eye, cam.target, cam.up); Mat4 view_proj = proj * view; + const FrustumPlanes frustum = extract_frustum_planes(view_proj); // Pack dynamic lights (up to 12) and craft contact shadows (up to 10) constexpr int kMaxLights = 12; @@ -1390,35 +1557,18 @@ void WorldRenderer::render_world_view(const RenderCamera& cam, const std::vector } int cshadow_count = modern ? std::min(static_cast(craft_shadows.size()), kMaxCraftShadows) : 0; Vec4 cshadow_spheres[kMaxCraftShadows]{}; + float cshadow_floor_y[kMaxCraftShadows]{}; for (int i = 0; i < cshadow_count; ++i) { cshadow_spheres[i] = Vec4(craft_shadows[i].pos.x, craft_shadows[i].pos.y, craft_shadows[i].pos.z, std::max(craft_shadows[i].radius, 0.25f)); + cshadow_floor_y[i] = craft_shadows[i].floor_y; } - // 1. Cylindrical Skybox (no translation, depth <= 1.0) - glDisable(GL_CULL_FACE); + // 1. Opaque Terrain (frustum & distance culled by 16x16 chunk) & 3D Columns glEnable(GL_DEPTH_TEST); - glDepthFunc(GL_LEQUAL); - glDepthMask(GL_FALSE); - if (tex_sky_ && sky_vao_) { - Mat4 view_no_trans = view; - view_no_trans.m[12] = view_no_trans.m[13] = view_no_trans.m[14] = 0.0f; - sky_shader_.use(); - sky_shader_.set_mat4("uViewProjNoTrans", proj * view_no_trans); - sky_shader_.set_vec3("uFogColor", fog_color_); - sky_shader_.set_vec3("uSunDir", theme.sun_dir); - sky_shader_.set_vec3("uSunColor", theme.sun_color); - sky_shader_.set_float("uModernLighting", modern ? 1.0f : 0.0f); - gl::ActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, tex_sky_); - sky_shader_.set_int("uSkyTex", 0); - gl::BindVertexArray(sky_vao_); - glDrawArrays(GL_TRIANGLES, 0, sky_vert_count_); - } - - // 2. Terrain & 3D Columns glDepthMask(GL_TRUE); glDepthFunc(GL_LESS); + glDisable(GL_BLEND); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); @@ -1429,6 +1579,7 @@ void WorldRenderer::render_world_view(const RenderCamera& cam, const std::vector world_shader_.set_vec3("uFogColor", fog_color_); world_shader_.set_float("uDrawDist", draw_dist); world_shader_.set_float("uModernLighting", modern ? 1.0f : 0.0f); + world_shader_.set_float("uUseShadowMap", use_shadows ? 1.0f : 0.0f); world_shader_.set_vec3("uSunDir", theme.sun_dir); world_shader_.set_vec3("uSunColor", theme.sun_color); world_shader_.set_vec3("uSkyColor", theme.sky_color); @@ -1441,6 +1592,7 @@ void WorldRenderer::render_world_view(const RenderCamera& cam, const std::vector world_shader_.set_int("uCraftShadowCount", cshadow_count); if (cshadow_count > 0) { world_shader_.set_vec4_array("uCraftShadows", cshadow_spheres, cshadow_count); + world_shader_.set_float_array("uCraftShadowFloorY", cshadow_floor_y, cshadow_count); } gl::ActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D_ARRAY, tex_terrain_array_); @@ -1454,14 +1606,31 @@ void WorldRenderer::render_world_view(const RenderCamera& cam, const std::vector if (terrain_mesh_.vao && terrain_mesh_.index_count > 0) { gl::BindVertexArray(terrain_mesh_.vao); - glDrawElements(GL_TRIANGLES, terrain_mesh_.index_count, GL_UNSIGNED_INT, nullptr); + if (!world_geo_.terrain_chunks.empty()) { + const float max_chunk_d2 = (draw_dist + 4.0f) * (draw_dist + 4.0f); + for (const auto& ch : world_geo_.terrain_chunks) { + if (ch.index_count == 0) continue; + float cx = std::clamp(cam.eye.x, ch.min_b.x, ch.max_b.x); + float cy = std::clamp(cam.eye.y, ch.min_b.y, ch.max_b.y); + float cz = std::clamp(cam.eye.z, ch.min_b.z, ch.max_b.z); + float d2 = (cx - cam.eye.x) * (cx - cam.eye.x) + + (cy - cam.eye.y) * (cy - cam.eye.y) + + (cz - cam.eye.z) * (cz - cam.eye.z); + if (d2 > max_chunk_d2) continue; + if (!aabb_in_frustum(frustum, ch.min_b, ch.max_b)) continue; + glDrawElements(GL_TRIANGLES, static_cast(ch.index_count), GL_UNSIGNED_INT, + reinterpret_cast(static_cast(ch.first_index) * sizeof(uint32_t))); + } + } else { + glDrawElements(GL_TRIANGLES, terrain_mesh_.index_count, GL_UNSIGNED_INT, nullptr); + } } if (column_mesh_.vao && column_mesh_.index_count > 0) { gl::BindVertexArray(column_mesh_.vao); glDrawElements(GL_TRIANGLES, column_mesh_.index_count, GL_UNSIGNED_INT, nullptr); } - // 3. 3D Models (opaque first, then translucent ghosts) + // 2. Opaque 3D Models glDisable(GL_CULL_FACE); // Bullfrog models mix face windings on thin fins/wings model_shader_.use(); model_shader_.set_mat4("uViewProj", view_proj); @@ -1491,29 +1660,25 @@ void WorldRenderer::render_world_view(const RenderCamera& cam, const std::vector } gl::ActiveTexture(GL_TEXTURE0); - auto draw_model = [&](const ModelInstance& inst) { - auto it = model_cache_.find(inst.model_key); - if (it == model_cache_.end() || !it->second.vao) return; - model_shader_.set_mat4("uModel", build_model_matrix(inst)); - model_shader_.set_vec4("uTint", inst.tint); - gl::BindVertexArray(it->second.vao); - glDrawElements(GL_TRIANGLES, it->second.index_count, GL_UNSIGNED_INT, nullptr); - }; - - for (const auto& inst : models) { - if (inst.tint.w >= 0.99f) draw_model(inst); + for (const auto& draw : opaque_models_) { + model_shader_.set_mat4("uModel", draw.model); + model_shader_.set_vec4("uTint", draw.tint); + gl::BindVertexArray(draw.mesh->vao); + glDrawElements(GL_TRIANGLES, draw.mesh->index_count, GL_UNSIGNED_INT, nullptr); } - // 3b. Textured World Billboards (authentic Bullfrog TMAPS powerup & pickup icons) + // 2b. Prepare Billboard Stream (opaque first for depth + early-Z skybox, then translucent sorted back-to-front) + billboard_verts_.clear(); + translucent_bb_idx_.clear(); + size_t opaque_bb_vert_count = 0; + size_t trans_bb_vert_count = 0; if (!billboards.empty() && tex_tmaps_atlas_ && billboard_vao_) { Vec3 cam_right(view.m[0], view.m[4], view.m[8]); Vec3 cam_up(view.m[1], view.m[5], view.m[9]); - std::vector bverts; - bverts.reserve(billboards.size() * 6 * 9); - for (const auto& b : billboards) { - if (b.tmap_id < 0 || static_cast(b.tmap_id) >= tmap_rects_.size()) continue; + auto emit_bb = [&](const WorldBillboard& b) { + if (b.tmap_id < 0 || static_cast(b.tmap_id) >= tmap_rects_.size()) return; const TmapUvRect& rect = tmap_rects_[static_cast(b.tmap_id)]; - if (!rect.valid) continue; + if (!rect.valid) return; Vec3 rx = cam_right * (b.size * 0.5f * rect.aspect); Vec3 ry = cam_up * (b.size * 0.5f); @@ -1521,73 +1686,137 @@ void WorldRenderer::render_world_view(const RenderCamera& cam, const std::vector Vec3 c1 = b.pos + rx - ry; Vec3 c2 = b.pos + rx + ry; Vec3 c3 = b.pos - rx + ry; - auto emit = [&](const Vec3& q, float u, float v) { - bverts.push_back(q.x); bverts.push_back(q.y); bverts.push_back(q.z); - bverts.push_back(u); bverts.push_back(v); - bverts.push_back(b.tint.x); bverts.push_back(b.tint.y); - bverts.push_back(b.tint.z); bverts.push_back(b.tint.w); + billboard_verts_.push_back(q.x); billboard_verts_.push_back(q.y); billboard_verts_.push_back(q.z); + billboard_verts_.push_back(u); billboard_verts_.push_back(v); + billboard_verts_.push_back(b.tint.x); billboard_verts_.push_back(b.tint.y); + billboard_verts_.push_back(b.tint.z); billboard_verts_.push_back(b.tint.w); }; // Bottom uses v1 and top uses v0 (row 0 = top of decoded TMAP image) emit(c0, rect.u0, rect.v1); emit(c1, rect.u1, rect.v1); emit(c2, rect.u1, rect.v0); emit(c0, rect.u0, rect.v1); emit(c2, rect.u1, rect.v0); emit(c3, rect.u0, rect.v0); + }; + for (size_t i = 0; i < billboards.size(); ++i) { + const auto& b = billboards[i]; + if (b.tint.w >= 0.99f) emit_bb(b); + else translucent_bb_idx_.push_back(i); } - if (!bverts.empty()) { - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDepthMask(GL_TRUE); - billboard_shader_.use(); - billboard_shader_.set_mat4("uViewProj", view_proj); - billboard_shader_.set_vec3("uCamPos", cam.eye); - billboard_shader_.set_vec3("uFogColor", fog_color_); - billboard_shader_.set_float("uDrawDist", draw_dist); - billboard_shader_.set_float("uModernLighting", modern ? 1.0f : 0.0f); - gl::ActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, tex_tmaps_atlas_); - billboard_shader_.set_int("uTex", 0); + opaque_bb_vert_count = billboard_verts_.size() / 9; + if (!translucent_bb_idx_.empty()) { + std::sort(translucent_bb_idx_.begin(), translucent_bb_idx_.end(), [&](size_t a, size_t b_idx) { + return (billboards[a].pos - cam.eye).len_sq() > (billboards[b_idx].pos - cam.eye).len_sq(); + }); + for (size_t idx : translucent_bb_idx_) emit_bb(billboards[idx]); + trans_bb_vert_count = (billboard_verts_.size() / 9) - opaque_bb_vert_count; + } + if (!billboard_verts_.empty()) { + const size_t bytes = billboard_verts_.size() * sizeof(float); gl::BindVertexArray(billboard_vao_); gl::BindBuffer(GL_ARRAY_BUFFER, billboard_vbo_); - gl::BufferData(GL_ARRAY_BUFFER, - static_cast(bverts.size() * sizeof(float)), - bverts.data(), GL_DYNAMIC_DRAW); - glDrawArrays(GL_TRIANGLES, 0, static_cast(bverts.size() / 9)); - glDisable(GL_BLEND); + if (bytes <= billboard_vbo_cap_) { + gl::BufferSubData(GL_ARRAY_BUFFER, 0, static_cast(bytes), billboard_verts_.data()); + } else { + gl::BufferData(GL_ARRAY_BUFFER, static_cast(bytes), + billboard_verts_.data(), GL_DYNAMIC_DRAW); + billboard_vbo_cap_ = bytes; + } } } + auto setup_billboard_pass = [&]() { + billboard_shader_.use(); + billboard_shader_.set_mat4("uViewProj", view_proj); + billboard_shader_.set_vec3("uCamPos", cam.eye); + billboard_shader_.set_vec3("uFogColor", fog_color_); + billboard_shader_.set_float("uDrawDist", draw_dist); + billboard_shader_.set_float("uModernLighting", modern ? 1.0f : 0.0f); + gl::ActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, tex_tmaps_atlas_); + billboard_shader_.set_int("uTex", 0); + gl::BindVertexArray(billboard_vao_); + }; + + if (opaque_bb_vert_count > 0) { + setup_billboard_pass(); + glDisable(GL_BLEND); + glDepthMask(GL_TRUE); + glDrawArrays(GL_TRIANGLES, 0, static_cast(opaque_bb_vert_count)); + } + + // 3. Cylindrical Skybox drawn AFTER opaque world for hardware Early-Z rejection (depth == 1.0) + if (tex_sky_ && sky_vao_) { + glDisable(GL_CULL_FACE); + glDisable(GL_BLEND); + glDepthFunc(GL_LEQUAL); + glDepthMask(GL_FALSE); + Mat4 view_no_trans = view; + view_no_trans.m[12] = view_no_trans.m[13] = view_no_trans.m[14] = 0.0f; + sky_shader_.use(); + sky_shader_.set_mat4("uViewProjNoTrans", proj * view_no_trans); + sky_shader_.set_vec3("uFogColor", fog_color_); + sky_shader_.set_vec3("uSunDir", theme.sun_dir); + sky_shader_.set_vec3("uSunColor", theme.sun_color); + sky_shader_.set_float("uModernLighting", modern ? 1.0f : 0.0f); + gl::ActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, tex_sky_); + sky_shader_.set_int("uSkyTex", 0); + gl::BindVertexArray(sky_vao_); + glDrawArrays(GL_TRIANGLES, 0, sky_vert_count_); + glDepthFunc(GL_LESS); + } + + // 4. Translucent Billboards & Models + Particles (depth write disabled, blended back-to-front) glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDepthMask(GL_FALSE); - for (const auto& inst : models) { - if (inst.tint.w < 0.99f) draw_model(inst); + + if (trans_bb_vert_count > 0) { + setup_billboard_pass(); + glDrawArrays(GL_TRIANGLES, static_cast(opaque_bb_vert_count), + static_cast(trans_bb_vert_count)); } - // 4. Particles: volumetric alpha-blended smoke/debris (back-to-front), then additive fireballs/glows + if (!translucent_models_.empty()) { + // Always re-bind model shader & textures because billboard/sky shaders changed bindings above + model_shader_.use(); + gl::ActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, tex_obj_atlas_); + model_shader_.set_int("uAtlas", 0); + model_shader_.set_int("uShadowMap", 1); + if (shadow_depth_tex_) { + gl::ActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, shadow_depth_tex_); + } + gl::ActiveTexture(GL_TEXTURE0); + for (const auto& draw : translucent_models_) { + model_shader_.set_mat4("uModel", draw.model); + model_shader_.set_vec4("uTint", draw.tint); + gl::BindVertexArray(draw.mesh->vao); + glDrawElements(GL_TRIANGLES, draw.mesh->index_count, GL_UNSIGNED_INT, nullptr); + } + } + + // 5. Particles: volumetric alpha-blended smoke/debris (back-to-front), then additive fireballs/glows if (!particles.empty() && part_vao_) { - // Extract camera right & up vectors from view matrix Vec3 cam_right(view.m[0], view.m[4], view.m[8]); Vec3 cam_up(view.m[1], view.m[5], view.m[9]); Vec3 cam_fwd(-view.m[2], -view.m[6], -view.m[10]); - std::vector alpha_idx; - std::vector add_idx; - alpha_idx.reserve(particles.size()); - add_idx.reserve(particles.size()); + part_alpha_idx_.clear(); + part_add_idx_.clear(); for (size_t i = 0; i < particles.size(); ++i) { Vec3 rel = particles[i].pos - cam.eye; if (rel.dot(cam_fwd) < 0.55f) continue; // avoid clipping particles right in front of cockpit lens - if (particles[i].additive) add_idx.push_back(i); - else alpha_idx.push_back(i); + if (particles[i].additive) part_add_idx_.push_back(i); + else part_alpha_idx_.push_back(i); } - std::sort(alpha_idx.begin(), alpha_idx.end(), [&](size_t ia, size_t ib) { + std::sort(part_alpha_idx_.begin(), part_alpha_idx_.end(), [&](size_t ia, size_t ib) { float da = (particles[ia].pos - cam.eye).len_sq(); float db = (particles[ib].pos - cam.eye).len_sq(); return da > db; }); - const size_t total_quads = alpha_idx.size() + add_idx.size(); - std::vector pverts; - pverts.reserve(total_quads * 6 * 11); + part_verts_.clear(); auto push_quad_idx = [&](size_t idx) { const auto& p = particles[idx]; Vec3 rx = cam_right * (p.size * 0.5f); @@ -1598,36 +1827,43 @@ void WorldRenderer::render_world_view(const RenderCamera& cam, const std::vector Vec3 c3 = p.pos - rx + ry; auto emit = [&](const Vec3& q, float u, float v) { - pverts.push_back(q.x); pverts.push_back(q.y); pverts.push_back(q.z); - pverts.push_back(u); pverts.push_back(v); - pverts.push_back(p.color.x); pverts.push_back(p.color.y); - pverts.push_back(p.color.z); pverts.push_back(p.color.w); - pverts.push_back(p.style); pverts.push_back(p.seed); + part_verts_.push_back(q.x); part_verts_.push_back(q.y); part_verts_.push_back(q.z); + part_verts_.push_back(u); part_verts_.push_back(v); + part_verts_.push_back(p.color.x); part_verts_.push_back(p.color.y); + part_verts_.push_back(p.color.z); part_verts_.push_back(p.color.w); + part_verts_.push_back(p.style); part_verts_.push_back(p.seed); }; emit(c0, 0.0f, 0.0f); emit(c1, 1.0f, 0.0f); emit(c2, 1.0f, 1.0f); emit(c0, 0.0f, 0.0f); emit(c2, 1.0f, 1.0f); emit(c3, 0.0f, 1.0f); }; - for (size_t idx : alpha_idx) push_quad_idx(idx); - for (size_t idx : add_idx) push_quad_idx(idx); + for (size_t idx : part_alpha_idx_) push_quad_idx(idx); + for (size_t idx : part_add_idx_) push_quad_idx(idx); - particle_shader_.use(); - particle_shader_.set_mat4("uViewProj", view_proj); - particle_shader_.set_vec3("uCamPos", cam.eye); - particle_shader_.set_vec3("uFogColor", fog_color_); - particle_shader_.set_float("uDrawDist", draw_dist); - gl::BindVertexArray(part_vao_); - gl::BindBuffer(GL_ARRAY_BUFFER, part_vbo_); - gl::BufferData(GL_ARRAY_BUFFER, - static_cast(pverts.size() * sizeof(float)), - pverts.data(), GL_DYNAMIC_DRAW); - if (!alpha_idx.empty()) { - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDrawArrays(GL_TRIANGLES, 0, static_cast(alpha_idx.size() * 6)); - } - if (!add_idx.empty()) { - glBlendFunc(GL_SRC_ALPHA, GL_ONE); - glDrawArrays(GL_TRIANGLES, static_cast(alpha_idx.size() * 6), - static_cast(add_idx.size() * 6)); + if (!part_verts_.empty()) { + particle_shader_.use(); + particle_shader_.set_mat4("uViewProj", view_proj); + particle_shader_.set_vec3("uCamPos", cam.eye); + particle_shader_.set_vec3("uFogColor", fog_color_); + particle_shader_.set_float("uDrawDist", draw_dist); + gl::BindVertexArray(part_vao_); + gl::BindBuffer(GL_ARRAY_BUFFER, part_vbo_); + const size_t bytes = part_verts_.size() * sizeof(float); + if (bytes <= part_vbo_cap_) { + gl::BufferSubData(GL_ARRAY_BUFFER, 0, static_cast(bytes), part_verts_.data()); + } else { + gl::BufferData(GL_ARRAY_BUFFER, static_cast(bytes), + part_verts_.data(), GL_DYNAMIC_DRAW); + part_vbo_cap_ = bytes; + } + if (!part_alpha_idx_.empty()) { + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDrawArrays(GL_TRIANGLES, 0, static_cast(part_alpha_idx_.size() * 6)); + } + if (!part_add_idx_.empty()) { + glBlendFunc(GL_SRC_ALPHA, GL_ONE); + glDrawArrays(GL_TRIANGLES, static_cast(part_alpha_idx_.size() * 6), + static_cast(part_add_idx_.size() * 6)); + } } } @@ -1668,6 +1904,10 @@ void WorldRenderer::end_classic_world_pass(int backbuffer_w, int backbuffer_h, c glBindTexture(GL_TEXTURE_2D, tex_palette_); classic_shader_.set_int("uPaletteTex", 1); + gl::ActiveTexture(GL_TEXTURE2); + glBindTexture(GL_TEXTURE_3D, tex_palette_lut_); + classic_shader_.set_int("uPaletteLut", 2); + classic_shader_.set_float("uScanlines", cfg.classic_scanlines ? 1.0f : 0.0f); classic_shader_.set_float("uHeightPx", static_cast(classic_h_)); diff --git a/src/render/world_renderer.hpp b/src/render/world_renderer.hpp index 09e967d..8a6d468 100644 --- a/src/render/world_renderer.hpp +++ b/src/render/world_renderer.hpp @@ -64,6 +64,7 @@ struct DynamicLight { struct CraftShadow { Vec3 pos; float radius = 0.95f; + float floor_y = 0.0f; }; class WorldRenderer { @@ -132,7 +133,7 @@ private: void destroy_mesh(GpuMesh& m); void upload_world_mesh(GpuMesh& m, const std::vector& verts, const std::vector& indices, bool dynamic); - void ensure_classic_fbo(int w, int h); + bool ensure_classic_fbo(int w, int h); bool init_shadow_map(); void apply_texture_filtering(TextureFilterMode mode); static WorldLightingTheme theme_for_world(int world_idx); @@ -159,6 +160,7 @@ private: GLuint tex_obj_atlas_ = 0; GLuint tex_tmaps_atlas_ = 0; GLuint tex_palette_ = 0; + GLuint tex_palette_lut_ = 0; TextureFilterMode active_filter_ = TextureFilterMode::Linear; std::vector tmap_rects_; @@ -176,6 +178,22 @@ private: // Dynamic particles & billboards GLuint part_vao_ = 0, part_vbo_ = 0; GLuint billboard_vao_ = 0, billboard_vbo_ = 0; + size_t column_vbo_cap_ = 0, column_ebo_cap_ = 0; + size_t part_vbo_cap_ = 0, billboard_vbo_cap_ = 0; + + // Reusable per-frame draw lists & scratch buffers (zero steady-state heap allocations) + struct ResolvedModelDraw { + const GpuMesh* mesh = nullptr; + Mat4 model; + Vec4 tint; + }; + std::vector opaque_models_; + std::vector translucent_models_; + std::vector translucent_bb_idx_; + std::vector billboard_verts_; + std::vector part_alpha_idx_; + std::vector part_add_idx_; + std::vector part_verts_; // Fullscreen quad & Classic Mode FBO GLuint quad_vao_ = 0, quad_vbo_ = 0; diff --git a/src/sim/ai_driver.cpp b/src/sim/ai_driver.cpp index d1c5a5c..468ad97 100644 --- a/src/sim/ai_driver.cpp +++ b/src/sim/ai_driver.cpp @@ -1,4 +1,5 @@ #include "sim/ai_driver.hpp" +#include "sim/combat.hpp" #include "sim/vehicle_defs.hpp" #include @@ -24,29 +25,32 @@ CraftInput compute_ai_input(CraftState& ai, const assets::LevelData& level, ai.ai_pit_cooldown = std::max(0.0f, ai.ai_pit_cooldown - dt); } - auto is_ai_blocked = [&](float wx, float wz, float ref_y) -> bool { + auto is_point_blocked = [&](float px, float pz, float ref_y, float* out_floor = nullptr) -> bool { + if (px < 1.5f || px > assets::kMapWidth - 2.5f || + pz < 1.5f || pz > assets::kMapHeight - 2.5f) { + return true; + } + float local_floor = 0.0f; + float local_ceil = 1e6f; + level.sample_surface_and_ceiling(px, pz, ref_y, local_floor, local_ceil); + if (out_floor) *out_floor = local_floor; + if (local_floor > ref_y + 0.72f) { + return true; + } + float probe_y = (local_floor > ref_y) + ? (local_floor + 0.28f) + : std::max(local_floor + 0.24f, std::min(ref_y, local_floor + 0.35f)); + int ix = static_cast(std::floor(px)); + int iz = static_cast(std::floor(pz)); + return level.is_cell_solid_at_point(ix, iz, px, pz, probe_y) || + level.is_cliff_blocking_at_y(ix, iz, probe_y); + }; + + auto is_ai_blocked = [&](float wx, float wz, float ref_y, int start_k = 0) -> bool { static constexpr float kOffX[5] = {0.0f, 1.0f, -1.0f, 0.0f, 0.0f}; static constexpr float kOffZ[5] = {0.0f, 0.0f, 0.0f, 1.0f, -1.0f}; - for (int k = 0; k < 5; ++k) { - float px = wx + kOffX[k] * probe_r; - float pz = wz + kOffZ[k] * probe_r; - if (px < 1.5f || px > assets::kMapWidth - 2.5f || - pz < 1.5f || pz > assets::kMapHeight - 2.5f) { - return true; - } - float local_floor = 0.0f; - float local_ceil = 1e6f; - level.sample_surface_and_ceiling(px, pz, ref_y, local_floor, local_ceil); - if (local_floor > ref_y + 0.72f) { - return true; - } - float probe_y = (local_floor > ref_y) - ? (local_floor + 0.28f) - : std::max(local_floor + 0.24f, std::min(ref_y, local_floor + 0.35f)); - int ix = static_cast(std::floor(px)); - int iz = static_cast(std::floor(pz)); - if (level.is_cell_solid_at_point(ix, iz, px, pz, probe_y) || - level.is_cliff_blocking_at_y(ix, iz, probe_y)) { + for (int k = start_k; k < 5; ++k) { + if (is_point_blocked(wx + kOffX[k] * probe_r, wz + kOffZ[k] * probe_r, ref_y)) { return true; } } @@ -65,12 +69,7 @@ CraftInput compute_ai_input(CraftState& ai, const assets::LevelData& level, float t = static_cast(s) / static_cast(steps); Vec2 p = a + d * t; float nf = 0.0f; - float nc = 1e6f; - level.sample_surface_and_ceiling(p.x, p.y, cur_y, nf, nc); - if (nf > cur_y + 0.72f) { - return false; - } - if (is_ai_blocked(p.x, p.y, cur_y)) { + if (is_point_blocked(p.x, p.y, cur_y, &nf) || is_ai_blocked(p.x, p.y, cur_y, 1)) { return false; } cur_y = nf + spec.hover_offset; @@ -101,9 +100,10 @@ CraftInput compute_ai_input(CraftState& ai, const assets::LevelData& level, return best; }; - const bool need_fuel = (ai.fuel < ai.max_fuel * 0.25f); - const bool need_shield = (ai.shield < ai.max_shield * 0.28f); - const bool need_ammo = (ai.ammo < ai.max_ammo * 0.15f); + const bool was_charging_pit = (ai.ai_pit_stay_timer > 0.0f); + const bool need_fuel = (ai.fuel < ai.max_fuel * (was_charging_pit ? 0.85f : 0.25f)); + const bool need_shield = (ai.shield < ai.max_shield * (was_charging_pit ? 0.85f : 0.28f)); + const bool need_ammo = (ai.ammo < ai.max_ammo * (was_charging_pit ? 0.85f : 0.15f)); const bool on_needed_pad = (ai.active_recharge_mask != 0) && ((need_fuel && (ai.active_recharge_mask & 2u)) || (need_shield && (ai.active_recharge_mask & 1u)) || @@ -118,6 +118,10 @@ CraftInput compute_ai_input(CraftState& ai, const assets::LevelData& level, } float spd = ai.speed_horizontal(); + Vec2 cur_pos(ai.curr_pose.pos.x, ai.curr_pose.pos.z); + const auto& cur_wp = level.main_waypoints[wp_idx]; + Vec2 cur_wp_pos(cur_wp.x, cur_wp.z); + float dist_to_wp = (cur_wp_pos - cur_pos).len(); if (!ai.ai_anchor_init) { ai.ai_progress_anchor = ai.curr_pose.pos; ai.ai_anchor_init = true; @@ -137,38 +141,23 @@ CraftInput compute_ai_input(CraftState& ai, const assets::LevelData& level, ai.ai_stuck_timer = std::max(0.0f, ai.ai_stuck_timer - dt * 1.5f); } } + if (charging_pit) { + ai.ai_wp_stall_timer = 0.0f; + ai.ai_wp_best_dist = std::min(ai.ai_wp_best_dist, dist_to_wp); + } else if (dist_to_wp < ai.ai_wp_best_dist - 1.5f) { + ai.ai_wp_best_dist = dist_to_wp; + ai.ai_wp_stall_timer = 0.0f; + } else { + ai.ai_wp_stall_timer += dt; + } } - // Stage 2 Failsafe Track Recovery if trapped for >= 6.0s without progress - if (!charging_pit && ai.ai_progress_timer >= 6.0f && (!ai.is_human || ai.autopilot)) { - int rec_wp = find_clear_wp_in_range(-1, 2, false); - const auto& rw = level.main_waypoints[rec_wp]; - if (Vec2(rw.x - ai.curr_pose.pos.x, rw.z - ai.curr_pose.pos.z).len() > 28.0f) { - rec_wp = find_clear_wp_in_range(0, n_wp - 1, false); - } - const auto& wp = level.main_waypoints[rec_wp]; - const auto& wpn = level.main_waypoints[(rec_wp + 1) % n_wp]; - float fy = 0.0f, cy = 1e6f; - level.sample_surface_and_ceiling(wp.x, wp.z, ai.curr_pose.pos.y, fy, cy); - ai.curr_pose.pos = Vec3(wp.x, fy + spec.hover_offset, wp.z); - ai.curr_pose.yaw = std::atan2(wpn.x - wp.x, wpn.z - wp.z); - ai.curr_pose.pitch = 0.0f; - ai.curr_pose.roll = 0.0f; - ai.vel = Vec3(0.0f, 0.0f, 0.0f); - float imp = 0.0f; - bool scr = false; - resolve_world_collisions(ai, level, imp, scr); - ai.prev_pose = ai.curr_pose; - ai.current_wp = rec_wp; - ai.ai_target_wp = (rec_wp + 1) % n_wp; - ai.ai_stuck_timer = 0.0f; - ai.ai_unstuck_timer = 0.0f; - ai.ai_progress_timer = 0.0f; - ai.ai_pit_stay_timer = 0.0f; + // Stage 2 Failsafe Track Recovery if trapped for >= 6.0s or circling off-track without waypoint progress + if (!charging_pit && + (ai.ai_progress_timer >= 6.0f || ai.ai_wp_stall_timer >= 7.5f) && + (!ai.is_human || ai.autopilot)) { + place_craft_on_track(ai, level, all_crafts, true); ai.ai_pit_cooldown = 8.0f; - ai.ai_seeking_pit = false; - ai.ai_progress_anchor = ai.curr_pose.pos; - ai.ai_anchor_init = true; return out; } @@ -199,6 +188,8 @@ CraftInput compute_ai_input(CraftState& ai, const assets::LevelData& level, if ((fwd_pos - cur_p).len() < cur_wp_dist && has_clear_corridor(cur_p, fwd_pos, ai.curr_pose.pos.y)) { ai.ai_target_wp = fwd_wp; + ai.ai_wp_best_dist = 1e9f; + ai.ai_wp_stall_timer = 0.0f; } } } @@ -211,25 +202,23 @@ CraftInput compute_ai_input(CraftState& ai, const assets::LevelData& level, } // Portal-safe forward waypoint advance - Vec2 cur_pos(ai.curr_pose.pos.x, ai.curr_pose.pos.z); - const auto& cur_wp = level.main_waypoints[wp_idx]; - Vec2 cur_wp_pos(cur_wp.x, cur_wp.z); - float dist_to_wp = (cur_wp_pos - cur_pos).len(); int next_wp_idx = (wp_idx + 1) % n_wp; Vec2 next_wp_pos(level.main_waypoints[next_wp_idx].x, level.main_waypoints[next_wp_idx].z); Vec2 seg_to_next = next_wp_pos - cur_wp_pos; float dist_to_next = (next_wp_pos - cur_pos).len(); - bool passed_wp = ((cur_pos - cur_wp_pos).dot(seg_to_next) > 0.0f) && - (dist_to_next < dist_to_wp) && - has_clear_corridor(cur_pos, next_wp_pos, ai.curr_pose.pos.y); + bool passed_geom = ((cur_pos - cur_wp_pos).dot(seg_to_next) > 0.0f) && (dist_to_next < dist_to_wp); + bool advance_wp = (dist_to_wp < 3.4f); + if (!advance_wp && (dist_to_wp < 5.2f || passed_geom)) { + advance_wp = has_clear_corridor(cur_pos, next_wp_pos, ai.curr_pose.pos.y); + } - if (dist_to_wp < 3.4f || - (dist_to_wp < 5.2f && has_clear_corridor(cur_pos, next_wp_pos, ai.curr_pose.pos.y)) || - passed_wp) { + if (advance_wp) { wp_idx = next_wp_idx; ai.ai_target_wp = wp_idx; cur_wp_pos = next_wp_pos; dist_to_wp = dist_to_next; + ai.ai_wp_best_dist = dist_to_wp; + ai.ai_wp_stall_timer = 0.0f; } // Line-of-sight-validated pitstop detour @@ -250,7 +239,7 @@ CraftInput compute_ai_input(CraftState& ai, const assets::LevelData& level, if (d2 >= best_d2 || d2 < 0.04f) continue; if (to_pad.normalized().dot(wp_dir) <= 0.20f) continue; if (!has_clear_corridor(cur_pos, p, ai.curr_pose.pos.y)) continue; - float pad_floor_y = level.sample_height_world(p.x, p.y) + spec.hover_offset; + float pad_floor_y = level.sample_entity_surface_y(p.x, p.y) + spec.hover_offset; if (!has_clear_corridor(p, cur_wp_pos, pad_floor_y)) continue; best_d2 = d2; tgt_pos = p; @@ -287,6 +276,7 @@ CraftInput compute_ai_input(CraftState& ai, const assets::LevelData& level, float hit_dist = -1.0f; float max_probe = std::min(tgt_dist, 7.5f); float probe_y = ai.curr_pose.pos.y; + float gap_air_dist = 0.0f; for (float d = 0.85f; d <= max_probe; d += 0.70f) { Vec2 p = cur_pos + base_dir * d; float nf = 0.0f, nc = 1e6f; @@ -295,7 +285,13 @@ CraftInput compute_ai_input(CraftState& ai, const assets::LevelData& level, hit_dist = d; break; } - probe_y = nf + spec.hover_offset; + if (spd > 6.5f && nf < probe_y - 0.55f && gap_air_dist < 3.5f) { + // Preserve airborne launch height across short jump gaps before landing decks + gap_air_dist += 0.70f; + } else { + probe_y = nf + spec.hover_offset; + gap_air_dist = 0.0f; + } } if (hit_dist > 0.0f) { static constexpr std::array kFanAngles = { @@ -316,10 +312,11 @@ CraftInput compute_ai_input(CraftState& ai, const assets::LevelData& level, } } - // Craft avoidance repulsion + // Craft avoidance repulsion (same elevation layer only) Vec2 avoid(0.0f, 0.0f); for (const auto& other : all_crafts) { if (other.id == ai.id || other.recovery_state != RecoveryState::Active) continue; + if (std::abs(other.curr_pose.pos.y - ai.curr_pose.pos.y) > 1.2f) continue; Vec2 d(ai.curr_pose.pos.x - other.curr_pose.pos.x, ai.curr_pose.pos.z - other.curr_pose.pos.z); float dist_sq = d.len_sq(); if (dist_sq > 0.01f && dist_sq < 2.25f) { @@ -358,6 +355,7 @@ CraftInput compute_ai_input(CraftState& ai, const assets::LevelData& level, // Combat AI: shoot visible opponents in sights! if (ai.ammo > 5.0f) { Vec3 fwd = ai.forward_dir(); + const Vec3 eye_a = ai.curr_pose.pos + Vec3(0.0f, 0.25f, 0.0f); for (const auto& other : all_crafts) { if (other.id == ai.id || other.recovery_state != RecoveryState::Active || other.invisible_timer > 0.0f) { @@ -367,8 +365,10 @@ CraftInput compute_ai_input(CraftState& ai, const assets::LevelData& level, float dist = to_e.len(); if (dist < 1.2f || dist > 22.0f) continue; float cos_ang = (to_e / dist).dot(fwd); - if (cos_ang > 0.93f && difficulty >= 0) { + if (cos_ang > 0.93f && difficulty >= 0 && + has_line_of_sight(level, eye_a, other.curr_pose.pos + Vec3(0.0f, 0.25f, 0.0f))) { out.fire_minigun = (difficulty == 2 || (static_cast(ai.race_time * 10.0f) % 2 == 0)); + if (out.fire_minigun) break; } } if (ai.lock_progress >= 1.0f && difficulty >= 1 && ai.ammo >= 20.0f) { diff --git a/src/sim/combat.cpp b/src/sim/combat.cpp index bee1334..26450df 100644 --- a/src/sim/combat.cpp +++ b/src/sim/combat.cpp @@ -25,6 +25,14 @@ float fx_hash(uint32_t x) { return static_cast(x & 0x00FFFFFFu) / 16777216.0f; } +float closest_segment_t(const Vec3& a, const Vec3& b, const Vec3& p, Vec3& out_pt) { + Vec3 ab = b - a; + float len_sq = ab.len_sq(); + float t = (len_sq > 1e-8f) ? std::clamp((p - a).dot(ab) / len_sq, 0.0f, 1.0f) : 1.0f; + out_pt = a + ab * t; + return t; +} + void apply_damage(CraftState& victim, int attacker_id, const std::vector& crafts, const RaceSetup& setup, std::vector& particles, std::vector& events, bool& out_race_over, int& out_winner_id) { @@ -39,8 +47,12 @@ void apply_damage(CraftState& victim, int attacker_id, const std::vector= 0 && attacker_id < static_cast(crafts.size())) { @@ -142,6 +154,27 @@ void apply_pickup(CraftState& c, uint8_t subtype, std::vector& events) } // namespace +bool has_line_of_sight(const assets::LevelData& level, const Vec3& a, const Vec3& b) { + Vec3 d = b - a; + float len = d.len(); + if (len < 0.5f) return true; + int steps = std::max(1, static_cast(std::ceil(len / 0.70f))); + for (int s = 1; s < steps; ++s) { + float t = static_cast(s) / static_cast(steps); + Vec3 p = a + d * t; + float gy = level.sample_height_world(p.x, p.z); + if (p.y <= gy - 0.10f) { + return false; + } + int ix = static_cast(std::floor(p.x)); + int iz = static_cast(std::floor(p.z)); + if (level.is_cell_solid_at_point(ix, iz, p.x, p.z, p.y, 0.10f)) { + return false; + } + } + return true; +} + void spawn_smoke_puff(std::vector& particles, const Vec3& pos, const Vec3& vel, float start_size, float end_size, const Vec4& color, float life, float drag, float gravity, float seed) { @@ -273,7 +306,10 @@ void step_combat_and_world( bool& out_race_over, int& out_winner_id, float dt, - std::vector* out_projectile_traces) { + std::vector* out_projectile_traces, + uint32_t* io_next_projectile_uid) { + uint32_t fallback_uid = 1; + uint32_t& uid_counter = io_next_projectile_uid ? *io_next_projectile_uid : fallback_uid; // 1. Recovery craft state machine & weapon firing per craft for (size_t i = 0; i < crafts.size(); ++i) { @@ -281,60 +317,36 @@ void step_combat_and_world( if (c.recovery_state != RecoveryState::Active) { c.recovery_timer -= dt; - if (c.recovery_state == RecoveryState::CallingRepair && c.recovery_timer < 2.2f) { + float rec_dur = std::max(c.recovery_duration, 0.1f); + float u = c.recovery_timer / rec_dur; + if (c.recovery_state == RecoveryState::CallingRepair && u < 0.68f) { c.recovery_state = RecoveryState::AwaitingRepair; if (c.is_human) { - events.push_back({SimSoundCue::None, c.curr_pose.pos, c.player_index, "AWAITING REPAIR", 0.0f}); + events.push_back({SimSoundCue::None, c.curr_pose.pos, c.player_index, + c.recovery_refill ? "AWAITING REPAIR" : "AWAITING RECOVERY", 0.0f}); } - } else if (c.recovery_state == RecoveryState::AwaitingRepair && c.recovery_timer < 1.1f) { + } else if (c.recovery_state == RecoveryState::AwaitingRepair && u < 0.34f) { c.recovery_state = RecoveryState::Repairing; if (c.is_human) { - events.push_back({SimSoundCue::Refuel, c.curr_pose.pos, c.player_index, "REPAIRING", 0.0f}); + events.push_back({c.recovery_refill ? SimSoundCue::Refuel : SimSoundCue::SwitchTrigger, + c.curr_pose.pos, c.player_index, + c.recovery_refill ? "REPAIRING" : "RECOVERING TO TRACK", 0.0f}); } } else if (c.recovery_timer <= 0.0f) { c.recovery_state = RecoveryState::Active; - c.shield = c.max_shield; - c.fuel = c.max_fuel; - c.ammo = std::max(c.ammo, c.max_ammo * 0.5f); - // Place cleanly at nearest clear main waypoint and resolve against morphed walls - if (!level.main_waypoints.empty()) { - size_t best_wp = 0; - float best_d2 = 1e18f; - for (size_t wi = 0; wi < level.main_waypoints.size(); ++wi) { - const auto& w = level.main_waypoints[wi]; - float dx = w.x - c.curr_pose.pos.x; - float dz = w.z - c.curr_pose.pos.z; - float d2 = dx * dx + dz * dz; - if (d2 < best_d2) { - best_d2 = d2; - best_wp = wi; - } - } - const auto& wp = level.main_waypoints[best_wp]; - const auto& wpn = level.main_waypoints[(best_wp + 1) % level.main_waypoints.size()]; - const VehicleSpec& sp_rec = kVehicleSpecs[std::clamp(c.vehicle_idx, 0, 5)]; - float fy = 0.0f, cy = 1e6f; - level.sample_surface_and_ceiling(wp.x, wp.z, c.curr_pose.pos.y, fy, cy); - c.curr_pose.pos = Vec3(wp.x, fy + sp_rec.hover_offset, wp.z); - c.curr_pose.yaw = std::atan2(wpn.x - wp.x, wpn.z - wp.z); - c.curr_pose.pitch = 0.0f; - c.curr_pose.roll = 0.0f; - c.vel = Vec3(0, 0, 0); - float dummy_imp = 0.0f; - bool dummy_scr = false; - resolve_world_collisions(c, level, dummy_imp, dummy_scr); - c.prev_pose = c.curr_pose; - c.current_wp = static_cast(best_wp); - c.ai_target_wp = static_cast((best_wp + 1) % level.main_waypoints.size()); + if (c.recovery_refill) { + c.shield = c.max_shield; + c.fuel = c.max_fuel; + c.ammo = std::max(c.ammo, c.max_ammo * 0.5f); + c.invincible_timer = std::max(c.invincible_timer, 2.0f); + } else if (setup.fuel_enabled && c.fuel < 5.0f) { + c.fuel = 8.0f; } - c.ai_stuck_timer = 0.0f; - c.ai_unstuck_timer = 0.0f; - c.ai_progress_timer = 0.0f; - c.ai_pit_stay_timer = 0.0f; + place_craft_on_track(c, level, crafts, setup.mode != GameMode::DeathMatch); c.ai_pit_cooldown = 0.0f; - c.ai_seeking_pit = false; - c.ai_progress_anchor = c.curr_pose.pos; - c.ai_anchor_init = true; + c.recovery_cooldown = 1.5f; + c.recovery_refill = true; + c.recovery_duration = 3.2f; } else if (c.shield <= 0.1f) { int rec_ticks = static_cast(std::lround(c.recovery_timer * 60.0f)); if (rec_ticks % 4 == 0) { @@ -359,7 +371,12 @@ void step_combat_and_world( // Trigger repair if fuel completely depleted and stopped if (setup.fuel_enabled && c.fuel <= 0.05f && c.speed_horizontal() < 0.8f) { c.recovery_state = RecoveryState::CallingRepair; + c.recovery_refill = true; + c.recovery_duration = 3.0f; c.recovery_timer = 3.0f; + c.recovery_pos = c.curr_pose.pos; + c.pit_stuck_timer = 0.0f; + c.stuck_in_pit_hint = false; if (c.is_human) { events.push_back({SimSoundCue::Warning, c.curr_pose.pos, c.player_index, "CALLING REPAIR", 0.2f}); } @@ -372,8 +389,9 @@ void step_combat_and_world( continue; } - // Update missile lock-on cone + // Update missile lock-on cone (requires line-of-sight) Vec3 fwd = c.forward_dir(); + const Vec3 eye_a = c.curr_pose.pos + Vec3(0.0f, 0.25f, 0.0f); int best_tgt = -1; float best_score = 0.72f; // ~44 deg half-cone for (size_t j = 0; j < crafts.size(); ++j) { @@ -385,7 +403,8 @@ void step_combat_and_world( float dist = to_tgt.len(); if (dist < 1.0f || dist > 38.0f) continue; float align = (to_tgt / dist).dot(fwd); - if (align > best_score) { + if (align > best_score && + has_line_of_sight(level, eye_a, crafts[j].curr_pose.pos + Vec3(0.0f, 0.25f, 0.0f))) { best_score = align; best_tgt = static_cast(j); } @@ -417,6 +436,7 @@ void step_combat_and_world( float dmg = sp.minigun_damage * (1.0f + 0.25f * static_cast(c.minigun_level - 1)); Projectile p; + p.uid = uid_counter++; p.active = true; p.is_missile = false; p.owner_id = c.id; @@ -438,6 +458,7 @@ void step_combat_and_world( float dmg = sp.missile_damage * (1.0f + 0.22f * static_cast(c.missile_level - 1)); Projectile p; + p.uid = uid_counter++; p.active = true; p.is_missile = true; p.owner_id = c.id; @@ -491,22 +512,132 @@ void step_combat_and_world( Vec3 prev_pos = pr.pos; pr.pos += pr.vel * dt; + + // Swept segment intersection against world, crafts, and destructible props + bool hit_world = false; + float world_t = 2.0f; + Vec3 world_pos = pr.pos; + { + float seg_len = (pr.pos - prev_pos).len(); + int sub = std::clamp(static_cast(std::ceil(seg_len / 0.35f)), 1, 4); + for (int s = 1; s <= sub; ++s) { + float t = static_cast(s) / static_cast(sub); + Vec3 sp = lerp(prev_pos, pr.pos, t); + float gy = level.sample_height_world(sp.x, sp.z); + int ix = static_cast(std::floor(sp.x)); + int iz = static_cast(std::floor(sp.z)); + if (sp.y <= gy || + level.is_cell_solid_at_point(ix, iz, sp.x, sp.z, sp.y, 0.10f)) { + hit_world = true; + world_t = t; + world_pos = sp; + break; + } + } + } + + int hit_craft_idx = -1; + float craft_t = 2.0f; + Vec3 craft_hit_pos = pr.pos; + for (size_t j = 0; j < crafts.size(); ++j) { + const CraftState& victim = crafts[j]; + if (victim.id == pr.owner_id || victim.recovery_state != RecoveryState::Active) continue; + const VehicleSpec& vspec = kVehicleSpecs[std::clamp(victim.vehicle_idx, 0, 5)]; + float hit_r = vspec.collision_radius + 0.12f; + Vec3 cpt; + float t = closest_segment_t(prev_pos, pr.pos, victim.curr_pose.pos, cpt); + if ((victim.curr_pose.pos - cpt).len_sq() < hit_r * hit_r && t < craft_t) { + craft_t = t; + hit_craft_idx = static_cast(j); + craft_hit_pos = cpt; + } + } + + int hit_prop_idx = -1; + float prop_t = 2.0f; + Vec3 prop_hit_pos = pr.pos; + for (size_t pi = 0; pi < props.size(); ++pi) { + const auto& prop = props[pi]; + if (!prop.alive) continue; + Vec3 center = prop.pos + Vec3(0.0f, 0.25f, 0.0f); + Vec3 cpt; + float t = closest_segment_t(prev_pos, pr.pos, center, cpt); + if ((center - cpt).len_sq() < 0.60f * 0.60f && t < prop_t) { + prop_t = t; + hit_prop_idx = static_cast(pi); + prop_hit_pos = cpt; + } + } + if (out_projectile_traces != nullptr) { int owner_player = -1; if (pr.owner_id >= 0 && pr.owner_id < static_cast(crafts.size()) && crafts[pr.owner_id].is_human) { owner_player = crafts[pr.owner_id].player_index; } - out_projectile_traces->push_back({prev_pos, pr.pos, owner_player, pr.is_missile}); + Vec3 trace_end = pr.pos; + if (hit_craft_idx >= 0 && craft_t <= prop_t && (!hit_world || craft_t <= world_t)) { + trace_end = craft_hit_pos; + } else if (hit_prop_idx >= 0 && (!hit_world || prop_t <= world_t)) { + trace_end = prop_hit_pos; + } + out_projectile_traces->push_back({prev_pos, trace_end, owner_player, pr.is_missile, pr.uid}); } - // World/Column/Ground impact - float gy = level.sample_height_world(pr.pos.x, pr.pos.z); - int ix = static_cast(std::floor(pr.pos.x)); - int iz = static_cast(std::floor(pr.pos.z)); - if (pr.pos.y <= gy || - level.is_cell_solid_at_point(ix, iz, pr.pos.x, pr.pos.z, pr.pos.y, 0.10f)) { + if (hit_craft_idx >= 0 && craft_t <= prop_t && (!hit_world || craft_t <= world_t)) { + CraftState& victim = crafts[static_cast(hit_craft_idx)]; pr.active = false; + pr.pos = craft_hit_pos; + if (pr.owner_id >= 0 && pr.owner_id < static_cast(crafts.size())) { + crafts[pr.owner_id].shots_hit += 1; + } + if (pr.is_missile) { + spawn_explosion_fx(particles, pr.pos, 1.15f); + events.push_back({SimSoundCue::Explosion, pr.pos, + victim.is_human ? victim.player_index : -1, "", 0.65f}); + } else { + spawn_impact_fx(particles, pr.pos, true); + events.push_back({SimSoundCue::Impact, pr.pos, + victim.is_human ? victim.player_index : -1, "", 0.20f}); + } + + if (setup.damage_enabled && victim.invincible_timer <= 0.0f) { + victim.shield -= pr.damage; + victim.armour_used += pr.damage; + victim.damage_flash = 0.22f; + if (victim.shield <= 0.0f) { + if (pr.owner_id >= 0 && pr.owner_id < static_cast(crafts.size())) { + crafts[pr.owner_id].kills += 1; + if (setup.mode == GameMode::DeathMatch && + crafts[pr.owner_id].kills >= setup.deathmatch_kill_limit) { + out_race_over = true; + out_winner_id = crafts[pr.owner_id].id; + } + } + apply_damage(victim, pr.owner_id, crafts, setup, particles, events, + out_race_over, out_winner_id); + } + } + continue; + } + + if (hit_prop_idx >= 0 && (!hit_world || prop_t <= world_t)) { + PropObject& prop = props[static_cast(hit_prop_idx)]; + pr.active = false; + pr.pos = prop_hit_pos; + prop.hp -= pr.damage; + if (prop.hp <= 0.0f) { + prop.alive = false; + prop.respawn_timer = 25.0f; + spawn_explosion_fx(particles, prop.pos, 0.95f); + events.push_back({SimSoundCue::Explosion, prop.pos, -1, "", 0.25f}); + } + continue; + } + + if (hit_world) { + pr.active = false; + pr.pos = world_pos; if (pr.is_missile) { spawn_explosion_fx(particles, pr.pos, 0.95f); events.push_back({SimSoundCue::Explosion, pr.pos, -1, "", 0.0f}); @@ -515,65 +646,6 @@ void step_combat_and_world( } continue; } - - // Hit Crafts - for (size_t j = 0; j < crafts.size(); ++j) { - CraftState& victim = crafts[j]; - if (victim.id == pr.owner_id || victim.recovery_state != RecoveryState::Active) continue; - const VehicleSpec& vspec = kVehicleSpecs[std::clamp(victim.vehicle_idx, 0, 5)]; - float hit_r = vspec.collision_radius + 0.12f; - Vec3 d = victim.curr_pose.pos - pr.pos; - if (d.len_sq() < hit_r * hit_r) { - pr.active = false; - if (pr.owner_id >= 0 && pr.owner_id < static_cast(crafts.size())) { - crafts[pr.owner_id].shots_hit += 1; - } - if (pr.is_missile) { - spawn_explosion_fx(particles, pr.pos, 1.15f); - events.push_back({SimSoundCue::Explosion, pr.pos, - victim.is_human ? victim.player_index : -1, "", 0.65f}); - } else { - spawn_impact_fx(particles, pr.pos, true); - events.push_back({SimSoundCue::Impact, pr.pos, - victim.is_human ? victim.player_index : -1, "", 0.20f}); - } - - if (setup.damage_enabled && victim.invincible_timer <= 0.0f) { - victim.shield -= pr.damage; - victim.armour_used += pr.damage; - if (victim.shield <= 0.0f) { - if (pr.owner_id >= 0 && pr.owner_id < static_cast(crafts.size())) { - crafts[pr.owner_id].kills += 1; - if (setup.mode == GameMode::DeathMatch && - crafts[pr.owner_id].kills >= setup.deathmatch_kill_limit) { - out_race_over = true; - out_winner_id = crafts[pr.owner_id].id; - } - } - apply_damage(victim, pr.owner_id, crafts, setup, particles, events, - out_race_over, out_winner_id); - } - } - break; - } - } - if (!pr.active) continue; - - // Hit Destructible Props - for (auto& prop : props) { - if (!prop.alive) continue; - if ((prop.pos - pr.pos).len_sq() < 0.60f * 0.60f) { - pr.active = false; - prop.hp -= pr.damage; - if (prop.hp <= 0.0f) { - prop.alive = false; - prop.respawn_timer = 25.0f; - spawn_explosion_fx(particles, prop.pos, 0.95f); - events.push_back({SimSoundCue::Explosion, prop.pos, -1, "", 0.25f}); - } - break; - } - } } projectiles.erase( std::remove_if(projectiles.begin(), projectiles.end(), @@ -623,8 +695,13 @@ void step_combat_and_world( prop.alive = false; prop.respawn_timer = 25.0f; if (prop.model_key.rfind("BAREL", 0) == 0) { - if (setup.damage_enabled) { - c.shield = std::max(5.0f, c.shield - 12.0f); + if (setup.damage_enabled && c.invincible_timer <= 0.0f) { + float dmg = std::min(12.0f, std::max(0.0f, c.shield - 5.0f)); + if (dmg > 0.0f) { + c.shield -= dmg; + c.armour_used += dmg; + } + c.damage_flash = 0.22f; } spawn_explosion_fx(particles, prop.pos, 1.0f); events.push_back({SimSoundCue::Explosion, prop.pos, @@ -647,12 +724,14 @@ std::vector get_recovery_visuals(const std::vector& c.recovery_state == RecoveryState::Repairing) { RecoveryVisual rv; rv.active = true; + float rec_dur = std::max(c.recovery_duration, 0.1f); + float u = std::clamp(c.recovery_timer / rec_dur, 0.0f, 1.0f); float hover_y = 0.0f; if (c.recovery_state == RecoveryState::CallingRepair) { - float t = std::clamp((c.recovery_timer - 2.2f) / 1.0f, 0.0f, 1.0f); + float t = std::clamp((u - 0.68f) / 0.32f, 0.0f, 1.0f); hover_y = 1.6f + t * 8.0f; } else if (c.recovery_state == RecoveryState::AwaitingRepair) { - float t = std::clamp((c.recovery_timer - 1.1f) / 1.1f, 0.0f, 1.0f); + float t = std::clamp((u - 0.34f) / 0.34f, 0.0f, 1.0f); hover_y = 1.05f + t * 0.55f; } else { hover_y = 1.05f; @@ -665,4 +744,24 @@ std::vector get_recovery_visuals(const std::vector& return out; } +bool trigger_track_recovery(CraftState& craft, std::vector& events) { + if (craft.recovery_state != RecoveryState::Active || craft.finished || + craft.recovery_cooldown > 0.0f) { + return false; + } + craft.vel = Vec3(0.0f, 0.0f, 0.0f); + craft.recovery_state = RecoveryState::CallingRepair; + craft.recovery_refill = false; + craft.recovery_duration = 1.6f; + craft.recovery_timer = 1.6f; + craft.recovery_pos = craft.curr_pose.pos; + craft.pit_stuck_timer = 0.0f; + craft.stuck_in_pit_hint = false; + if (craft.is_human) { + events.push_back({SimSoundCue::Warning, craft.curr_pose.pos, craft.player_index, + "CALLING RECOVERY", 0.18f}); + } + return true; +} + } // namespace top_octane::sim diff --git a/src/sim/combat.hpp b/src/sim/combat.hpp index 5d53b0c..a1dfcbf 100644 --- a/src/sim/combat.hpp +++ b/src/sim/combat.hpp @@ -19,6 +19,9 @@ void spawn_smoke_puff(std::vector& particles, const Vec3& pos, co float drag = 2.0f, float gravity = 1.2f, float seed = 0.25f); void spawn_impact_fx(std::vector& particles, const Vec3& pos, bool hit_craft); +// Checks line-of-sight between two world points against terrain height and solid columns +bool has_line_of_sight(const assets::LevelData& level, const Vec3& a, const Vec3& b); + // Updates forward-cone missile lock, weapon firing, projectile movement, collisions, pickups, props & recovery void step_combat_and_world( RaceSetup& setup, @@ -33,9 +36,13 @@ void step_combat_and_world( bool& out_race_over, int& out_winner_id, float dt, - std::vector* out_projectile_traces = nullptr); + std::vector* out_projectile_traces = nullptr, + uint32_t* io_next_projectile_uid = nullptr); // Computes visual Recovery Helicopter (RECOV0-0) positions for any craft under repair std::vector get_recovery_visuals(const std::vector& crafts); +// Triggers manual track recovery for an active craft without refilling resources +bool trigger_track_recovery(CraftState& craft, std::vector& events); + } // namespace top_octane::sim diff --git a/src/sim/physics.cpp b/src/sim/physics.cpp index 12cb896..161655e 100644 --- a/src/sim/physics.cpp +++ b/src/sim/physics.cpp @@ -90,6 +90,47 @@ bool resolve_world_collisions(CraftState& craft, const assets::LevelData& level, level.is_cliff_blocking_at_y(nx, nz, y); }; + auto try_mountable_deck_top = [&](int nx, int nz, float qx, float qz, float y, + float& out_top) -> bool { + if (nx < 0 || nx >= assets::kMapWidth || nz < 0 || nz >= assets::kMapHeight) { + return false; + } + const assets::MapEntry& m = level.cell(nx, nz); + if (m.tex_or_col >= 0) return false; + int col_idx = -m.tex_or_col; + if (col_idx <= 0 || col_idx >= assets::kMaxColumns) return false; + const assets::ColumnDefinition& col = level.columns[col_idx]; + if (col.shape_mask == 0) return false; + + float cx_p = std::clamp(qx, static_cast(nx), static_cast(nx + 1)); + float cz_p = std::clamp(qz, static_cast(nz), static_cast(nz + 1)); + float ground_y = level.sample_height_world(cx_p, cz_p); + float min_y = y - 0.05f; + float max_y = y + 0.42f; + bool found = false; + float best_top = -1e6f; + for (int s = 0; s < 8; ++s) { + if ((col.shape_mask & (1u << s)) == 0) continue; + float slot_bot = ground_y + static_cast(s); + float slot_top = slot_bot + 1.0f; + if (slot_top > min_y && slot_bot < max_y) { + if ((slot_top - y) <= 0.35f && + (s == 7 || (col.shape_mask & (1u << (s + 1))) == 0)) { + best_top = std::max(best_top, slot_top); + found = true; + } else { + return false; + } + } + } + if (!found) return false; + if (level.is_cell_solid_at_point(nx, nz, cx_p, cz_p, best_top + spec.hover_offset)) { + return false; + } + out_top = best_top; + return true; + }; + // 3-pass seam-free 3D Column + Cliff AABB vs Craft Circle pushout for (int pass = 0; pass < 3; ++pass) { int cx = static_cast(std::floor(craft.curr_pose.pos.x)); @@ -113,6 +154,16 @@ bool resolve_world_collisions(CraftState& craft, const assets::LevelData& level, continue; } + float deck_top = 0.0f; + if (!level.is_cliff_blocking_at_y(nx, nz, craft.curr_pose.pos.y) && + try_mountable_deck_top(nx, nz, closest_x, closest_z, + craft.curr_pose.pos.y, deck_top)) { + craft.curr_pose.pos.y = std::max(craft.curr_pose.pos.y, + deck_top + spec.hover_offset); + craft.vel.y = std::max(0.0f, craft.vel.y); + continue; + } + Vec2 norm; float pen = 0.0f; bool inside_box = (dist_sq <= 1e-8f); @@ -311,11 +362,13 @@ bool resolve_world_collisions(CraftState& craft, const assets::LevelData& level, } } - // Gentle steep slope deflection for intermediate slopes (ny < 0.49) + // Gentle steep slope deflection for intermediate slopes (ny < 0.49) — skip when riding an elevated bridge deck float post_floor_y = 0.0f, post_ceil_y = 1e6f; level.sample_surface_and_ceiling(craft.curr_pose.pos.x, craft.curr_pose.pos.z, craft.curr_pose.pos.y, post_floor_y, post_ceil_y); - if (!craft.airborne || craft.curr_pose.pos.y < post_floor_y + 0.55f) { + const float raw_post_y = level.sample_height_world(craft.curr_pose.pos.x, craft.curr_pose.pos.z); + const bool on_bridge_deck = (post_floor_y > raw_post_y + 0.5f); + if (!on_bridge_deck && (!craft.airborne || craft.curr_pose.pos.y < post_floor_y + 0.55f)) { Vec3 surf_n = level.sample_normal_world(craft.curr_pose.pos.x, craft.curr_pose.pos.z); if (surf_n.y < 0.49f) { float hn_len = std::sqrt(surf_n.x * surf_n.x + surf_n.z * surf_n.z); @@ -334,6 +387,19 @@ bool resolve_world_collisions(CraftState& craft, const assets::LevelData& level, } } + // Re-clamp ceiling after any escape/pop/cliff vertical lift + level.sample_surface_and_ceiling(craft.curr_pose.pos.x, craft.curr_pose.pos.z, + craft.curr_pose.pos.y, post_floor_y, post_ceil_y); + if (post_ceil_y < 1e5f) { + float max_craft_y = std::max(post_floor_y + 0.14f, post_ceil_y - 0.46f); + if (craft.curr_pose.pos.y > max_craft_y) { + craft.curr_pose.pos.y = max_craft_y; + if (craft.vel.y > 0.0f) { + craft.vel.y = 0.0f; + } + } + } + return hit; } @@ -342,6 +408,9 @@ CraftStepFeedback step_craft_physics(CraftState& craft, const CraftInput& input, bool fuel_enabled) { CraftStepFeedback fb; craft.prev_pose = craft.curr_pose; + if (!std::isfinite(dt) || dt <= 1e-6f) { + return fb; + } if (craft.recovery_state != RecoveryState::Active) { craft.vel = Vec3(0, 0, 0); @@ -357,6 +426,7 @@ CraftStepFeedback step_craft_physics(CraftState& craft, const CraftInput& input, if (craft.invincible_timer > 0.0f) craft.invincible_timer = std::max(0.0f, craft.invincible_timer - dt); if (craft.invisible_timer > 0.0f) craft.invisible_timer = std::max(0.0f, craft.invisible_timer - dt); if (craft.refuel_sound_cd > 0.0f) craft.refuel_sound_cd = std::max(0.0f, craft.refuel_sound_cd - dt); + if (craft.recovery_cooldown > 0.0f) craft.recovery_cooldown = std::max(0.0f, craft.recovery_cooldown - dt); // Steering & banking float steer = std::clamp(input.steer, -1.0f, 1.0f); @@ -409,8 +479,11 @@ CraftStepFeedback step_craft_physics(CraftState& craft, const CraftInput& input, float fwd_spd = craft.vel.dot(fwd); if (fwd_spd > 0.8f) { craft.vel -= fwd * (brake * spec.reverse_accel * 1.6f * dt); - } else { + } else if (has_fuel) { craft.vel -= fwd * (brake * spec.reverse_accel * dt); + } else if (fwd_spd > 0.0f) { + float decel = std::min(fwd_spd, brake * spec.reverse_accel * 1.6f * dt); + craft.vel -= fwd * decel; } } @@ -441,6 +514,11 @@ CraftStepFeedback step_craft_physics(CraftState& craft, const CraftInput& input, constexpr int kSubSteps = 3; float sub_dt = dt / static_cast(kSubSteps); for (int s = 0; s < kSubSteps; ++s) { + float prev_floor_y = 0.0f; + float prev_ceil_y = 1e6f; + level.sample_surface_and_ceiling(craft.curr_pose.pos.x, craft.curr_pose.pos.z, + craft.curr_pose.pos.y, prev_floor_y, prev_ceil_y); + craft.curr_pose.pos.x += craft.vel.x * sub_dt; craft.curr_pose.pos.z += craft.vel.z * sub_dt; @@ -460,7 +538,9 @@ CraftStepFeedback step_craft_physics(CraftState& craft, const CraftInput& input, craft.curr_pose.pos.y, floor_y, ceil_y); float target_y = floor_y + spec.hover_offset; - if (craft.curr_pose.pos.y <= target_y + 0.08f && craft.vel.y <= 3.2f) { + bool grounded_band = (!craft.airborne && craft.curr_pose.pos.y <= target_y + 0.14f) || + (craft.curr_pose.pos.y <= target_y + 0.08f && craft.vel.y <= 3.2f); + if (grounded_band) { // Landed or hovering smoothly if (craft.airborne) { float deg = rad_to_deg(craft.air_spin_accum); @@ -471,21 +551,51 @@ CraftStepFeedback step_craft_physics(CraftState& craft, const CraftInput& input, craft.airtime = 0.0f; craft.air_spin_accum = 0.0f; } + float df = floor_y - prev_floor_y; + float terrain_vy = (std::abs(df) < 0.30f) ? std::clamp(df / sub_dt, 0.0f, 5.5f) : 0.0f; float y_err = target_y - craft.curr_pose.pos.y; - craft.vel.y += (y_err * 95.0f - craft.vel.y * 14.0f) * sub_dt; + craft.vel.y += (y_err * 95.0f - (craft.vel.y - terrain_vy) * 14.0f) * sub_dt; craft.curr_pose.pos.y += craft.vel.y * sub_dt; - // Launch into air when cresting a hill fast! - float next_floor = 0.0f; - float next_ceil = 1e6f; - level.sample_surface_and_ceiling( - craft.curr_pose.pos.x + craft.vel.x * sub_dt * 2.0f, - craft.curr_pose.pos.z + craft.vel.z * sub_dt * 2.0f, - craft.curr_pose.pos.y, next_floor, next_ceil); - float ground_drop = (floor_y - next_floor) / std::max(sub_dt * 2.0f, 1e-4f); - if (ceil_y > 1e5f && ground_drop > 3.5f && craft.speed_horizontal() > 10.0f) { - craft.airborne = true; - craft.vel.y = std::max(craft.vel.y, 2.2f); + // Launch into air when cresting a hill or ski-jump ramp! + float hspd = craft.speed_horizontal(); + if (ceil_y > 1e5f && hspd > 5.0f) { + float hx = craft.vel.x / hspd; + float hz = craft.vel.z / hspd; + constexpr float kAheadDist = 0.25f; + float next_floor = 0.0f; + float next_ceil = 1e6f; + level.sample_surface_and_ceiling( + craft.curr_pose.pos.x + hx * kAheadDist, + craft.curr_pose.pos.z + hz * kAheadDist, + craft.curr_pose.pos.y, next_floor, next_ceil); + float ground_drop = (floor_y - next_floor) / (kAheadDist / std::max(hspd, 1.0f)); + + constexpr float kBackDist = 0.85f; + float back_floor = 0.0f; + float back_ceil = 1e6f; + level.sample_surface_and_ceiling( + craft.curr_pose.pos.x - hx * kBackDist, + craft.curr_pose.pos.z - hz * kBackDist, + craft.curr_pose.pos.y, back_floor, back_ceil); + float ramp_slope = (std::abs(floor_y - back_floor) < 1.2f) + ? ((floor_y - back_floor) / kBackDist) + : 0.0f; + bool is_jump_ramp = (ramp_slope > 0.12f); + float min_launch_spd = is_jump_ramp ? 5.0f : 10.0f; + if (ground_drop > 3.5f && hspd > min_launch_spd) { + craft.airborne = true; + if (is_jump_ramp) { + craft.curr_pose.pos.y = std::max(craft.curr_pose.pos.y, target_y); + } + float ramp_vy = is_jump_ramp + ? std::clamp(hspd * ramp_slope * 1.25f + 1.6f, 3.0f, 5.4f) + : 2.2f; + craft.vel.y = std::max(craft.vel.y, ramp_vy); + } else if (craft.curr_pose.pos.y < floor_y + 0.14f) { + craft.curr_pose.pos.y = floor_y + 0.14f; + if (craft.vel.y < 0.0f) craft.vel.y = 0.0f; + } } else if (craft.curr_pose.pos.y < floor_y + 0.14f) { craft.curr_pose.pos.y = floor_y + 0.14f; if (craft.vel.y < 0.0f) craft.vel.y = 0.0f; @@ -513,8 +623,10 @@ CraftStepFeedback step_craft_physics(CraftState& craft, const CraftInput& input, } } - // Banked slope acceleration on tilted track surfaces - if (!craft.airborne) { + // Banked slope acceleration on tilted track surfaces (skip on elevated bridge decks) + const bool sub_on_bridge = + (floor_y > level.sample_height_world(craft.curr_pose.pos.x, craft.curr_pose.pos.z) + 0.5f); + if (!craft.airborne && !sub_on_bridge) { Vec3 sub_n = level.sample_normal_world(craft.curr_pose.pos.x, craft.curr_pose.pos.z); if (sub_n.y >= 0.49f && sub_n.y < 0.78f) { craft.vel.x += sub_n.x * 5.0f * sub_dt; @@ -551,8 +663,14 @@ CraftStepFeedback step_craft_physics(CraftState& craft, const CraftInput& input, float target_scrape = fb.scraping ? std::clamp(craft.speed_horizontal() / spec.top_speed, 0.25f, 1.0f) : 0.0f; craft.scrape_intensity = lerp(craft.scrape_intensity, target_scrape, std::min(1.0f, dt * 16.0f)); - // Visual pitch & roll banking from terrain slope + steering - Vec3 surf_n = level.sample_normal_world(craft.curr_pose.pos.x, craft.curr_pose.pos.z); + // Visual pitch & roll banking from terrain slope + steering (flat normal when riding elevated bridge deck) + float vis_floor = 0.0f, vis_ceil = 1e6f; + level.sample_surface_and_ceiling(craft.curr_pose.pos.x, craft.curr_pose.pos.z, + craft.curr_pose.pos.y, vis_floor, vis_ceil); + const bool vis_on_bridge = + (vis_floor > level.sample_height_world(craft.curr_pose.pos.x, craft.curr_pose.pos.z) + 0.5f); + Vec3 surf_n = vis_on_bridge ? Vec3(0.0f, 1.0f, 0.0f) + : level.sample_normal_world(craft.curr_pose.pos.x, craft.curr_pose.pos.z); float slope_pitch = -std::asin(std::clamp(surf_n.dot(fwd), -0.7f, 0.7f)); float speed_ratio = std::clamp(craft.speed_horizontal() / spec.top_speed, 0.0f, 1.2f); float target_roll = steer * 0.34f * speed_ratio; @@ -606,6 +724,236 @@ bool resolve_craft_pair_collision(CraftState& a, CraftState& b, float& out_rel_s return true; } +bool place_craft_on_track(CraftState& craft, const assets::LevelData& level, + const std::vector& all_crafts, + bool restrict_to_checkpoint_arc) { + const VehicleSpec& spec = kVehicleSpecs[std::clamp(craft.vehicle_idx, 0, 5)]; + + auto finalize_pose = [&](const Vec3& pos, float yaw) { + craft.curr_pose.pos = pos; + craft.curr_pose.yaw = yaw; + craft.curr_pose.pitch = 0.0f; + craft.curr_pose.roll = 0.0f; + craft.vel = Vec3(0.0f, 0.0f, 0.0f); + craft.yaw_rate = 0.0f; + craft.airborne = false; + craft.airtime = 0.0f; + craft.air_spin_accum = 0.0f; + craft.wrong_way = false; + craft.scrape_intensity = 0.0f; + craft.boost_timer = 0.0f; + float dummy_imp = 0.0f; + bool dummy_scr = false; + resolve_world_collisions(craft, level, dummy_imp, dummy_scr); + craft.prev_pose = craft.curr_pose; + craft.pit_stuck_timer = 0.0f; + craft.stuck_in_pit_hint = false; + craft.ai_stuck_timer = 0.0f; + craft.ai_unstuck_timer = 0.0f; + craft.ai_progress_timer = 0.0f; + craft.ai_pit_stay_timer = 0.0f; + craft.ai_seeking_pit = false; + craft.ai_progress_anchor = craft.curr_pose.pos; + craft.ai_anchor_init = true; + craft.ai_wp_best_dist = 1e9f; + craft.ai_wp_stall_timer = 0.0f; + }; + + if (level.main_waypoints.empty()) { + float gx = std::clamp(craft.curr_pose.pos.x, 2.0f, static_cast(assets::kMapWidth - 3)); + float gz = std::clamp(craft.curr_pose.pos.z, 2.0f, static_cast(assets::kMapHeight - 3)); + float gy = level.sample_entity_surface_y(gx, gz); + float fy = 0.0f, cy = 1e6f; + level.sample_surface_and_ceiling(gx, gz, gy + spec.hover_offset, fy, cy); + finalize_pose(Vec3(gx, fy + spec.hover_offset, gz), craft.curr_pose.yaw); + return true; + } + + const int n_wp = static_cast(level.main_waypoints.size()); + const float probe_r = spec.collision_radius + 0.08f; + + auto is_spot_clear = [&](float wx, float wz, float& out_y, bool check_crafts) -> bool { + if (wx < 2.0f || wx > static_cast(assets::kMapWidth - 3) || + wz < 2.0f || wz > static_cast(assets::kMapHeight - 3)) { + return false; + } + float raw_gy = level.sample_height_world(wx, wz); + float gy = level.sample_entity_surface_y(wx, wz); + float fy = 0.0f, cy = 1e6f; + level.sample_surface_and_ceiling(wx, wz, gy + spec.hover_offset, fy, cy); + if (cy - fy < 0.70f) { + return false; + } + bool on_bridge = (fy > raw_gy + 0.5f); + if (!on_bridge && level.sample_normal_world(wx, wz).y < 0.50f) { + return false; + } + const float probe_y = fy + spec.hover_offset; + static constexpr float kOffX[5] = {0.0f, 1.0f, -1.0f, 0.0f, 0.0f}; + static constexpr float kOffZ[5] = {0.0f, 0.0f, 0.0f, 1.0f, -1.0f}; + for (int k = 0; k < 5; ++k) { + float px = wx + kOffX[k] * probe_r; + float pz = wz + kOffZ[k] * probe_r; + if (px < 1.5f || px > static_cast(assets::kMapWidth) - 2.5f || + pz < 1.5f || pz > static_cast(assets::kMapHeight) - 2.5f) { + return false; + } + int ix = static_cast(std::floor(px)); + int iz = static_cast(std::floor(pz)); + if (level.is_cell_solid_at_point(ix, iz, px, pz, probe_y) || + level.is_cliff_blocking_at_y(ix, iz, probe_y)) { + return false; + } + } + if (check_crafts) { + for (const auto& o : all_crafts) { + if (o.id == craft.id || o.recovery_state != RecoveryState::Active) continue; + float dx = o.curr_pose.pos.x - wx; + float dz = o.curr_pose.pos.z - wz; + if (dx * dx + dz * dz < 1.6f * 1.6f && + std::abs(o.curr_pose.pos.y - probe_y) < 1.5f) { + return false; + } + } + } + out_y = probe_y; + return true; + }; + + auto dist_sq_to_wp = [&](int wi) -> float { + float dx = level.main_waypoints[wi].x - craft.curr_pose.pos.x; + float dz = level.main_waypoints[wi].z - craft.curr_pose.pos.z; + return dx * dx + dz * dz; + }; + + int best_wp = -1; + float best_d2 = 1e18f; + + // 1. Constrain recovery to the active [prev_checkpoint, next_checkpoint) arc when monotonic + if (restrict_to_checkpoint_arc && level.checkpoints.size() >= 2 && n_wp >= 4) { + int num_cps = static_cast(level.checkpoints.size()); + int expected_cp = ((craft.next_checkpoint % num_cps) + num_cps) % num_cps; + int prev_cp = (expected_cp + num_cps - 1) % num_cps; + + auto nearest_wp_to_gate = [&](int cp_idx) -> int { + const auto& g = level.checkpoints[cp_idx]; + int bw = 0; + float bd2 = 1e18f; + for (int wi = 0; wi < n_wp; ++wi) { + float dx = level.main_waypoints[wi].x - g.cx; + float dz = level.main_waypoints[wi].z - g.cz; + float d2 = dx * dx + dz * dz; + if (d2 < bd2) { + bd2 = d2; + bw = wi; + } + } + return bw; + }; + + int wp_start = nearest_wp_to_gate(prev_cp); + int wp_end = nearest_wp_to_gate(expected_cp); + int arc_len = (wp_end - wp_start + n_wp) % n_wp; + + if (arc_len > 0 && arc_len <= (n_wp * 3) / 4) { + for (int step = 0; step < arc_len; ++step) { + int wi = (wp_start + step) % n_wp; + const auto& w = level.main_waypoints[wi]; + float dummy_y = 0.0f; + if (!is_spot_clear(w.x, w.z, dummy_y, false)) continue; + float d2 = dist_sq_to_wp(wi); + if (d2 < best_d2) { + best_d2 = d2; + best_wp = wi; + } + } + if (best_wp >= 0 && best_d2 > 60.0f * 60.0f) { + best_wp = -1; + } + } + } + + // 2. Fallback to globally nearest terrain-clear waypoint + if (best_wp < 0) { + best_d2 = 1e18f; + for (int wi = 0; wi < n_wp; ++wi) { + const auto& w = level.main_waypoints[wi]; + float dummy_y = 0.0f; + if (!is_spot_clear(w.x, w.z, dummy_y, false)) continue; + float d2 = dist_sq_to_wp(wi); + if (d2 < best_d2) { + best_d2 = d2; + best_wp = wi; + } + } + } + + // 3. Last-resort nearest waypoint by 2D distance + if (best_wp < 0) { + best_wp = 0; + best_d2 = 1e18f; + for (int wi = 0; wi < n_wp; ++wi) { + float d2 = dist_sq_to_wp(wi); + if (d2 < best_d2) { + best_d2 = d2; + best_wp = wi; + } + } + } + + const auto& wp = level.main_waypoints[best_wp]; + const auto& wpn = level.main_waypoints[(best_wp + 1) % n_wp]; + Vec2 fwd(wpn.x - wp.x, wpn.z - wp.z); + if (fwd.len_sq() < 1e-4f) { + fwd = Vec2(0.0f, -1.0f); + } else { + fwd = fwd.normalized(); + } + Vec2 right(-fwd.y, fwd.x); + const float yaw = std::atan2(fwd.x, fwd.y); + + float chosen_x = wp.x; + float chosen_z = wp.z; + float chosen_y = level.sample_entity_surface_y(wp.x, wp.z) + spec.hover_offset; + + const Vec2 offsets[5] = { + Vec2(0.0f, 0.0f), + right * 0.9f, + right * -0.9f, + fwd * -1.6f, + fwd * -3.0f, + }; + bool placed_clear = false; + for (const auto& off : offsets) { + float tx = wp.x + off.x; + float tz = wp.z + off.y; + float ty = 0.0f; + if (is_spot_clear(tx, tz, ty, true)) { + chosen_x = tx; + chosen_z = tz; + chosen_y = ty; + placed_clear = true; + break; + } + } + if (!placed_clear) { + float ty = 0.0f; + if (is_spot_clear(wp.x, wp.z, ty, false)) { + chosen_y = ty; + } else { + float gy = level.sample_entity_surface_y(wp.x, wp.z); + float fy = 0.0f, cy = 1e6f; + level.sample_surface_and_ceiling(wp.x, wp.z, gy + spec.hover_offset, fy, cy); + chosen_y = fy + spec.hover_offset; + } + } + + finalize_pose(Vec3(chosen_x, chosen_y, chosen_z), yaw); + craft.current_wp = best_wp; + craft.ai_target_wp = (best_wp + 1) % n_wp; + return true; +} + CraftPose interpolate_pose(const CraftState& craft, float alpha) { CraftPose out; out.pos = lerp(craft.prev_pose.pos, craft.curr_pose.pos, alpha); diff --git a/src/sim/physics.hpp b/src/sim/physics.hpp index 30c6536..54cc293 100644 --- a/src/sim/physics.hpp +++ b/src/sim/physics.hpp @@ -6,6 +6,7 @@ #include "sim/vehicle_defs.hpp" #include +#include namespace top_octane::sim { @@ -73,6 +74,11 @@ struct CraftState { RecoveryState recovery_state = RecoveryState::Active; float recovery_timer = 0.0f; Vec3 recovery_pos{0.0f, 0.0f, 0.0f}; + bool recovery_refill = true; + float recovery_duration = 3.2f; + float recovery_cooldown = 0.0f; + float pit_stuck_timer = 0.0f; + bool stuck_in_pit_hint = false; // Race / Deathmatch progression int lap = 1; @@ -106,6 +112,8 @@ struct CraftState { Vec3 ai_progress_anchor{0.0f, 0.0f, 0.0f}; float ai_progress_timer = 0.0f; bool ai_anchor_init = false; + float ai_wp_best_dist = 1e9f; + float ai_wp_stall_timer = 0.0f; float speed_horizontal() const { return std::sqrt(vel.x * vel.x + vel.z * vel.z); @@ -137,6 +145,11 @@ bool resolve_world_collisions(CraftState& craft, const assets::LevelData& level, // Resolves sphere-sphere bounce between two active crafts bool resolve_craft_pair_collision(CraftState& a, CraftState& b, float& out_rel_speed); +// Safely places a craft on the nearest clear, drivable main track waypoint +bool place_craft_on_track(CraftState& craft, const assets::LevelData& level, + const std::vector& all_crafts, + bool restrict_to_checkpoint_arc = true); + // Interpolates craft pose for smooth rendering at arbitrary refresh rate CraftPose interpolate_pose(const CraftState& craft, float alpha); diff --git a/src/sim/race_sim.cpp b/src/sim/race_sim.cpp index a0d4e17..c1e1aa7 100644 --- a/src/sim/race_sim.cpp +++ b/src/sim/race_sim.cpp @@ -77,6 +77,7 @@ bool RaceSim::start_race(const assets::LevelData& level, const RaceSetup& setup, props_.clear(); particles_.clear(); events_.clear(); + next_projectile_uid_ = 1; countdown_timer_ = 3.0f; last_countdown_int_ = 4; @@ -96,7 +97,7 @@ bool RaceSim::start_race(const assets::LevelData& level, const RaceSetup& setup, p.active = p.group_unlocked; float tx = e.tile_x() + 0.5f; float tz = e.tile_z() + 0.5f; - p.pos = Vec3(tx, level_.sample_height_world(tx, tz) + 0.45f, tz); + p.pos = Vec3(tx, level_.sample_entity_surface_y(tx, tz) + 0.45f, tz); pickups_.push_back(p); } } @@ -108,7 +109,8 @@ bool RaceSim::start_race(const assets::LevelData& level, const RaceSetup& setup, else pr.model_key = "CONE0-0"; float tx = e.tile_x() + 0.5f; float tz = e.tile_z() + 0.5f; - pr.pos = Vec3(tx, level_.sample_height_world(tx, tz) + 0.25f, tz); + float sy = level_.sample_entity_surface_y(tx, tz); + pr.pos = Vec3(tx, (e.subtype == 3) ? sy : (sy + 0.14f), tz); props_.push_back(pr); } @@ -306,7 +308,7 @@ void RaceSim::compute_start_grid(int count, std::vector& out_poses) c } void RaceSim::step(const CraftInput& p1_input, const CraftInput& p2_input, float dt) { - if (race_over_) return; + if (!std::isfinite(dt) || dt <= 1e-6f || race_over_) return; // Countdown handling if (countdown_timer_ > 0.0f) { @@ -334,7 +336,7 @@ void RaceSim::step(const CraftInput& p1_input, const CraftInput& p2_input, float update_active_morphs(dt); update_steam_vents(dt); - std::vector inputs(crafts_.size()); + step_inputs_.resize(crafts_.size()); for (size_t i = 0; i < crafts_.size(); ++i) { CraftState& c = crafts_[i]; CraftInput in; @@ -345,6 +347,9 @@ void RaceSim::step(const CraftInput& p1_input, const CraftInput& p2_input, float events_.push_back({SimSoundCue::None, c.curr_pose.pos, c.player_index, c.autopilot ? "AUTO PILOT ON" : "AUTO PILOT OFF", 0.0f}); } + if (in.recover_pressed && !c.finished && c.recovery_state == RecoveryState::Active) { + trigger_track_recovery(c, events_); + } if (c.autopilot) { CraftInput ai_in = compute_ai_input(c, level_, crafts_, setup_.difficulty, dt); in.steer = ai_in.steer; @@ -354,7 +359,7 @@ void RaceSim::step(const CraftInput& p1_input, const CraftInput& p2_input, float } else { in = compute_ai_input(c, level_, crafts_, setup_.difficulty, dt); } - inputs[i] = in; + step_inputs_[i] = in; float prev_boost_timer = c.boost_timer; CraftStepFeedback fb = step_craft_physics(c, in, level_, dt, setup_.fuel_enabled); @@ -441,28 +446,67 @@ void RaceSim::step(const CraftInput& p1_input, const CraftInput& p2_input, float update_checkpoints_and_laps(c, dt); update_recharge_pads(c, dt); update_triggers(c); + + // Detect when a human craft is trapped in a deep pit or wedged against a cliff/wall + if (!c.is_human || c.autopilot || c.finished || + c.recovery_state != RecoveryState::Active || c.on_pit_mask != 0 || + level_.main_waypoints.empty()) { + c.pit_stuck_timer = 0.0f; + c.stuck_in_pit_hint = false; + } else { + int n_wp = static_cast(level_.main_waypoints.size()); + int wp_i = std::clamp(c.current_wp, 0, n_wp - 1); + const auto& wp = level_.main_waypoints[wp_i]; + float wp_y = level_.sample_height_world(wp.x, wp.z); + bool input_driving = (in.throttle > 0.1f || in.brake > 0.1f || in.boost); + bool input_any = (input_driving || std::abs(in.steer) > 0.15f); + float spd = c.speed_horizontal(); + bool deep_in_pit = (wp_y - c.curr_pose.pos.y >= 1.05f) && + (spd < 4.5f || fb.collided_wall || input_any); + bool wedged = input_driving && (spd < 2.0f); + if (deep_in_pit || wedged) { + c.pit_stuck_timer += dt; + } else { + c.pit_stuck_timer = std::max(0.0f, c.pit_stuck_timer - dt * 2.5f); + } + if (c.pit_stuck_timer >= 2.0f) { + c.stuck_in_pit_hint = true; + } else if (c.pit_stuck_timer < 0.5f) { + c.stuck_in_pit_hint = false; + } + } } // Combat, projectiles, pickups, props, and recovery craft - std::vector projectile_traces; - step_combat_and_world(setup_, level_, crafts_, inputs, projectiles_, pickups_, props_, - particles_, events_, race_over_, winner_id_, dt, &projectile_traces); - update_rocket_triggers(projectile_traces); + step_traces_.clear(); + step_combat_and_world(setup_, level_, crafts_, step_inputs_, projectiles_, pickups_, props_, + particles_, events_, race_over_, winner_id_, dt, &step_traces_, + &next_projectile_uid_); + update_rocket_triggers(step_traces_); // Multi-iteration craft-to-craft + world re-projection solver so squeezed crafts never clip walls for (int iter = 0; iter < 2; ++iter) { + pair_moved_.assign(crafts_.size(), 0); + bool any_pair = false; for (size_t i = 0; i < crafts_.size(); ++i) { for (size_t j = i + 1; j < crafts_.size(); ++j) { float rel = 0.0f; - if (resolve_craft_pair_collision(crafts_[i], crafts_[j], rel) && iter == 0 && rel > 3.5f) { - events_.push_back({SimSoundCue::Impact, crafts_[i].curr_pose.pos, - crafts_[i].is_human ? crafts_[i].player_index : - (crafts_[j].is_human ? crafts_[j].player_index : -1), - "", std::clamp(rel / 15.0f, 0.15f, 0.8f)}); + if (resolve_craft_pair_collision(crafts_[i], crafts_[j], rel)) { + pair_moved_[i] = 1; + pair_moved_[j] = 1; + any_pair = true; + if (iter == 0 && rel > 3.5f) { + events_.push_back({SimSoundCue::Impact, crafts_[i].curr_pose.pos, + crafts_[i].is_human ? crafts_[i].player_index : + (crafts_[j].is_human ? crafts_[j].player_index : -1), + "", std::clamp(rel / 15.0f, 0.15f, 0.8f)}); + } } } } + if (!any_pair) break; for (size_t i = 0; i < crafts_.size(); ++i) { + if (!pair_moved_[i]) continue; float dummy_imp = 0.0f; bool dummy_scr = false; resolve_world_collisions(crafts_[i], level_, dummy_imp, dummy_scr); @@ -486,6 +530,18 @@ void RaceSim::step(const CraftInput& p1_input, const CraftInput& p2_input, float update_particles(dt); } +bool RaceSim::request_track_recovery(int player_index) { + if (countdown_timer_ > 0.0f || race_over_) { + return false; + } + for (auto& c : crafts_) { + if (c.is_human && c.player_index == player_index) { + return trigger_track_recovery(c, events_); + } + } + return false; +} + void RaceSim::update_checkpoints_and_laps(CraftState& c, float dt) { if (level_.checkpoints.empty() || c.finished) return; int num_cps = static_cast(level_.checkpoints.size()); @@ -494,8 +550,12 @@ void RaceSim::update_checkpoints_and_laps(CraftState& c, float dt) { int expected = c.next_checkpoint % num_cps; const auto& gate = level_.checkpoints[expected]; + Vec2 move = p1 - p0; + float mlen = move.len(); + bool moving_forward = (mlen <= 1e-4f || move.dot(gate.dir) >= -0.25f * mlen); float cross_frac = 1.0f; - if (segments_intersect_or_near(p0, p1, Vec2(gate.x0, gate.z0), Vec2(gate.x1, gate.z1), + if (moving_forward && + segments_intersect_or_near(p0, p1, Vec2(gate.x0, gate.z0), Vec2(gate.x1, gate.z1), 2.5f, &cross_frac)) { ++c.checkpoints_passed; c.next_checkpoint = (expected + 1) % num_cps; @@ -559,8 +619,10 @@ void RaceSim::update_recharge_pads(CraftState& c, float dt) { const float px = c.curr_pose.pos.x; const float pz = c.curr_pose.pos.z; - const float ground_y = level_.sample_height_world(px, pz); - if (c.curr_pose.pos.y > ground_y + 1.5f) return; + float floor_y = 0.0f; + float ceil_y = 1e6f; + level_.sample_surface_and_ceiling(px, pz, c.curr_pose.pos.y, floor_y, ceil_y); + if (c.curr_pose.pos.y > floor_y + 1.5f) return; bool in_shield = false; bool in_fuel = false; @@ -616,17 +678,23 @@ void RaceSim::push_dirty_rect(int x0, int z0, int x1, int z1) { int cz1 = std::clamp(z1, 0, assets::kMapHeight - 2); if (cx0 > cx1 || cz0 > cz1) return; - for (int z = cz0; z <= cz1 + 1 && !columns_dirty_; ++z) { - for (int x = cx0; x <= cx1 + 1; ++x) { - if (level_.cell(x, z).tex_or_col < 0) { - columns_dirty_ = true; - break; + if (!columns_dirty_) { + int col_x0 = std::max(0, cx0 + 1); + int col_z0 = std::max(0, cz0 + 1); + int col_x1 = std::min(assets::kMapWidth - 1, cx1); + int col_z1 = std::min(assets::kMapHeight - 1, cz1); + for (int z = col_z0; z <= col_z1 && !columns_dirty_; ++z) { + for (int x = col_x0; x <= col_x1; ++x) { + if (level_.cell(x, z).tex_or_col < 0) { + columns_dirty_ = true; + break; + } } } } - if (!dirty_rects_.empty()) { - const auto& prev = dirty_rects_.back(); - if (prev.x0 == cx0 && prev.z0 == cz0 && prev.x1 == cx1 && prev.z1 == cz1) { + for (const auto& existing : dirty_rects_) { + if (existing.x0 <= cx0 && existing.z0 <= cz0 && + existing.x1 >= cx1 && existing.z1 >= cz1) { return; } } @@ -668,7 +736,7 @@ void RaceSim::activate_group(uint16_t group, int actor_player, bool allow_banner pk.group_unlocked = true; pk.active = true; pk.respawn_timer = 0.0f; - pk.pos.y = level_.sample_height_world(pk.pos.x, pk.pos.z) + 0.45f; + pk.pos.y = level_.sample_entity_surface_y(pk.pos.x, pk.pos.z) + 0.45f; } } @@ -687,6 +755,9 @@ void RaceSim::activate_group(uint16_t group, int actor_player, bool allow_banner } } else if (ef.subtype == 5 || ef.subtype == 8) { int count = (ef.subtype == 5) ? 6 : 3; + if (ei < steam_vent_timers_.size() && steam_vent_timers_[ei] > 1.5f) { + count = 2; // Avoid particle pool starvation when rapid timed triggers re-fire + } for (int k = 0; k < count; ++k) { float ang = kTwoPi * (static_cast(k) / static_cast(count)); Vec3 v(std::cos(ang) * 0.65f, 2.6f + static_cast(k % 2) * 0.9f, @@ -702,11 +773,16 @@ void RaceSim::activate_group(uint16_t group, int actor_player, bool allow_banner spawn_explosion_fx(particles_, epos, 0.75f); if (setup_.damage_enabled) { for (auto& c : crafts_) { - if (c.recovery_state != RecoveryState::Active) continue; + if (c.recovery_state != RecoveryState::Active || c.invincible_timer > 0.0f) continue; + if (std::abs(c.curr_pose.pos.y - epos.y) > 2.2f) continue; float dx = c.curr_pose.pos.x - ef.x; float dz = c.curr_pose.pos.z - ef.z; if (dx * dx + dz * dz <= 1.5f * 1.5f) { - c.shield = std::max(1.0f, c.shield - 10.0f); + float dmg = std::min(10.0f, std::max(0.0f, c.shield - 1.0f)); + if (dmg > 0.0f) { + c.shield -= dmg; + c.armour_used += dmg; + } c.damage_flash = 0.22f; } } @@ -784,12 +860,41 @@ void RaceSim::activate_group(uint16_t group, int actor_player, bool allow_banner continue; } + // Relocate secret-room pickups stored in morph SRC sector into the track DST sector + if (m.dst_x != m.src_x || m.dst_z != m.src_z) { + const float sx0 = static_cast(m.src_x); + const float sx1 = static_cast(m.src_x + m.size_x + 1); + const float sz0 = static_cast(m.src_z); + const float sz1 = static_cast(m.src_z + m.size_z + 1); + const float dx0 = static_cast(m.dst_x); + const float dx1 = static_cast(m.dst_x + m.size_x + 1); + const float dz0 = static_cast(m.dst_z); + const float dz1 = static_cast(m.dst_z + m.size_z + 1); + const float shift_x = dx0 - sx0; + const float shift_z = dz0 - sz0; + for (auto& pk : pickups_) { + const bool in_src = (pk.pos.x >= sx0 && pk.pos.x < sx1 && + pk.pos.z >= sz0 && pk.pos.z < sz1); + const bool in_dst = (pk.pos.x >= dx0 && pk.pos.x < dx1 && + pk.pos.z >= dz0 && pk.pos.z < dz1); + if (in_src && !in_dst) { + pk.pos.x += shift_x; + pk.pos.z += shift_z; + pk.pos.y = level_.sample_entity_surface_y(pk.pos.x, pk.pos.z) + 0.45f; + } + } + } + am.duration = height_differs ? (fast_morph ? 0.35f : 0.50f) : 0.0f; push_dirty_rect(m.dst_x - 2, m.dst_z - 2, m.dst_x + m.size_x + 1, m.dst_z + m.size_z + 1); push_dirty_rect(m.src_x - 2, m.src_z - 2, m.src_x + m.size_x + 1, m.src_z + m.size_z + 1); if (am.duration <= 0.0f) { apply_morph_fraction(am, 1.0f); + morph_touched_.clear(); + morph_touched_.push_back({m.dst_x, m.dst_z, m.dst_x + m.size_x, m.dst_z + m.size_z}); + morph_touched_.push_back({m.src_x, m.src_z, m.src_x + m.size_x, m.src_z + m.size_z}); + resnap_entities_in_rects(morph_touched_); } else { active_morphs_.push_back(std::move(am)); } @@ -856,6 +961,18 @@ void RaceSim::update_rocket_triggers(const std::vector& traces) if (!segment_intersects_aabb(trace.p0, trace.p1, x0, x1, y0, y1, z0, z1)) { continue; } + if (trace.projectile_uid != 0) { + bool dup = false; + for (uint32_t seen_id : ts.recent_uids) { + if (seen_id == trace.projectile_uid) { + dup = true; + break; + } + } + if (dup) continue; + ts.recent_uids[ts.recent_uid_pos % ts.recent_uids.size()] = trace.projectile_uid; + ts.recent_uid_pos = static_cast((ts.recent_uid_pos + 1u) % ts.recent_uids.size()); + } ts.hit_accum += (trace.is_missile ? 3 : 1); if (ts.hit_accum >= 3) { ts.fired = true; @@ -873,36 +990,10 @@ void RaceSim::update_rocket_triggers(const std::vector& traces) } } -void RaceSim::update_active_morphs(float dt) { - if (active_morphs_.empty()) return; - - std::vector touched; - std::vector repeat_permanent; - for (size_t ai = 0; ai < active_morphs_.size();) { - auto& am = active_morphs_[ai]; - am.elapsed += dt; - float t = (am.duration > 1e-4f) ? std::clamp(am.elapsed / am.duration, 0.0f, 1.0f) : 1.0f; - float s = t * t * (3.0f - 2.0f * t); - apply_morph_fraction(am, s); - - if (am.morph_idx < level_.morphs.size()) { - const auto& m = level_.morphs[am.morph_idx]; - touched.push_back({m.dst_x, m.dst_z, m.dst_x + m.size_x, m.dst_z + m.size_z}); - touched.push_back({m.src_x, m.src_z, m.src_x + m.size_x, m.src_z + m.size_z}); - if (t >= 1.0f && m.permanent) { - repeat_permanent.push_back(am.morph_idx); - } - } - - if (t >= 1.0f) { - active_morphs_.erase(active_morphs_.begin() + static_cast(ai)); - } else { - ++ai; - } - } - +void RaceSim::resnap_entities_in_rects(const std::vector& rects) { + if (rects.empty()) return; auto touches_any = [&](float wx, float wz, float pad) -> bool { - for (const auto& r : touched) { + for (const auto& r : rects) { if (wx >= static_cast(r.x0) - pad && wx <= static_cast(r.x1 + 1) + pad && wz >= static_cast(r.z0) - pad && wz <= static_cast(r.z1 + 1) + pad) { return true; @@ -913,30 +1004,73 @@ void RaceSim::update_active_morphs(float dt) { for (auto& pk : pickups_) { if (touches_any(pk.pos.x, pk.pos.z, 1.0f)) { - pk.pos.y = level_.sample_height_world(pk.pos.x, pk.pos.z) + 0.45f; + pk.pos.y = level_.sample_entity_surface_y(pk.pos.x, pk.pos.z) + 0.45f; } } for (auto& pr : props_) { if (touches_any(pr.pos.x, pr.pos.z, 1.0f)) { - pr.pos.y = level_.sample_height_world(pr.pos.x, pr.pos.z) + 0.25f; + float sy = level_.sample_entity_surface_y(pr.pos.x, pr.pos.z); + pr.pos.y = (pr.subtype == 3) ? sy : (sy + 0.14f); } } for (auto& c : crafts_) { - if (c.recovery_state != RecoveryState::Active) continue; - if (touches_any(c.curr_pose.pos.x, c.curr_pose.pos.z, 1.5f)) { - float imp = 0.0f; - bool scr = false; - resolve_world_collisions(c, level_, imp, scr); - float fy = 0.0f, cy = 1e6f; - level_.sample_surface_and_ceiling(c.curr_pose.pos.x, c.curr_pose.pos.z, - c.curr_pose.pos.y, fy, cy); - if (c.curr_pose.pos.y < fy + 0.14f) { - c.curr_pose.pos.y = fy + kVehicleSpecs[std::clamp(c.vehicle_idx, 0, 5)].hover_offset; + if (!touches_any(c.curr_pose.pos.x, c.curr_pose.pos.z, 1.5f)) continue; + const float hover = kVehicleSpecs[std::clamp(c.vehicle_idx, 0, 5)].hover_offset; + if (c.recovery_state != RecoveryState::Active) { + float sy = level_.sample_entity_surface_y(c.curr_pose.pos.x, c.curr_pose.pos.z); + c.curr_pose.pos.y = sy + hover; + c.recovery_pos.y = c.curr_pose.pos.y; + continue; + } + float imp = 0.0f; + bool scr = false; + resolve_world_collisions(c, level_, imp, scr); + float fy = 0.0f, cy = 1e6f; + level_.sample_surface_and_ceiling(c.curr_pose.pos.x, c.curr_pose.pos.z, + c.curr_pose.pos.y, fy, cy); + if (c.curr_pose.pos.y < fy + 0.14f) { + c.curr_pose.pos.y = fy + hover; + } + if (cy < 1e5f) { + float max_y = std::max(fy + 0.14f, cy - 0.46f); + if (c.curr_pose.pos.y > max_y) { + c.curr_pose.pos.y = max_y; } } } +} - for (size_t mi : repeat_permanent) { +void RaceSim::update_active_morphs(float dt) { + if (active_morphs_.empty()) return; + + morph_touched_.clear(); + morph_repeat_.clear(); + for (size_t ai = 0; ai < active_morphs_.size();) { + auto& am = active_morphs_[ai]; + am.elapsed += dt; + float t = (am.duration > 1e-4f) ? std::clamp(am.elapsed / am.duration, 0.0f, 1.0f) : 1.0f; + float s = t * t * (3.0f - 2.0f * t); + apply_morph_fraction(am, s); + + if (am.morph_idx < level_.morphs.size()) { + const auto& m = level_.morphs[am.morph_idx]; + morph_touched_.push_back({m.dst_x, m.dst_z, m.dst_x + m.size_x, m.dst_z + m.size_z}); + morph_touched_.push_back({m.src_x, m.src_z, m.src_x + m.size_x, m.src_z + m.size_z}); + if (t >= 1.0f && m.permanent) { + morph_repeat_.push_back(am.morph_idx); + } + } + + if (t >= 1.0f) { + active_morphs_.erase(active_morphs_.begin() + static_cast(ai)); + } else { + ++ai; + } + } + + resnap_entities_in_rects(morph_touched_); + + for (size_t mi : morph_repeat_) { if (mi >= level_.morphs.size()) continue; const auto& m = level_.morphs[mi]; int w = m.size_x + 1; @@ -998,10 +1132,10 @@ void RaceSim::update_triggers(CraftState& c) { } void RaceSim::update_standings() { - std::vector order(crafts_.size()); - for (size_t i = 0; i < crafts_.size(); ++i) order[i] = i; + standings_order_.resize(crafts_.size()); + for (size_t i = 0; i < crafts_.size(); ++i) standings_order_[i] = i; - std::sort(order.begin(), order.end(), [&](size_t ia, size_t ib) { + std::sort(standings_order_.begin(), standings_order_.end(), [&](size_t ia, size_t ib) { const CraftState& a = crafts_[ia]; const CraftState& b = crafts_[ib]; if (setup_.mode == GameMode::DeathMatch) { @@ -1026,8 +1160,8 @@ void RaceSim::update_standings() { return ia < ib; }); - for (size_t rank = 0; rank < order.size(); ++rank) { - crafts_[order[rank]].placement = static_cast(rank + 1); + for (size_t rank = 0; rank < standings_order_.size(); ++rank) { + crafts_[standings_order_[rank]].placement = static_cast(rank + 1); } // End non-DeathMatch races only when all human players have finished @@ -1045,7 +1179,7 @@ void RaceSim::update_standings() { } } if (race_over_ && !times_finalized_ && setup_.mode != GameMode::DeathMatch) { - finalize_unfinished_times(order); + finalize_unfinished_times(standings_order_); times_finalized_ = true; } } diff --git a/src/sim/race_sim.hpp b/src/sim/race_sim.hpp index 767baaf..50d69fd 100644 --- a/src/sim/race_sim.hpp +++ b/src/sim/race_sim.hpp @@ -5,6 +5,7 @@ #include "input/input_manager.hpp" #include "sim/physics.hpp" +#include #include #include #include @@ -50,6 +51,7 @@ struct SimEvent { }; struct Projectile { + uint32_t uid = 0; bool active = false; bool is_missile = false; int owner_id = -1; @@ -122,6 +124,7 @@ struct ProjectileTrace { Vec3 p1{0, 0, 0}; int owner_player = -1; bool is_missile = false; + uint32_t projectile_uid = 0; }; struct RaceSetup { @@ -154,6 +157,9 @@ public: // Advances 1 fixed 60 Hz tick void step(const CraftInput& p1_input, const CraftInput& p2_input, float dt); + // Manually triggers track recovery for human player (0 = P1, 1 = P2) + bool request_track_recovery(int player_index); + const RaceSetup& setup() const { return setup_; } const assets::LevelData& level() const { return level_; } const std::vector& crafts() const { return crafts_; } @@ -187,6 +193,8 @@ private: float timer = 0.0f; int hit_accum = 0; int pending_player = -1; + std::array recent_uids{}; + uint8_t recent_uid_pos = 0; }; struct ActiveMorph { @@ -204,6 +212,7 @@ private: void update_timed_triggers(float dt); void update_rocket_triggers(const std::vector& traces); void update_active_morphs(float dt); + void resnap_entities_in_rects(const std::vector& rects); void apply_morph_fraction(const ActiveMorph& am, float s); void push_dirty_rect(int x0, int z0, int x1, int z1); void activate_group(uint16_t group, int actor_player, bool allow_banner, bool fast_morph = false); @@ -220,6 +229,15 @@ private: std::vector props_; std::vector particles_; std::vector events_; + uint32_t next_projectile_uid_ = 1; + + // Per-step reusable scratch buffers (avoids 60 Hz heap allocs) + std::vector step_inputs_; + std::vector step_traces_; + std::vector standings_order_; + std::vector morph_touched_; + std::vector morph_repeat_; + std::vector pair_moved_; float countdown_timer_ = 3.0f; int last_countdown_int_ = 4; diff --git a/tests/test_assets.cpp b/tests/test_assets.cpp index e9d2008..a8fbe46 100644 --- a/tests/test_assets.cpp +++ b/tests/test_assets.cpp @@ -15,7 +15,9 @@ #include #include #include +#include #include +#include #include using namespace top_octane; @@ -386,5 +388,101 @@ int main() { std::cout << "[PASS] Vfs relocatable & XDG data directory lookup validated\n"; } + // 9. GameConfig recovery keybindings defaults & persistence round-trip + { + GameConfig def_cfg; + CHECK(def_cfg.keys.recover == 21); + CHECK(def_cfg.keys.p2_recover == 42); + + std::filesystem::path tmp_ini = std::filesystem::temp_directory_path() / "top_octane_test_config.ini"; + std::filesystem::remove(tmp_ini); + + GameConfig saved_cfg; + saved_cfg.keys.recover = 29; // Z + saved_cfg.keys.p2_recover = 76; // Delete + CHECK(saved_cfg.save(tmp_ini)); + + GameConfig loaded_cfg; + CHECK(loaded_cfg.load(tmp_ini)); + CHECK(loaded_cfg.keys.recover == 29); + CHECK(loaded_cfg.keys.p2_recover == 76); + + std::filesystem::remove(tmp_ini); + std::cout << "[PASS] GameConfig keybinding persistence validated\n"; + } + + // 10. Security hardening (VFS traversal, RNC1/RNC2 bombs & truncation, WAV, corrupt config) + { + std::vector tmp_buf; + CHECK(!vfs.exists("../Makefile")); + CHECK(!vfs.exists("/etc/passwd")); + CHECK(!vfs.read_file("../Makefile", tmp_buf)); + CHECK(!vfs.read_file("/etc/passwd", tmp_buf)); + + // RNC1 bomb (> 32 MiB) & truncated RNC1/RNC2 headers + const std::vector rnc1_bomb = { + 'R', 'N', 'C', 1, 0x04, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x10, 0, 0, 0, 0, 0, 0 + }; + const std::vector rnc1_trunc = { + 'R', 'N', 'C', 1, 0x00, 0x00, 0x00, 0x20, + 0x00, 0x00, 0x00, 0x10, 0, 0 + }; + const std::vector rnc2_bomb = { + 'R', 'N', 'C', 2, 0x04, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x10, 0, 0, 0, 0, 0, 0 + }; + const std::vector rnc2_trunc = { + 'R', 'N', 'C', 2, 0x00, 0x00, 0x00, 0x10, + 0x00, 0x00, 0x00, 0x04, 0, 0, 0, 0, 0, 0 + }; + CHECK(!rnc_unpack(rnc1_bomb, tmp_buf)); + CHECK(!rnc_unpack(rnc1_trunc, tmp_buf)); + CHECK(!rnc_unpack(rnc2_bomb, tmp_buf)); + CHECK(!rnc_unpack(rnc2_trunc, tmp_buf)); + + // Invalid WAV / empty buffers + SoundSample bad_wav_out; + const std::vector garbage_wav = {'R', 'I', 'F', 'F', 12, 0, 0, 0, 'W', 'A', 'V', 'E'}; + CHECK(!decode_wav_bytes(nullptr, 0, bad_wav_out)); + CHECK(!decode_wav_bytes(garbage_wav.data(), garbage_wav.size(), bad_wav_out)); + + // Corrupt GameConfig (NaN/Inf/out-of-range/path-traversal) rejected/sanitized cleanly + std::filesystem::path bad_ini = std::filesystem::temp_directory_path() / "top_octane_bad_cfg.ini"; + { + std::ofstream ofs(bad_ini); + ofs << "fov_deg = nan\n" + << "draw_distance = inf\n" + << "master_volume = -inf\n" + << "key_recover = -9\n" + << "key_p2_recover = 99999\n" + << "custom_soundfont_path = ../evil.sf2\n"; + } + GameConfig bad_cfg; + CHECK(bad_cfg.load(bad_ini)); + CHECK(std::isfinite(bad_cfg.fov_deg) && bad_cfg.fov_deg >= 50.0f && bad_cfg.fov_deg <= 105.0f); + CHECK(std::isfinite(bad_cfg.draw_distance) && bad_cfg.draw_distance >= 30.0f); + CHECK(std::isfinite(bad_cfg.master_volume) && bad_cfg.master_volume >= 0.0f && bad_cfg.master_volume <= 1.0f); + CHECK(bad_cfg.keys.recover == 21); + CHECK(bad_cfg.keys.p2_recover == 42); + CHECK(bad_cfg.custom_soundfont_path.empty()); + std::filesystem::remove(bad_ini); + std::cout << "[PASS] VFS traversal, RNC bombs, invalid WAV & corrupt GameConfig hardening validated\n"; + } + + // 11. LevelData::sample_entity_surface_y on L6 skybridge, L8 bridge/archway, L9 alcove + { + LevelData lvl6, lvl8, lvl9; + CHECK(lvl6.load(vfs, 6)); + CHECK(lvl8.load(vfs, 8)); + CHECK(lvl9.load(vfs, 9)); + CHECK(lvl6.sample_entity_surface_y(90.5f, 39.5f) >= 2.9f); + CHECK(lvl6.sample_entity_surface_y(87.5f, 39.5f) >= 2.9f); + CHECK(lvl8.sample_entity_surface_y(75.5f, 70.5f) >= 1.9f); + CHECK(lvl8.sample_entity_surface_y(46.5f, 19.5f) < 0.5f); + CHECK(lvl9.sample_entity_surface_y(10.0f, 88.0f) < 0.8f); + std::cout << "[PASS] LevelData::sample_entity_surface_y bridge/archway/alcove heights validated\n"; + } + return 0; } diff --git a/tests/test_gameplay.cpp b/tests/test_gameplay.cpp index 6c2fcff..d8aace7 100644 --- a/tests/test_gameplay.cpp +++ b/tests/test_gameplay.cpp @@ -10,6 +10,7 @@ #include #include #include +#include using namespace top_octane; @@ -1082,5 +1083,232 @@ int main() { } std::cout << "[PASS] All 9 tracks 8-racer AI anti-stuck & progression validated\n"; + // 12. Manual Track Recovery from pit, HUD stuck hint, anti-exploit, and SplitScreen P2 + { + sim::RaceSetup rs; + rs.mode = sim::GameMode::SingleRace; + rs.track_number = 1; + rs.num_ai = 0; + rs.fuel_enabled = true; + + sim::RaceSim rsim; + CHECK(rsim.start_race(lvl1, rs)); + // Still in countdown -> cannot trigger manual recovery + CHECK(!rsim.request_track_recovery(0)); + for (int t = 0; t < 200; ++t) rsim.step(CraftInput{}, CraftInput{}, dt); + + auto& p1 = rsim.crafts_mut()[0]; + p1.curr_pose.pos = Vec3(32.5f, lvl1.sample_height_world(32.5f, 57.5f) + 0.28f, 57.5f); + p1.curr_pose.yaw = kHalfPi; + p1.prev_pose = p1.curr_pose; + p1.vel = Vec3(0.0f, 0.0f, 0.0f); + p1.next_checkpoint = 1; + p1.shield = p1.max_shield * 0.50f; + p1.ammo = p1.max_ammo * 0.40f; + p1.fuel = 42.0f; + + // Driving trapped inside pit triggers HUD stuck hint after ~2.0s + CraftInput drive_fwd; + drive_fwd.throttle = 1.0f; + for (int t = 0; t < 135; ++t) rsim.step(drive_fwd, CraftInput{}, dt); + CHECK(p1.curr_pose.pos.y < 0.0f); + CHECK(p1.stuck_in_pit_hint); + + const float pre_shield = p1.shield; + const float pre_ammo = p1.ammo; + const float pre_fuel = p1.fuel; + + // Press manual recover key + rsim.clear_events(); + CraftInput rec_in; + rec_in.recover_pressed = true; + rsim.step(rec_in, CraftInput{}, dt); + CHECK(p1.recovery_state == sim::RecoveryState::CallingRepair); + CHECK(!p1.recovery_refill); + CHECK(!p1.stuck_in_pit_hint); + CHECK(!sim::get_recovery_visuals(rsim.crafts()).empty()); + + bool saw_recovery_banner = false; + for (const auto& ev : rsim.events()) { + if (ev.banner_text == "CALLING RECOVERY") saw_recovery_banner = true; + } + CHECK(saw_recovery_banner); + + // Wait ~1.75s for manual recovery sequence (1.6s) to complete + for (int t = 0; t < 105; ++t) rsim.step(CraftInput{}, CraftInput{}, dt); + CHECK(p1.recovery_state == sim::RecoveryState::Active); + CHECK(p1.deaths == 0); + CHECK(p1.curr_pose.pos.y > 0.0f); + CHECK(p1.curr_pose.pos.x < 25.0f); + CHECK(p1.next_checkpoint == 1); + CHECK(!p1.stuck_in_pit_hint); + int px = static_cast(std::floor(p1.curr_pose.pos.x)); + int pz = static_cast(std::floor(p1.curr_pose.pos.z)); + CHECK(!lvl1.is_cell_solid_at_point(px, pz, p1.curr_pose.pos.x, + p1.curr_pose.pos.z, p1.curr_pose.pos.y)); + CHECK(!lvl1.is_cliff_blocking_at_y(px, pz, p1.curr_pose.pos.y)); + + // Resources were not freely topped off (anti-exploit) + CHECK(std::abs(p1.shield - pre_shield) < 0.01f); + CHECK(std::abs(p1.ammo - pre_ammo) < 0.01f); + CHECK(p1.fuel <= pre_fuel + 0.01f); + CHECK(p1.fuel < p1.max_fuel * 0.6f); + + // Cooldown prevents instant spam right after recovery completes + CHECK(p1.recovery_cooldown > 0.5f); + rsim.step(rec_in, CraftInput{}, dt); + CHECK(p1.recovery_state == sim::RecoveryState::Active); + + // Finished craft cannot recover + p1.finished = true; + CHECK(!rsim.request_track_recovery(0)); + + // SplitScreen P2 manual recovery & emergency minimal fuel floor (<5 -> 8) + sim::RaceSetup ss; + ss.mode = sim::GameMode::SplitScreen; + ss.track_number = 1; + ss.num_ai = 0; + ss.fuel_enabled = true; + sim::RaceSim ssim; + CHECK(ssim.start_race(lvl1, ss)); + for (int t = 0; t < 200; ++t) ssim.step(CraftInput{}, CraftInput{}, dt); + + auto& s_p2 = ssim.crafts_mut()[1]; + s_p2.curr_pose.pos = Vec3(32.5f, lvl1.sample_height_world(32.5f, 57.5f) + 0.28f, 57.5f); + s_p2.prev_pose = s_p2.curr_pose; + s_p2.next_checkpoint = 1; + s_p2.fuel = 1.0f; + + ssim.step(CraftInput{}, rec_in, dt); + CHECK(s_p2.recovery_state == sim::RecoveryState::CallingRepair); + for (int t = 0; t < 110; ++t) ssim.step(CraftInput{}, CraftInput{}, dt); + CHECK(s_p2.recovery_state == sim::RecoveryState::Active); + CHECK(s_p2.curr_pose.pos.y > 0.0f); + CHECK(s_p2.curr_pose.pos.x < 25.0f); + CHECK(s_p2.fuel >= 5.0f && s_p2.fuel < 15.0f); + CHECK(ssim.request_track_recovery(0)); + } + std::cout << "[PASS] Manual Track Recovery from pit, stuck prompt, anti-exploit & SplitScreen P2 validated\n"; + + // 13. Step dt safety, Track 6 off-track AI recovery, DamageCraft & Level 9 morph & save fuzzing + { + // 13a. RaceSim::step ignores dt <= 0 and NaN cleanly + sim::RaceSetup rs; + rs.mode = sim::GameMode::SingleRace; + rs.track_number = 1; + rs.num_ai = 1; + sim::RaceSim sim0; + CHECK(sim0.start_race(lvl1, rs)); + for (int t = 0; t < 200; ++t) sim0.step(CraftInput{}, CraftInput{}, dt); + const Vec3 p_before = sim0.crafts()[0].curr_pose.pos; + sim0.step(CraftInput{0.5f, 1.0f}, CraftInput{}, 0.0f); + sim0.step(CraftInput{0.5f, 1.0f}, CraftInput{}, -0.1f); + sim0.step(CraftInput{0.5f, 1.0f}, CraftInput{}, std::numeric_limits::quiet_NaN()); + CHECK((sim0.crafts()[0].curr_pose.pos - p_before).len_sq() < 1e-8f); + + // 13b. AI circling behind Track 6 perimeter berm recovers via ai_wp_stall_timer in < 10s + assets::LevelData lvl6; + CHECK(lvl6.load(vfs, 6)); + sim::RaceSetup rs6; + rs6.mode = sim::GameMode::SingleRace; + rs6.track_number = 6; + rs6.num_ai = 1; + sim::RaceSim sim6; + CHECK(sim6.start_race(lvl6, rs6)); + sim6.crafts_mut()[0].autopilot = true; + for (int t = 0; t < 200; ++t) sim6.step(CraftInput{}, CraftInput{}, dt); + auto& ai6 = sim6.crafts_mut()[1]; + ai6.curr_pose.pos = Vec3(78.0f, lvl6.sample_height_world(78.0f, 15.0f) + 0.25f, 15.0f); + ai6.prev_pose = ai6.curr_pose; + ai6.vel = Vec3(5.0f, 0.0f, 0.0f); + ai6.current_wp = 0; + ai6.ai_target_wp = 1; + ai6.next_checkpoint = 1; + ai6.ai_stuck_timer = 0.0f; + ai6.ai_progress_timer = 0.0f; + ai6.ai_wp_stall_timer = 0.0f; + ai6.ai_wp_best_dist = 1e9f; + bool recovered = false; + for (int t = 0; t < 600; ++t) { + sim6.step(CraftInput{}, CraftInput{}, dt); + if (ai6.checkpoints_passed >= 1 || ai6.curr_pose.pos.x > 84.0f || ai6.curr_pose.pos.z < 10.0f) { + recovered = true; + break; + } + } + CHECK(recovered); + + // 13c. Invincible craft takes zero weapon/barrel damage & never heals from negative damage + { + std::vector cvec(2); + cvec[0].id = 0; cvec[0].recovery_state = sim::RecoveryState::Active; + cvec[0].curr_pose.pos = Vec3(10.0f, lvl1.sample_height_world(10.0f, 10.0f) + 0.25f, 10.0f); + cvec[0].prev_pose = cvec[0].curr_pose; + cvec[0].shield = 25.0f; cvec[0].max_shield = 100.0f; + cvec[0].invincible_timer = 3.0f; + cvec[1].id = 1; cvec[1].recovery_state = sim::RecoveryState::Active; + cvec[1].curr_pose.pos = cvec[0].curr_pose.pos + Vec3(0.0f, 0.0f, -2.0f); + cvec[1].prev_pose = cvec[1].curr_pose; + std::vector pjs; + sim::Projectile prj; + prj.active = true; prj.owner_id = 1; prj.damage = 40.0f; + prj.pos = cvec[0].curr_pose.pos + Vec3(0.0f, 0.0f, -0.5f); + prj.vel = Vec3(0.0f, 0.0f, 60.0f); + pjs.push_back(prj); + std::vector pks; + std::vector prs; + std::vector pts; + std::vector evs; + std::vector ins(2); + bool ro = false; + int wid = -1; + sim::step_combat_and_world(rs, lvl1, cvec, ins, pjs, pks, prs, pts, evs, ro, wid, dt); + CHECK(std::abs(cvec[0].shield - 25.0f) < 1e-4f); + } + + // 13d. Level 9 st=23 grp=1 permanent morph does not auto-activate and blank arena cells + assets::LevelData lvl9; + CHECK(lvl9.load(vfs, 9)); + sim::RaceSetup rs9; + rs9.mode = sim::GameMode::DeathMatch; + rs9.track_number = 9; + rs9.num_ai = 3; + sim::RaceSim sim9; + CHECK(sim9.start_race(lvl9, rs9)); + for (int t = 0; t < 600; ++t) sim9.step(CraftInput{}, CraftInput{}, dt); + int nontriv_arena_cells = 0; + for (const auto& pad : sim9.level().pads) { + int cx = static_cast(std::floor(pad.cx)); + int cz = static_cast(std::floor(pad.cz)); + const auto& cell = sim9.level().cell(cx, cz); + if (cell.tex_or_col != 0) ++nontriv_arena_cells; + } + CHECK(nontriv_arena_cells == static_cast(sim9.level().pads.size())); + + // 13e. Corrupt/malformed save files safely rejected without mutating valid state + std::filesystem::path bad_dir = std::filesystem::temp_directory_path() / "top_octane_bad_saves"; + std::filesystem::create_directories(bad_dir); + { + std::ofstream ofs(bad_dir / "hiscores.dat"); + ofs << "HIOCTANE_HISCORES_V2\n" + << "TRACK 1 nan 1 DEADFISH 999\n"; + } + game::HighscoreTable ht; + ht.load(bad_dir / "hiscores.dat"); + for (const auto& rec : ht.tracks) { + CHECK(std::isfinite(rec.best_lap)); + CHECK(std::isfinite(rec.best_race)); + } + { + std::ofstream ofs(bad_dir / "clone_t1.dat"); + ofs << "INVALID_MAGIC 1 -9 99 nan 9999999\n"; + } + sim::CloneRecording cre; + CHECK(!game::load_clone_recording(bad_dir, 1, cre)); + std::filesystem::remove_all(bad_dir); + + std::cout << "[PASS] Gameplay dt/AI-basin/invincible/Level9-morph & save hardening validated\n"; + } + return 0; } diff --git a/tests/test_physics.cpp b/tests/test_physics.cpp index 879166a..47a17b1 100644 --- a/tests/test_physics.cpp +++ b/tests/test_physics.cpp @@ -9,6 +9,7 @@ #include #include #include +#include using namespace top_octane; @@ -271,6 +272,9 @@ int main() { std::cout << " Track " << l << " 1-lap autopilot: finished=" << p1.finished << " time=" << p1.race_time << "s\n"; CHECK(p1.finished); + if (l == 8) { + CHECK(p1.race_time < 45.0f); + } } std::cout << "[PASS] 1-lap autopilot completion verified across all 9 tracks\n"; @@ -479,5 +483,145 @@ int main() { CHECK(cruise[3] - cruise[2] >= 8.5f); // Vampyr vs Jugga std::cout << "[PASS] Vehicle top speeds & boost velocities strictly differentiate all 6 crafts\n"; } + + // 11. Track recovery placement from deep pit & under overhead tunnel ceiling + { + assets::LevelData lvl1, lvl2; + CHECK(lvl1.load(vfs, 1)); + CHECK(lvl2.load(vfs, 2)); + + // 11a. Pit trap in Level 1 (32.5, 57.5) between cp 0 and cp 1 stays on outbound leg (x < 25, y > 0) + sim::CraftState pit_car; + pit_car.id = 0; + pit_car.vehicle_idx = 0; + pit_car.next_checkpoint = 1; + pit_car.curr_pose.pos = Vec3(32.5f, lvl1.sample_height_world(32.5f, 57.5f) + 0.28f, 57.5f); + pit_car.prev_pose = pit_car.curr_pose; + pit_car.vel = Vec3(3.0f, -2.0f, 1.0f); + pit_car.wrong_way = true; + + std::vector peers{pit_car}; + CHECK(sim::place_craft_on_track(pit_car, lvl1, peers, true)); + CHECK(pit_car.curr_pose.pos.y > 0.0f); + CHECK(pit_car.curr_pose.pos.x < 25.0f); + CHECK(pit_car.vel.len() < 1e-4f); + CHECK(!pit_car.wrong_way); + int ix = static_cast(std::floor(pit_car.curr_pose.pos.x)); + int iz = static_cast(std::floor(pit_car.curr_pose.pos.z)); + CHECK(!lvl1.is_cell_solid_at_point(ix, iz, pit_car.curr_pose.pos.x, + pit_car.curr_pose.pos.z, pit_car.curr_pose.pos.y)); + CHECK(!lvl1.is_cliff_blocking_at_y(ix, iz, pit_car.curr_pose.pos.y)); + + // 11b. High-Y craft above Level 2 tunnel waypoint (126.5, 23.5) recovers on road beneath roof + float gy2 = lvl2.sample_height_world(126.5f, 23.5f); + sim::CraftState tun_car; + tun_car.id = 0; + tun_car.vehicle_idx = 0; + tun_car.next_checkpoint = 1; + tun_car.curr_pose.pos = Vec3(126.5f, gy2 + 5.0f, 23.5f); + tun_car.prev_pose = tun_car.curr_pose; + std::vector peers2{tun_car}; + CHECK(sim::place_craft_on_track(tun_car, lvl2, peers2, true)); + float road_y2 = lvl2.sample_height_world(tun_car.curr_pose.pos.x, tun_car.curr_pose.pos.z); + CHECK(tun_car.curr_pose.pos.y < road_y2 + 0.60f); + CHECK(tun_car.curr_pose.pos.y >= road_y2 + 0.14f); + std::cout << "[PASS] Track placement from pit & tunnel clearance verified\n"; + } + + // 12. Track 8 (Arctic Land) ramp jump & bridge deck clearance across all 6 vehicles + { + assets::LevelData lvl8; + CHECK(lvl8.load(vfs, 8)); + const float dt = static_cast(FixedStepClock::kFixedDt); + const float jump_yaw = std::atan2(90.5f - 56.0f, 70.5f - 69.5f); + + auto run_bridge_jump = [&](int veh_idx, float start_x, float start_spd, int max_ticks) -> int { + sim::CraftState c; + c.id = 0; + c.vehicle_idx = veh_idx; + c.curr_pose.pos = Vec3(start_x, lvl8.sample_height_world(start_x, 69.5f) + sim::kVehicleSpecs[veh_idx].hover_offset, 69.5f); + c.curr_pose.yaw = jump_yaw; + c.prev_pose = c.curr_pose; + c.vel = Vec3(std::sin(jump_yaw) * start_spd, 0.0f, std::cos(jump_yaw) * start_spd); + c.fuel = c.max_fuel = 100.0f; + + CraftInput in; + in.throttle = 1.0f; + float max_y = c.curr_pose.pos.y; + float min_y_over_gap = 1e6f; + for (int t = 0; t < max_ticks && c.curr_pose.pos.x < 79.0f; ++t) { + sim::step_craft_physics(c, in, lvl8, dt, false); + max_y = std::max(max_y, c.curr_pose.pos.y); + if (c.curr_pose.pos.x >= 68.0f && c.curr_pose.pos.x <= 77.5f) { + min_y_over_gap = std::min(min_y_over_gap, c.curr_pose.pos.y); + } + } + CHECK(c.curr_pose.pos.x >= 78.5f); + CHECK(max_y >= 2.15f); + CHECK(min_y_over_gap >= 1.40f); + return 0; + }; + + for (int v = 0; v < 6; ++v) { + CHECK(run_bridge_jump(v, 56.0f, sim::kVehicleSpecs[v].top_speed, 160) == 0); + } + // Slowest craft (Jugga, v=2) accelerating from dead stop right at wp[43] (65.5, 69.5) + CHECK(run_bridge_jump(2, 65.5f, 0.0f, 180) == 0); + std::cout << "[PASS] Track 8 (Arctic Land) bridge jump clearance verified for all 6 vehicles\n"; + } + + // 13. Non-finite/non-positive dt safety + elevated deck pitch & tunnel ceiling re-clamp + { + assets::LevelData lvl2, lvl8; + CHECK(lvl2.load(vfs, 2)); + CHECK(lvl8.load(vfs, 8)); + + sim::CraftState c; + c.id = 0; + c.vehicle_idx = 0; + const Vec3 start_pos(75.5f, 2.25f, 70.5f); + c.curr_pose.pos = start_pos; + c.prev_pose = c.curr_pose; + c.vel = Vec3(8.0f, 0.0f, 0.0f); + c.fuel = c.max_fuel = 100.0f; + + CraftInput drive; + drive.throttle = 1.0f; + drive.steer = 0.5f; + + sim::step_craft_physics(c, drive, lvl8, 0.0f, true); + CHECK((c.curr_pose.pos - start_pos).len_sq() < 1e-8f); + sim::step_craft_physics(c, drive, lvl8, -1.0f, true); + CHECK((c.curr_pose.pos - start_pos).len_sq() < 1e-8f); + sim::step_craft_physics(c, drive, lvl8, std::numeric_limits::quiet_NaN(), true); + CHECK(std::isfinite(c.curr_pose.pos.x) && std::isfinite(c.curr_pose.pos.y) && std::isfinite(c.curr_pose.pos.z)); + CHECK((c.curr_pose.pos - start_pos).len_sq() < 1e-8f); + + // Elevated bridge deck ride stability & smooth pitch + const float dt = static_cast(FixedStepClock::kFixedDt); + for (int t = 0; t < 5; ++t) { + sim::step_craft_physics(c, drive, lvl8, dt, false); + } + CHECK(std::isfinite(c.curr_pose.pitch) && std::isfinite(c.curr_pose.roll)); + CHECK(c.curr_pose.pos.y >= 1.9f); + + // Tunnel ceiling re-clamp on Level 2 (126.5, 23.5) + float road_y2 = lvl2.sample_height_world(126.5f, 23.5f); + float fy = 0.0f, cy = 1e6f; + lvl2.sample_surface_and_ceiling(126.5f, 23.5f, road_y2 + 0.30f, fy, cy); + CHECK(cy < 1e5f); + sim::CraftState tun; + tun.id = 1; + tun.vehicle_idx = 0; + tun.curr_pose.pos = Vec3(126.5f, cy - 0.10f, 23.5f); + tun.prev_pose = tun.curr_pose; + tun.vel = Vec3(0.0f, 5.0f, 0.0f); + float dummy_imp = 0.0f; + bool dummy_scr = false; + sim::resolve_world_collisions(tun, lvl2, dummy_imp, dummy_scr); + CHECK(tun.curr_pose.pos.y <= cy - 0.45f); + CHECK(tun.vel.y <= 0.0f); + std::cout << "[PASS] Physics dt safety, bridge deck attitude & tunnel ceiling re-clamp verified\n"; + } return 0; } diff --git a/tests/test_render_geom.cpp b/tests/test_render_geom.cpp index 63ce26d..aeefc30 100644 --- a/tests/test_render_geom.cpp +++ b/tests/test_render_geom.cpp @@ -6,6 +6,7 @@ #include "render/world_geometry.hpp" #include "sim/vehicle_defs.hpp" +#include #include #include @@ -165,13 +166,20 @@ int main() { CHECK(check_range(281, 286)); } - // Verify 3D model GPU geometry conversion + // Verify 3D model GPU geometry conversion & TEX0-0 half-texel UV inset assets::ObjectTextureAtlas atlas; CHECK(atlas.load(vfs, pal)); const char* keys[] = {"CAR0-0", "TANK0-0", "JUGGA0-0", "JET0-0", "BIKE0-0", "SKIM0-0", "RECOV0-0"}; for (const char* k : keys) { assets::ModelMesh mesh; CHECK(mesh.load(vfs, std::string("OBJECTS/DATA/") + k + ".DAT", &atlas)); + for (const auto& tri : mesh.triangles) { + if (!tri.textured) continue; + for (int c = 0; c < 3; ++c) { + CHECK(tri.u[c] > 0.0f && tri.u[c] < 1.0f); + CHECK(tri.v_coord[c] > 0.0f && tri.v_coord[c] < 1.0f); + } + } render::ModelGeometry mg = render::build_model_geometry(mesh, pal); CHECK(!mg.verts.empty()); CHECK(mg.indices.size() == mesh.triangles.size() * 3u); @@ -183,6 +191,70 @@ int main() { } } + // Verify Bottom (-Y) overpass diagonal split, TerrainChunk AABBs & update bounds + { + assets::LevelData lvl8; + CHECK(lvl8.load(vfs, 8)); + render::WorldGeometry geo8 = render::build_level_geometry(lvl8); + + // 1. 16x16 TerrainChunk AABBs cover every vertex and sum to terrain_indices + const int gw = assets::kMapWidth - 1; + const int gh = assets::kMapHeight - 1; + const int cs = render::WorldGeometry::kTerrainChunkSize; + const int chunks_x = (gw + cs - 1) / cs; + const int chunks_z = (gh + cs - 1) / cs; + CHECK(geo8.terrain_chunks.size() == static_cast(chunks_x) * static_cast(chunks_z)); + size_t total_chunk_idx = 0; + for (const auto& ch : geo8.terrain_chunks) { + CHECK(ch.index_count > 0); + CHECK(ch.first_index + ch.index_count <= geo8.terrain_indices.size()); + total_chunk_idx += ch.index_count; + for (uint32_t i = 0; i < ch.index_count; ++i) { + uint32_t vi = geo8.terrain_indices[ch.first_index + i]; + const Vec3& p = geo8.terrain_verts[vi].pos; + CHECK(p.x >= ch.min_b.x - 1e-4f && p.x <= ch.max_b.x + 1e-4f); + CHECK(p.y >= ch.min_b.y - 1e-4f && p.y <= ch.max_b.y + 1e-4f); + CHECK(p.z >= ch.min_b.z - 1e-4f && p.z <= ch.max_b.z + 1e-4f); + } + } + CHECK(total_chunk_idx == geo8.terrain_indices.size()); + + // 2. Refresh bounds reflects terrain height changes cleanly + lvl8.cell_mut(75, 70).height = 4096; + render::update_terrain_region(lvl8, 74, 69, 76, 71, geo8.terrain_verts); + render::refresh_terrain_chunk_bounds(geo8, 74, 69, 76, 71); + const auto& updated_chunk = geo8.terrain_chunks[(70 / cs) * chunks_x + (75 / cs)]; + CHECK(updated_chunk.max_b.y >= 2.9f); + + // 3. All Bottom (-Y) column quads split along (00)-(11) diagonal matching Top/Terrain + int bottom_quads = 0; + for (size_t i = 0; i + 5 < geo8.column_indices.size(); i += 6) { + const auto& v0 = geo8.column_verts[geo8.column_indices[i + 0]]; + if (v0.normal.y > -0.9f) continue; + // For our emitted bottom indices {base+3, base+2, base+1, base+3, base+1, base+0}, + // index+0 is p3=(00) and index+2 is p1=(11): shared diagonal has dx*dz > 0.5 + const auto& d0 = geo8.column_verts[geo8.column_indices[i + 0]]; + const auto& d1 = geo8.column_verts[geo8.column_indices[i + 2]]; + CHECK((d1.pos.x - d0.pos.x) * (d1.pos.z - d0.pos.z) > 0.5f); + ++bottom_quads; + } + CHECK(bottom_quads > 0); + + // 4. Synthetic 2x2 sm=0x02 overpass treats center vertex as overpass (ao=0.88), not solid base (0.72) + assets::LevelData syn; + syn.map.resize(assets::kMapWidth * assets::kMapHeight); + syn.columns[1].shape_mask = 0x02u; + syn.columns[1].blocks[1] = 0; + for (int z = 10; z <= 11; ++z) { + for (int x = 10; x <= 11; ++x) { + syn.cell_mut(x, z).tex_or_col = -1; + } + } + render::WorldGeometry geo_syn = render::build_level_geometry(syn); + const size_t v_base = (static_cast(11) * (assets::kMapWidth - 1) + 11) * 4u; + CHECK(std::abs(geo_syn.terrain_verts[v_base].ao - 0.88f) < 1e-4f); + } + std::cout << "[PASS] All 9 Levels & Vehicle 3D Render Geometry validated\n"; return 0; }