diff --git a/apps/server/tuning/ground-ai.jsonc b/apps/server/tuning/ground-ai.jsonc index 9270c1d..723df8f 100644 --- a/apps/server/tuning/ground-ai.jsonc +++ b/apps/server/tuning/ground-ai.jsonc @@ -94,6 +94,14 @@ "ridgeMaxShots": 6 }, + // Offline map baking parameters. These are copied into the generator's per-level POI input. + "coverMap": { + "minCoverHeightM": 1.55, + "peekMinM": 3.5, + "peekMaxM": 6.0, + "retreatMinM": 8.0 + }, + "navigation": { // "vehicle_phys" uses custom inputs with native ownership. "movesys" keeps stock movement. "driveMode": "vehicle_phys", diff --git a/native/wto-nav/wto_nav_format.h b/native/wto-nav/wto_nav_format.h index b955b01..07aa7f5 100644 --- a/native/wto-nav/wto_nav_format.h +++ b/native/wto-nav/wto_nav_format.h @@ -15,6 +15,7 @@ extern "C" { #define WTO_GEO_MAGIC "WTOGEO\0\1" #define WTO_GEO_VERSION 1u +#define WTO_GEO_FLAG_ROAD_MASK 0x01u #define WTO_NAV_MAGIC "WTONAV\0\1" #define WTO_NAV_VERSION 1u @@ -70,7 +71,7 @@ enum WtoCoverKind { typedef struct WtoGeoHeader { char magic[8]; /* WTO_GEO_MAGIC */ uint32_t version; /* WTO_GEO_VERSION */ - uint32_t flags; + uint32_t flags; /* WTO_GEO_FLAG_* */ uint8_t everSha1[20]; /* Built-in SHA-1 from DBLD eVER block */ float waterLevel; /* Level water_level in metres (-1e6 if none) */ float boundsMin[2]; /* World XZ crop min (battle area union + margin) */ @@ -83,7 +84,14 @@ typedef struct WtoGeoHeader { uint32_t obsTriCount; /* Number of obstacle triangles (uint32[3] + uint8 class) */ } WtoGeoHeader; -/* Baked tank cover point (48 bytes). */ +/* Optional trailer after obstacle triangles, followed by size*size uint8 road mask cells. */ +typedef struct WtoGeoRoadMask { + uint32_t size; + float origin[2]; /* World XZ of the first LMp2 cell */ + float cellSize; +} WtoGeoRoadMask; + +/* Baked tank cover point (68 bytes). */ typedef struct WtoCoverPoint { float pos[3]; /* World XYZ parking position behind cover */ float coverDir[2]; /* Unit XZ vector pointing FROM pos TOWARD the blocked threat */ diff --git a/tools/navgen/bake/bake.cpp b/tools/navgen/bake/bake.cpp index 8c1ef07..2dcfb63 100644 --- a/tools/navgen/bake/bake.cpp +++ b/tools/navgen/bake/bake.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include @@ -47,7 +48,15 @@ struct PoiPt { float x, y, z, radius; }; +struct CoverBake { + float minCoverHeightM; + float peekMinM; + float peekMaxM; + float retreatMinM; +}; + struct PoisData { + CoverBake cover{}; std::vector t1Spawns; std::vector t2Spawns; std::vector caps; @@ -74,15 +83,29 @@ static constexpr float kTileWorldSize = kTileSize * kCellSize; static constexpr float kShallowWaterMaxM = 0.60f; static constexpr float kShallowWaterMinM = 0.05f; static constexpr float kRoughSlopeDeg = 18.0f; +static constexpr float kCoverScanM = 5.2f; +static constexpr float kPeekSightM = 14.0f; +static constexpr float kHullDownSightM = 22.0f; +static constexpr float kCoverHeightToleranceM = 1.2f; struct GeoData { WtoGeoHeader hdr{}; std::vector heights; + WtoGeoRoadMask roads{}; + std::vector roadCells; std::vector obsVerts; std::vector obsTris; float minY = 1e9f; float maxY = -1e9f; + bool isRoad(float wx, float wz) const { + if (roadCells.empty()) return false; + float x = (wx - roads.origin[0]) / roads.cellSize; + float z = (wz - roads.origin[1]) / roads.cellSize; + if (x < 0.0f || z < 0.0f || x >= roads.size || z >= roads.size) return false; + return roadCells[(size_t)z * roads.size + (size_t)x] != 0; + } + float sampleHeight(float wx, float wz) const { float fx = (wx - hdr.hmOrigin[0]) / hdr.hmCellSize; float fz = (wz - hdr.hmOrigin[1]) / hdr.hmCellSize; @@ -121,6 +144,15 @@ static bool loadGeo(const std::string &path, GeoData &out) { in.read(reinterpret_cast(&cls), 1); out.obsTris[i] = { idx[0], idx[1], idx[2], cls }; } + if (out.hdr.flags & WTO_GEO_FLAG_ROAD_MASK) { + in.read(reinterpret_cast(&out.roads), sizeof(WtoGeoRoadMask)); + // Same allocation limit as the extractor. + if (!in || out.roads.size == 0 || out.roads.size > 8192 || + !(out.roads.cellSize > 0.0f) || !std::isfinite(out.roads.cellSize) || + !std::isfinite(out.roads.origin[0]) || !std::isfinite(out.roads.origin[1])) return false; + out.roadCells.resize((size_t)out.roads.size * out.roads.size); + in.read(reinterpret_cast(out.roadCells.data()), out.roadCells.size()); + } if (!in) return false; for (float h : out.heights) { @@ -142,6 +174,17 @@ static bool loadGeo(const std::string &path, GeoData &out) { return true; } +static float readJsonNumber(const std::string &json, const char *key, float fallback) { + size_t pos = json.find(std::string("\"") + key + "\""); + if (pos == std::string::npos) return fallback; + pos = json.find(':', pos); + if (pos == std::string::npos) return fallback; + const char *start = json.c_str() + pos + 1; + char *end = nullptr; + float value = std::strtof(start, &end); + return end != start && std::isfinite(value) ? value : fallback; +} + /* Minimal JSON array extractor for `.pois.json` (team1Spawns / team2Spawns / captureZones). */ static void parsePoiArray(const std::string &json, const std::string &key, std::vector &out) { std::string needle = "\"" + key + "\""; @@ -156,14 +199,6 @@ static void parsePoiArray(const std::string &json, const std::string &key, std:: else if (json[i] == ']') { depth--; if (depth == 0) break; } } std::string slice = json.substr(lb, i - lb + 1); - auto readNum = [](const std::string &obj, const char *field, float def) -> float { - std::string fn = std::string("\"") + field + "\""; - size_t p = obj.find(fn); - if (p == std::string::npos) return def; - p = obj.find(':', p); - if (p == std::string::npos) return def; - return std::strtof(obj.c_str() + p + 1, nullptr); - }; auto readStr = [](const std::string &obj, const char *field) -> std::string { std::string fn = std::string("\"") + field + "\""; size_t p = obj.find(fn); @@ -182,10 +217,10 @@ static void parsePoiArray(const std::string &json, const std::string &key, std:: std::string obj = slice.substr(ob, cb - ob + 1); PoiPt pt; pt.name = readStr(obj, "name"); - pt.x = readNum(obj, "x", 0.0f); - pt.y = readNum(obj, "y", 0.0f); - pt.z = readNum(obj, "z", 0.0f); - pt.radius = readNum(obj, "radius", 15.0f); + pt.x = readJsonNumber(obj, "x", 0.0f); + pt.y = readJsonNumber(obj, "y", 0.0f); + pt.z = readJsonNumber(obj, "z", 0.0f); + pt.radius = readJsonNumber(obj, "radius", 15.0f); out.push_back(pt); cur = cb + 1; } @@ -195,6 +230,18 @@ static bool loadPois(const std::string &path, PoisData &out) { std::ifstream in(path); if (!in) return false; std::string content((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + out.cover = { + readJsonNumber(content, "minCoverHeightM", -1.0f), + readJsonNumber(content, "peekMinM", -1.0f), + readJsonNumber(content, "peekMaxM", -1.0f), + readJsonNumber(content, "retreatMinM", -1.0f) + }; + if (out.cover.minCoverHeightM <= 0.0f || out.cover.peekMinM <= 0.0f || + out.cover.peekMaxM < out.cover.peekMinM || out.cover.peekMaxM >= kTileWorldSize || + out.cover.retreatMinM <= 0.0f || out.cover.retreatMinM >= kTileWorldSize) { + std::fprintf(stderr, "Invalid cover baking settings in %s. Regenerate it with mission-bounds.mts.\n", path.c_str()); + return false; + } parsePoiArray(content, "team1Spawns", out.t1Spawns); parsePoiArray(content, "team2Spawns", out.t2Spawns); parsePoiArray(content, "captureZones", out.caps); @@ -254,6 +301,129 @@ static bool hfTraceBand(const rcHeightfield &hardHf, const GeoData &geo, return false; } +static int coverBorderCells(const CoverBake &tuning) { + float reach = std::max(kHullDownSightM, std::hypot(tuning.peekMaxM, kPeekSightM)); + return (int)std::ceil(reach / kCellSize) + 1; +} + +static bool isCoverArea(unsigned char area) { + return area != RC_NULL_AREA && area != WTO_AREA_DEEP_WATER && area != WTO_AREA_SHALLOW_WATER; +} + +static bool isCoverBoundary(const rcCompactHeightfield &field, int x, int z, const rcCompactSpan &span) { + for (int dir = 0; dir < 4; ++dir) { + int connection = rcGetCon(span, dir); + if (connection == RC_NOT_CONNECTED) return true; + int nx = x + rcGetDirOffsetX(dir); + int nz = z + rcGetDirOffsetY(dir); + if (field.areas[field.cells[nx + nz * field.width].index + connection] == RC_NULL_AREA) return true; + } + return false; +} + +static bool findCornerPeek( + const rcCompactHeightfield &field, const rcHeightfield &hard, const GeoData &geo, + const CoverBake &tuning, const WtoCoverPoint &cover, float side, float (&point)[3] +) { + const float dx = cover.coverDir[0], dz = cover.coverDir[1]; + for (float distance = tuning.peekMinM; distance <= tuning.peekMaxM; distance += field.cs) { + const float x = cover.pos[0] - dz * side * distance; + const float z = cover.pos[2] + dx * side * distance; + const int gx = (int)std::floor((x - field.bmin[0]) / field.cs); + const int gz = (int)std::floor((z - field.bmin[2]) / field.cs); + if (gx < 0 || gz < 0 || gx >= field.width || gz >= field.height) break; + + const rcCompactCell &cell = field.cells[gx + gz * field.width]; + for (unsigned int i = cell.index; i < cell.index + cell.count; ++i) { + if (!isCoverArea(field.areas[i])) continue; + float y = field.bmin[1] + field.spans[i].y * field.ch; + if (std::fabs(y - cover.pos[1]) > kCoverHeightToleranceM) continue; + if (hfTraceBand(hard, geo, x, z, dx, dz, kPeekSightM, y + 1.8f, y + 2.6f)) continue; + point[0] = x; + point[1] = y; + point[2] = z; + return true; + } + } + return false; +} + +static void bakeTileCovers( + const rcCompactHeightfield &field, const rcHeightfield &hard, const GeoData &geo, + const rcConfig &cfg, const CoverBake &tuning, std::vector &covers +) { + static const float directions[8][2] = { + { 1.0f, 0.0f }, { 0.70710678f, 0.70710678f }, { 0.0f, 1.0f }, { -0.70710678f, 0.70710678f }, + { -1.0f, 0.0f }, { -0.70710678f, -0.70710678f }, { 0.0f, -1.0f }, { 0.70710678f, -0.70710678f } + }; + const int innerEnd = cfg.borderSize + cfg.tileSize; + for (int z = cfg.borderSize; z < innerEnd; ++z) { + for (int x = cfg.borderSize; x < innerEnd; ++x) { + const rcCompactCell &cell = field.cells[x + z * field.width]; + for (unsigned int i = cell.index; i < cell.index + cell.count; ++i) { + const rcCompactSpan &span = field.spans[i]; + if (!isCoverArea(field.areas[i]) || !isCoverBoundary(field, x, z, span)) continue; + Vec3 pos{ cfg.bmin[0] + (x + 0.5f) * cfg.cs, cfg.bmin[1] + span.y * cfg.ch, + cfg.bmin[2] + (z + 0.5f) * cfg.cs }; + + // Every usable bearing goes through the same checks, including opposite faces of one object. + for (const auto &dir : directions) { + float dx = dir[0], dz = dir[1]; + int hullHits = 0, turretHits = 0; + float totalHeight = 0.0f; + for (int column = -2; column <= 2; ++column) { + float offset = column * 0.9f; // Five samples across a 3.6 m hull. + float sx = pos.x - dz * offset, sz = pos.z + dx * offset; + float top = pos.y; + if (!hfTraceBand(hard, geo, sx, sz, dx, dz, kCoverScanM, pos.y + 0.65f, pos.y + 1.80f, &top)) continue; + ++hullHits; + totalHeight += std::max(0.0f, top - pos.y); + turretHits += hfTraceBand(hard, geo, sx, sz, dx, dz, kCoverScanM, pos.y + 2.05f, pos.y + 2.85f); + } + if (hullHits < 4 || totalHeight < tuning.minCoverHeightM * hullHits) continue; + + float width = 3.6f; + for (float off : { -2.6f, 2.6f }) { + if (hfTraceBand(hard, geo, pos.x - dz * off, pos.z + dx * off, dx, dz, + kCoverScanM, pos.y + 0.65f, pos.y + 1.80f)) width += 1.0f; + } + WtoCoverPoint cover{}; + cover.pos[0] = pos.x; cover.pos[1] = pos.y; cover.pos[2] = pos.z; + cover.coverDir[0] = dx; cover.coverDir[1] = dz; + cover.halfAngleDeg = width >= 5.0f ? 42.0f : 32.0f; + cover.heightM = totalHeight / hullHits; + cover.widthM = width; + + if (turretHits >= 3) { + cover.kind = WTO_COVER_FULL; + cover.hasPeekLeft = findCornerPeek(field, hard, geo, tuning, cover, -1.0f, cover.peekLeft); + cover.hasPeekRight = findCornerPeek(field, hard, geo, tuning, cover, 1.0f, cover.peekRight); + } else { + if (hfTraceBand(hard, geo, pos.x, pos.z, dx, dz, kHullDownSightM, pos.y + 2.15f, pos.y + 2.75f)) continue; + cover.kind = WTO_COVER_HULLDOWN; + } + covers.push_back(cover); + } + } + } + } +} + +static void markRoadAreas(rcCompactHeightfield &field, const GeoData &geo) { + if (geo.roadCells.empty()) return; + for (int z = 0; z < field.height; ++z) { + const float wz = field.bmin[2] + (z + 0.5f) * field.cs; + for (int x = 0; x < field.width; ++x) { + const float wx = field.bmin[0] + (x + 0.5f) * field.cs; + if (!geo.isRoad(wx, wz)) continue; + const rcCompactCell &cell = field.cells[x + z * field.width]; + for (unsigned int i = cell.index; i < cell.index + cell.count; ++i) { + if (field.areas[i] == WTO_AREA_GROUND) field.areas[i] = WTO_AREA_ROAD; + } + } + } +} + struct BuiltTile { int tx = 0; int tz = 0; @@ -272,7 +442,7 @@ static TileBakeResult buildSingleTile( const TierSpec &tier, int tx, int tz, float mapMinX, float mapMinZ, - bool bakeCovers + const CoverBake &coverTuning, bool bakeCovers ) { TileBakeResult res; res.tile.tx = tx; @@ -293,6 +463,8 @@ static TileBakeResult buildSingleTile( cfg.maxVertsPerPoly = 6; cfg.tileSize = kTileSize; cfg.borderSize = cfg.walkableRadius + 3; + // Cover and corner rays must see hard collision on the other side of tile boundaries. + if (bakeCovers) cfg.borderSize = std::max(cfg.borderSize, coverBorderCells(coverTuning)); cfg.width = cfg.tileSize + cfg.borderSize * 2; cfg.height = cfg.tileSize + cfg.borderSize * 2; cfg.detailSampleDist = 12.0f * cfg.cs; @@ -442,139 +614,14 @@ static TileBakeResult buildSingleTile( } } - /* 3. Bake tank-qualified covers directly from eroded Tier-1 walkable boundary + hardHf */ - if (bakeCovers && hardHf) { - const int b = cfg.borderSize; - const int innerEnd = b + cfg.tileSize; - static const float kDirs[8][2] = { - { 1.0f, 0.0f }, { 0.7071f, 0.7071f }, { 0.0f, 1.0f }, { -0.7071f, 0.7071f }, - { -1.0f, 0.0f }, { -0.7071f, -0.7071f }, { 0.0f, -1.0f }, { 0.7071f, -0.7071f } - }; - for (int z = b; z < innerEnd; z += 4) { - for (int x = b; x < innerEnd; x += 4) { - const rcCompactCell &c = chf->cells[x + z * chf->width]; - for (int si = (int)c.index, ni = (int)(c.index + c.count); si < ni; ++si) { - unsigned char area = chf->areas[si]; - if (area == RC_NULL_AREA || area == WTO_AREA_DEEP_WATER || area == WTO_AREA_SHALLOW_WATER) continue; - /* Check if any 4-neighbor (at distance 1..2 cells) was eroded to RC_NULL_AREA or disconnected */ - const rcCompactSpan &s = chf->spans[si]; - bool isBoundary = false; - for (int d = 0; d < 4; ++d) { - int con = rcGetCon(s, d); - if (con == RC_NOT_CONNECTED) { isBoundary = true; break; } - int nx = x + rcGetDirOffsetX(d); - int nz = z + rcGetDirOffsetY(d); - int nsi = (int)chf->cells[nx + nz * chf->width].index + con; - if (chf->areas[nsi] == RC_NULL_AREA) { isBoundary = true; break; } - } - if (!isBoundary) continue; - - float wx = cfg.bmin[0] + (x + 0.5f) * cfg.cs; - float wy = cfg.bmin[1] + s.y * cfg.ch; - float wz = cfg.bmin[2] + (z + 0.5f) * cfg.cs; - - /* Find strongest hard-obstacle direction within 2.0..5.2 m */ - int bestDir = -1; - float bestWidth = 0.0f; - float bestHeight = 0.0f; - bool bestTurretBlocked = false; - - for (int di = 0; di < 8; ++di) { - float dx = kDirs[di][0], dz = kDirs[di][1]; - float px = -dz, pz = dx; /* tangent */ - int hullHits = 0; - int turretHits = 0; - float hSum = 0.0f; - /* 5 lateral samples across 3.6 m hull width (-1.8, -0.9, 0, +0.9, +1.8) */ - for (int li = -2; li <= 2; ++li) { - float off = li * 0.9f; - float sx = wx + px * off; - float sz = wz + pz * off; - float topY = wy; - if (hfTraceBand(*hardHf, geo, sx, sz, dx, dz, 5.2f, wy + 0.65f, wy + 1.80f, &topY)) { - hullHits++; - hSum += std::max(0.0f, topY - wy); - if (hfTraceBand(*hardHf, geo, sx, sz, dx, dz, 5.2f, wy + 2.05f, wy + 2.85f)) { - turretHits++; - } - } - } - if (hullHits < 4) continue; /* Require >= 80% hull width blocked (eliminates thin posts & narrow rocks) */ - float avgH = hSum / (float)hullHits; - if (avgH < 1.55f) continue; /* Eliminate low rocks (< 1.55 m) */ - - /* Check extra lateral span for continuous obstacle width */ - float wMeters = 3.6f; - if (hfTraceBand(*hardHf, geo, wx + px * 2.6f, wz + pz * 2.6f, dx, dz, 5.2f, wy + 0.65f, wy + 1.80f)) wMeters += 1.0f; - if (hfTraceBand(*hardHf, geo, wx - px * 2.6f, wz - pz * 2.6f, dx, dz, 5.2f, wy + 0.65f, wy + 1.80f)) wMeters += 1.0f; - - if (wMeters > bestWidth || (wMeters == bestWidth && avgH > bestHeight)) { - bestDir = di; - bestWidth = wMeters; - bestHeight = avgH; - bestTurretBlocked = (turretHits >= 3); - } - } - - if (bestDir < 0) continue; - float dx = kDirs[bestDir][0], dz = kDirs[bestDir][1]; - float px = -dz, pz = dx; - - WtoCoverPoint cp{}; - cp.pos[0] = wx; cp.pos[1] = wy; cp.pos[2] = wz; - cp.coverDir[0] = dx; cp.coverDir[1] = dz; - cp.retreatDir[0] = -dx; cp.retreatDir[1] = -dz; - cp.halfAngleDeg = bestWidth >= 5.0f ? 42.0f : 32.0f; - cp.heightM = bestHeight; - cp.widthM = bestWidth; - - if (bestTurretBlocked) { - cp.kind = WTO_COVER_FULL; - /* Probe corner peek left/right at 4.2 m */ - for (int side = -1; side <= 1; side += 2) { - float kx = wx + px * (side * 4.2f); - float kz = wz + pz * (side * 4.2f); - int kgx = (int)std::floor((kx - cfg.bmin[0]) / cfg.cs); - int kgz = (int)std::floor((kz - cfg.bmin[2]) / cfg.cs); - if (kgx >= 0 && kgz >= 0 && kgx < chf->width && kgz < chf->height) { - const rcCompactCell &kc = chf->cells[kgx + kgz * chf->width]; - bool walkablePeek = false; - float ky = wy; - for (int ksi = (int)kc.index, kni = (int)(kc.index + kc.count); ksi < kni; ++ksi) { - if (chf->areas[ksi] != RC_NULL_AREA && chf->areas[ksi] != WTO_AREA_DEEP_WATER) { - float sy = cfg.bmin[1] + chf->spans[ksi].y * cfg.ch; - if (std::fabs(sy - wy) <= 1.2f) { walkablePeek = true; ky = sy; break; } - } - } - if (walkablePeek && !hfTraceBand(*hardHf, geo, kx, kz, dx, dz, 14.0f, ky + 1.8f, ky + 2.6f)) { - if (side < 0) { - cp.hasPeekLeft = 1; - cp.peekLeft[0] = kx; cp.peekLeft[1] = ky; cp.peekLeft[2] = kz; - } else { - cp.hasPeekRight = 1; - cp.peekRight[0] = kx; cp.peekRight[1] = ky; cp.peekRight[2] = kz; - } - } - } - } - res.covers.push_back(cp); - } else { - /* Hull-down candidate: verify forward 22 m clear at turret height */ - if (!hfTraceBand(*hardHf, geo, wx, wz, dx, dz, 22.0f, wy + 2.15f, wy + 2.75f)) { - cp.kind = WTO_COVER_HULLDOWN; - res.covers.push_back(cp); - } - } - } - } - } - } + if (hardHf) bakeTileCovers(*chf, *hardHf, geo, cfg, coverTuning, res.covers); rcFreeHeightField(hardHf); hardHf = nullptr; /* Smooth isolated single-voxel slope/area noise slivers before region building */ rcMedianFilterWalkableArea(&ctx, *chf); rcMedianFilterWalkableArea(&ctx, *chf); + markRoadAreas(*chf, geo); if (!rcBuildDistanceField(&ctx, *chf) || !rcBuildRegions(&ctx, *chf, cfg.borderSize, cfg.minRegionArea, cfg.mergeRegionArea)) { @@ -771,74 +818,89 @@ static void markChokepoints(dtNavMesh *mesh, dtNavMeshQuery *query, float chokeD } } +static dtPolyRef verifyCoverPosition(dtNavMeshQuery &query, const dtQueryFilter &filter, float (&point)[3]) { + const float extent[3] = { kCellSize, kCoverHeightToleranceM, kCellSize }; + dtPolyRef ref = 0; + float nearest[3]; + bool overPoly = false; + if (dtStatusFailed(query.findNearestPoly(point, extent, &filter, &ref, nearest, &overPoly)) || + !ref || !overPoly || std::fabs(nearest[1] - point[1]) > kCoverHeightToleranceM) return 0; + point[1] = nearest[1]; // Keep the XZ from the collision probe. + return ref; +} + +static bool clearCoverCorridor(dtNavMeshQuery &query, const dtQueryFilter &filter, + dtPolyRef startRef, const float *start, const float *end, dtPolyRef endRef = 0) { + float fraction = 0.0f, normal[3]; + dtPolyRef trail[32]; + int count = 0; + dtStatus status = query.raycast(startRef, start, end, &filter, &fraction, normal, trail, &count, 32); + return dtStatusSucceed(status) && !dtStatusDetail(status, DT_BUFFER_TOO_SMALL) && + fraction >= 1.0f && (!endRef || (count > 0 && trail[count - 1] == endRef)); +} + +static bool verifyCover(WtoCoverPoint &cover, dtNavMeshQuery &query, + const dtQueryFilter &filter, float retreatMinM) { + dtPolyRef startRef = verifyCoverPosition(query, filter, cover.pos); + if (!startRef) return false; + + const float heading = std::atan2(-cover.coverDir[1], -cover.coverDir[0]); + bool hasRetreat = false; + for (float offset : { 0.0f, 0.45f, -0.45f }) { + float rx = std::cos(heading + offset), rz = std::sin(heading + offset); + float end[3] = { cover.pos[0] + rx * retreatMinM, cover.pos[1], cover.pos[2] + rz * retreatMinM }; + if (!clearCoverCorridor(query, filter, startRef, cover.pos, end)) continue; + cover.retreatDir[0] = rx; + cover.retreatDir[1] = rz; + hasRetreat = true; + break; + } + if (!hasRetreat) return false; + + auto validatePeek = [&](float (&point)[3]) { + dtPolyRef endRef = verifyCoverPosition(query, filter, point); + return endRef && clearCoverCorridor(query, filter, startRef, cover.pos, point, endRef); + }; + cover.hasPeekLeft = cover.hasPeekLeft && validatePeek(cover.peekLeft); + cover.hasPeekRight = cover.hasPeekRight && validatePeek(cover.peekRight); + return true; +} + +static unsigned int peekCount(const WtoCoverPoint &cover) { + return cover.hasPeekLeft + cover.hasPeekRight; +} + static std::vector filterAndDedupeCovers( - const std::vector &raw, - dtNavMeshQuery *q1 + const std::vector &raw, dtNavMeshQuery &query, const CoverBake &tuning ) { dtQueryFilter filter; filter.setIncludeFlags(WTO_FLAG_WALK); filter.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED); - const float ext[3] = { 3.0f, 4.0f, 3.0f }; + std::vector usable; + for (WtoCoverPoint cover : raw) { + if (verifyCover(cover, query, filter, tuning.retreatMinM)) usable.push_back(cover); + } - /* Sort by quality: hulldown & corner-peek full covers first, then wider/taller covers */ - std::vector order(raw.size()); - for (size_t i = 0; i < raw.size(); ++i) order[i] = i; - std::sort(order.begin(), order.end(), [&](size_t a, size_t b) { - auto score = [](const WtoCoverPoint &c) { - float s = c.widthM * 2.0f + std::min(c.heightM, 4.0f); - if (c.kind == WTO_COVER_HULLDOWN) s += 3.0f; - if (c.hasPeekLeft || c.hasPeekRight) s += 2.5f; - return s; + std::sort(usable.begin(), usable.end(), [](const WtoCoverPoint &a, const WtoCoverPoint &b) { + auto rank = [](const WtoCoverPoint &c) { + return std::make_tuple(peekCount(c), c.widthM, c.heightM); }; - return score(raw[a]) > score(raw[b]); + if (rank(a) != rank(b)) return rank(a) > rank(b); + return std::tie(a.pos[0], a.pos[1], a.pos[2], a.coverDir[0], a.coverDir[1]) < + std::tie(b.pos[0], b.pos[1], b.pos[2], b.coverDir[0], b.coverDir[1]); }); std::vector kept; - kept.reserve(2048); - static const float kRetreatAngles[3] = { 0.0f, 0.45f, -0.45f }; - - for (size_t idx : order) { - WtoCoverPoint cp = raw[idx]; - bool dup = false; - for (const auto &k : kept) { - float dx = k.pos[0] - cp.pos[0]; - float dz = k.pos[2] - cp.pos[2]; - if (dx * dx + dz * dz < 49.0f) { /* 7 m dedupe radius */ - float dot = k.coverDir[0] * cp.coverDir[0] + k.coverDir[1] * cp.coverDir[1]; - if (dot > 0.78f && k.kind == cp.kind) { dup = true; break; } - } - } - if (dup) continue; - - /* Verify parking spot is on T1 navmesh and has >= 8 m safe retreat corridor */ - dtPolyRef startRef = 0; - float nearest[3]; - if (dtStatusFailed(q1->findNearestPoly(cp.pos, ext, &filter, &startRef, nearest)) || !startRef) continue; - float snapSq = (nearest[0] - cp.pos[0]) * (nearest[0] - cp.pos[0]) + (nearest[2] - cp.pos[2]) * (nearest[2] - cp.pos[2]); - if (snapSq > 9.0f) continue; - cp.pos[0] = nearest[0]; cp.pos[1] = nearest[1]; cp.pos[2] = nearest[2]; - - bool retreatOk = false; - float baseAng = std::atan2(-cp.coverDir[1], -cp.coverDir[0]); - for (float da : kRetreatAngles) { - float rx = std::cos(baseAng + da); - float rz = std::sin(baseAng + da); - float endPt[3] = { cp.pos[0] + rx * 8.5f, cp.pos[1], cp.pos[2] + rz * 8.5f }; - float t = 0.0f; - float hitNorm[3]; - dtPolyRef polys[32]; - int npolys = 0; - if (dtStatusSucceed(q1->raycast(startRef, cp.pos, endPt, &filter, &t, hitNorm, polys, &npolys, 32))) { - if (t >= 0.92f) { - cp.retreatDir[0] = rx; - cp.retreatDir[1] = rz; - retreatOk = true; - break; - } - } - } - if (!retreatOk) continue; - kept.push_back(cp); + const float maxLevelDifference = kTiers[WTO_NAV_TIER_STANDARD].maxClimb; + for (const auto &cover : usable) { + bool duplicate = std::any_of(kept.begin(), kept.end(), [&](const WtoCoverPoint &other) { + if (cover.kind != other.kind || std::fabs(cover.pos[1] - other.pos[1]) > maxLevelDifference) return false; + float dx = other.pos[0] - cover.pos[0], dz = other.pos[2] - cover.pos[2]; + float dot = other.coverDir[0] * cover.coverDir[0] + other.coverDir[1] * cover.coverDir[1]; + // Adjacent samples facing the same way are redundant. Perpendicular and opposite faces remain usable. + return dx * dx + dz * dz < 49.0f && dot > 0.78f; + }); + if (!duplicate) kept.push_back(cover); } return kept; } @@ -895,7 +957,7 @@ int main(int argc, char **argv) { geoPath.c_str(), mapMaxX - mapMinX, mapMaxZ - mapMinZ, tilesX, tilesZ, totalTiles, geo.hdr.obsTriCount); /* Bucket obstacle triangles once into overlapping tiles */ - const float pad = 4.5f; + const float pad = coverBorderCells(pois.cover) * kCellSize; std::vector> buckets((size_t)totalTiles); for (uint32_t ti = 0; ti < geo.hdr.obsTriCount; ++ti) { const auto &t = geo.obsTris[ti]; @@ -950,7 +1012,7 @@ int main(int argc, char **argv) { if (idx >= totalTiles) break; int tx = idx % tilesX; int tz = idx / tilesX; - auto br = buildSingleTile(geo, buckets[(size_t)idx], kTiers[tierIdx], tx, tz, mapMinX, mapMinZ, doCovers); + auto br = buildSingleTile(geo, buckets[(size_t)idx], kTiers[tierIdx], tx, tz, mapMinX, mapMinZ, pois.cover, doCovers); tierTiles[tierIdx][(size_t)idx] = br.tile; if (doCovers && !br.covers.empty()) { localCov.insert(localCov.end(), br.covers.begin(), br.covers.end()); @@ -984,14 +1046,15 @@ int main(int argc, char **argv) { } /* Dedupe + retreat-verify tank covers on Tier 1 */ - std::vector covers = filterAndDedupeCovers(rawCovers, queries[WTO_NAV_TIER_STANDARD]); - int fullCnt = 0, hdCnt = 0, peekCnt = 0; + std::vector covers = filterAndDedupeCovers(rawCovers, *queries[WTO_NAV_TIER_STANDARD], pois.cover); + int fullCnt = 0, hdCnt = 0, peekCnt = 0, bothPeeks = 0; for (const auto &c : covers) { if (c.kind == WTO_COVER_FULL) fullCnt++; else hdCnt++; - if (c.hasPeekLeft || c.hasPeekRight) peekCnt++; + if (peekCount(c) > 0) peekCnt++; + if (peekCount(c) == 2) bothPeeks++; } - std::printf(" Covers: raw=%zu -> verified=%zu (full=%d, hulldown=%d, withPeek=%d)\n", - rawCovers.size(), covers.size(), fullCnt, hdCnt, peekCnt); + std::printf(" Covers: raw=%zu -> verified=%zu (full=%d, hulldown=%d, withPeek=%d, bothPeeks=%d)\n", + rawCovers.size(), covers.size(), fullCnt, hdCnt, peekCnt, bothPeeks); /* Build 8m tactical grid (clearance + simple terrain-horizon exposure) */ const float tacCellM = 8.0f; @@ -1165,12 +1228,12 @@ int main(int argc, char **argv) { if (!outPreviewPath.empty()) { const uint32_t pw = 1024, ph = 1024; std::vector pHeight((size_t)pw * ph); - std::vector pFlags((size_t)pw * ph, 0); + std::vector pFlags((size_t)pw * ph, 0); /* Bit 0: T0 walkable, Bit 1: T1 walkable, Bit 2: T2 walkable, Bit 3: shallow water, - * Bit 4: deep water, Bit 5: chokepoint, Bit 6: crushable/forest, Bit 7: bridge */ + * Bit 4: deep water, Bit 5: chokepoint, Bit 6: crushable/forest, Bit 7: bridge, Bit 8: road */ dtQueryFilter anyF; anyF.setIncludeFlags(0xFFFF); - anyF.setExcludeFlags(0); + anyF.setExcludeFlags(WTO_FLAG_BLOCKED); const float ext[3] = { 0.8f, 6.0f, 0.8f }; std::atomic nextRow{ 0 }; @@ -1190,7 +1253,7 @@ int main(int argc, char **argv) { float wx = mapMinX + ((rx + 0.5f) / pw) * (mapMaxX - mapMinX); float gy = geo.sampleHeight(wx, wz); pHeight[(size_t)rz * pw + rx] = gy; - uint8_t fl = 0; + uint16_t fl = 0; float pt[3] = { wx, gy, wz }; for (uint32_t ti = 0; ti < WTO_NAV_TIER_COUNT; ++ti) { dtPolyRef ref = 0; @@ -1208,6 +1271,7 @@ int main(int argc, char **argv) { else if (area == WTO_AREA_CHOKEPOINT) fl |= 32; else if (area == WTO_AREA_CRUSHABLE || area == WTO_AREA_FOREST) fl |= 64; else if (area == WTO_AREA_BRIDGE) fl |= 128; + else if (area == WTO_AREA_ROAD) fl |= 256; } } } @@ -1222,7 +1286,7 @@ int main(int argc, char **argv) { for (auto &th : pWorkers) th.join(); std::ofstream pout(outPreviewPath, std::ios::binary); - pout.write("WTOPREV1", 8); + pout.write("WTOPREV2", 8); pout.write(reinterpret_cast(&pw), 4); pout.write(reinterpret_cast(&ph), 4); pout.write(reinterpret_cast(&mapMinX), 4); @@ -1231,7 +1295,7 @@ int main(int argc, char **argv) { pout.write(reinterpret_cast(&mapMaxZ), 4); pout.write(reinterpret_cast(&geo.hdr.waterLevel), 4); pout.write(reinterpret_cast(pHeight.data()), pHeight.size() * sizeof(float)); - pout.write(reinterpret_cast(pFlags.data()), pFlags.size()); + pout.write(reinterpret_cast(pFlags.data()), pFlags.size() * sizeof(uint16_t)); uint32_t cCnt = (uint32_t)covers.size(); pout.write(reinterpret_cast(&cCnt), 4); if (cCnt > 0) pout.write(reinterpret_cast(covers.data()), cCnt * sizeof(WtoCoverPoint)); diff --git a/tools/navgen/extract/Cargo.lock b/tools/navgen/extract/Cargo.lock index 6361db0..1d86e87 100644 --- a/tools/navgen/extract/Cargo.lock +++ b/tools/navgen/extract/Cargo.lock @@ -515,6 +515,8 @@ name = "wto-navgen-extract" version = "0.1.0" dependencies = [ "anyhow", + "lztans", + "ruzstd", "serde", "serde_json", "wt-formats", diff --git a/tools/navgen/extract/Cargo.toml b/tools/navgen/extract/Cargo.toml index 204ac04..68fd0df 100644 --- a/tools/navgen/extract/Cargo.toml +++ b/tools/navgen/extract/Cargo.toml @@ -6,6 +6,8 @@ description = "Offline Dagor level geometry and collision extractor for WTOfflin [dependencies] anyhow = "1" +lztans = "0.1.1" +ruzstd = "0.8" serde = { version = "1", features = ["derive"] } serde_json = "1" wt-formats = "0.1.0" diff --git a/tools/navgen/extract/src/main.rs b/tools/navgen/extract/src/main.rs index 8d51c1f..b10bf11 100644 --- a/tools/navgen/extract/src/main.rs +++ b/tools/navgen/extract/src/main.rs @@ -13,8 +13,11 @@ use wt_unpack::level::{Heightmap, Level}; use wt_unpack::rendinst::ResourceIndex; use wt_unpack::vromfs::Vromfs; +mod phys_map; + const WTO_GEO_MAGIC: &[u8; 8] = b"WTOGEO\0\x01"; const WTO_GEO_VERSION: u32 = 1; +const WTO_GEO_FLAG_ROAD_MASK: u32 = 1; const OBS_HARD_SOLID: u8 = 0; const OBS_BRIDGE_DECK: u8 = 1; @@ -372,17 +375,7 @@ fn main() -> Result<()> { let aces_meta = read_aces_meta(&game_dir, &pois.level); let water_level = aces_meta.water_level; - if let Some(pm) = level.phys_map_info()? { - println!( - " LMp2: {}x{} scale={:.2}m origin=({:.0},{:.0}) mats={:?}", - pm.size[0], - pm.size[1], - pm.metres_per_texel, - pm.world_origin[0], - pm.world_origin[1], - &pm.materials[..pm.materials.len().min(10)] - ); - } + let roads = phys_map::RoadMask::read(&level).with_context(|| format!("extracting {} roads", pois.level))?; let hm = level.heightmap()?.with_context(|| format!("{} has no HM2 heightmap", pois.level))?; let (cw, ch, crop_origin, heights) = crop_heightmap( @@ -512,7 +505,8 @@ fn main() -> Result<()> { // WtoGeoHeader (must match native/wto-nav/wto_nav_format.h byte-for-byte) w.write_all(WTO_GEO_MAGIC)?; w.write_all(&WTO_GEO_VERSION.to_le_bytes())?; - w.write_all(&0u32.to_le_bytes())?; // flags + let flags = if roads.is_some() { WTO_GEO_FLAG_ROAD_MASK } else { 0 }; + w.write_all(&flags.to_le_bytes())?; w.write_all(&ever_sha1)?; w.write_all(&water_level.to_le_bytes())?; w.write_all(&crop_origin[0].to_le_bytes())?; @@ -544,6 +538,9 @@ fn main() -> Result<()> { w.write_all(&idx[2].to_le_bytes())?; w.write_all(&[*cls])?; } + if let Some(roads) = roads { + roads.write(&mut w)?; + } w.flush()?; println!(" wrote {} ({:.1} MB)", out_path.display(), fs::metadata(&out_path)?.len() as f64 / (1024.0 * 1024.0)); Ok(()) diff --git a/tools/navgen/extract/src/phys_map.rs b/tools/navgen/extract/src/phys_map.rs new file mode 100644 index 0000000..2e127e0 --- /dev/null +++ b/tools/navgen/extract/src/phys_map.rs @@ -0,0 +1,318 @@ +use std::io::{Read, Write}; + +use anyhow::{bail, ensure, Context, Result}; +use wt_unpack::bytes::Reader; +use wt_unpack::level::Level; + +// Dagor's physMapLoad.cpp and treeBitmap.cpp define the LMp2 block and its bitmap. +const MIP_SIZE: usize = 16; +const MASK_TEXTURE_SIZE: usize = 32; +const MAX_PAYLOAD: usize = 256 * 1024 * 1024; +const MAX_GRID_CELLS: usize = 64 * 1024 * 1024; + +pub struct RoadMask { + size: usize, + origin: [f32; 2], + cell_size: f32, + cells: Vec, +} + +impl RoadMask { + pub fn read(level: &Level<'_>) -> Result> { + let Some(info) = level.phys_map_info()? else { + return Ok(None); + }; + if info.size == [0, 0] { + return Ok(None); + } + let size = info.size[0] as usize; + ensure!( + info.size[0] == info.size[1] && size.is_power_of_two() && size * size <= MAX_GRID_CELLS, + "unsupported LMp2 bitmap size {:?}", + info.size + ); + ensure!( + info.metres_per_texel.is_finite() && info.metres_per_texel > 0.0 + && info.world_origin.iter().all(|p| p.is_finite()), + "invalid LMp2 world transform" + ); + + let is_road: Vec<_> = info + .materials + .iter() + .map(|name| { + matches!( + name.to_ascii_lowercase().as_str(), + "road" | "roadsoil" | "roadsand" | "roadsnow" | "roadmud" + ) + }) + .collect(); + if !is_road.contains(&true) { + return Ok(None); + } + + let block = level.find("LMp2").context("missing LMp2 block")?; + let mut reader = Reader::at(block.data, 8)?; + for _ in &info.materials { + let len = reader.u32()? as usize; + reader.skip(len.next_multiple_of(4))?; + } + let legacy_size = if info.version == 0 { + let width = reader.u32()? as usize; + let height = reader.u32()? as usize; + reader.skip(3 * 4)?; + ensure!(width == height && width.is_power_of_two(), "invalid LMp2 level-1 bitmap size"); + Some(width) + } else { + None + }; + reader.skip(5 * 4)?; // Dimensions, world origin and metres per texel. + let block_header = reader.u32()?; + let packed = reader.bytes((block_header & 0x3fff_ffff) as usize)?; + let payload = unpack(block_header >> 30, packed)?; + let mut reader = Reader::new(&payload); + if let Some(size) = legacy_size { + read_tree(&mut reader, None, &is_road, [0, 0], size)?; + } + + let mut mask = Self { + size, + origin: info.world_origin, + cell_size: info.metres_per_texel, + cells: vec![0; size * size], + }; + read_tree(&mut reader, Some(&mut mask), &is_road, [0, 0], size)?; + let decals = read_decals(&mut reader, info.version)?; + let textures = if info.version == 0 { + &[][..] + } else { + let count = usize::from(reader.u16()?); + reader.bytes(count * MASK_TEXTURE_SIZE * size_of::())? + }; + for decal in &decals { + for group in &decal.groups { + let texture_bytes = MASK_TEXTURE_SIZE * size_of::(); + let start = usize::from(group.texture_id) * texture_bytes; + let texture = textures.get(start..start + texture_bytes); + let road = material_is_road(&is_road, group.material); + for (index, face) in group.faces.chunks_exact(6).enumerate() { + let vertices = indexed_points(face, &decal.vertices)?; + let uvs = texture + .map(|_| indexed_points(&group.uv_faces[index * 6..index * 6 + 6], &decal.uvs)) + .transpose()?; + mask.paint_triangle(vertices, road, texture.zip(uvs)); + } + } + } + let roads = mask.cells.iter().filter(|&&cell| cell != 0).count(); + println!(" LMp2: {size}x{size} at {:.2} m, {roads} road texels", mask.cell_size); + Ok(Some(mask)) + } + + pub fn write(&self, out: &mut impl Write) -> std::io::Result<()> { + out.write_all(&(self.size as u32).to_le_bytes())?; + out.write_all(&self.origin[0].to_le_bytes())?; + out.write_all(&self.origin[1].to_le_bytes())?; + out.write_all(&self.cell_size.to_le_bytes())?; + out.write_all(&self.cells) + } + + fn fill(&mut self, [x, z]: [usize; 2], size: usize, road: u8) { + for row in z..z + size { + let start = row * self.size + x; + self.cells[start..start + size].fill(road); + } + } + + fn paint_triangle( + &mut self, + vertices: [[f32; 2]; 3], + road: u8, + mask: Option<(&[u8], [[f32; 2]; 3])>, + ) { + let [a, b, c] = vertices.map(|[x, z]| { + [(x - self.origin[0]) / self.cell_size, (z - self.origin[1]) / self.cell_size] + }); + let area = edge(a, b, c); + if !area.is_finite() || area.abs() <= f32::EPSILON { + return; + } + let x0 = a[0].min(b[0]).min(c[0]).floor() as usize; + let x1 = (a[0].max(b[0]).max(c[0]).ceil() as usize).min(self.size); + let z0 = a[1].min(b[1]).min(c[1]).floor() as usize; + let z1 = (a[1].max(b[1]).max(c[1]).ceil() as usize).min(self.size); + for z in z0..z1 { + for x in x0..x1 { + let p = [x as f32 + 0.5, z as f32 + 0.5]; + let weights = [edge(b, c, p) / area, edge(c, a, p) / area, edge(a, b, p) / area]; + if weights.iter().all(|weight| *weight >= 0.0) + && mask.is_none_or(|(tex, uv)| mask_covers(tex, uv, weights)) + { + self.cells[z * self.size + x] = road; + } + } + } + } +} + +fn unpack(codec: u32, packed: &[u8]) -> Result> { + match codec { + 1 => { + let decoder = ruzstd::decoding::StreamingDecoder::new(packed).context("LMp2 zstd header")?; + let mut bytes = Vec::new(); + decoder.take(MAX_PAYLOAD as u64 + 1).read_to_end(&mut bytes)?; + ensure!(bytes.len() <= MAX_PAYLOAD, "LMp2 zstd payload is too large"); + Ok(bytes) + } + 2 => { + let mut reader = Reader::new(packed); + let size = reader.u32()? as usize; + ensure!(size <= MAX_PAYLOAD, "LMp2 Oodle payload is too large"); + let mut bytes = vec![0; size]; + lztans::decode(reader.rest(), &mut bytes) + .map_err(|err| anyhow::anyhow!("LMp2 Oodle decode: {err:?}"))?; + Ok(bytes) + } + _ => bail!("unsupported LMp2 block codec {codec}"), + } +} + +fn read_tree( + reader: &mut Reader<'_>, + mut mask: Option<&mut RoadMask>, + is_road: &[bool], + origin: [usize; 2], + size: usize, +) -> Result<()> { + let flags = reader.u8()?; + if reader.u8()? == 0 { + if let Some(mask) = mask { + mask.fill(origin, size, material_is_road(is_road, flags)); + } + return Ok(()); + } + if flags & 0x80 != 0 { + let shift = u32::from(flags & 0x7f) + 1; + ensure!(shift <= size.ilog2(), "invalid LMp2 bitmap subdivision"); + let stride = 1 << shift; + let child_size = size / stride; + for z in 0..stride { + for x in 0..stride { + let child = [origin[0] + x * child_size, origin[1] + z * child_size]; + read_tree(reader, mask.as_deref_mut(), is_road, child, child_size)?; + } + } + return Ok(()); + } + + let mip = (flags & 0x70) >> 4; + ensure!((1..=4).contains(&mip), "invalid LMp2 bitmap mip"); + let texel = 1 << (mip - 1); + ensure!(size == MIP_SIZE * texel || mask.is_none(), "LMp2 bitmap leaf size mismatch"); + let bits = match flags & 0x0c { + 0x04 => 1, + 0x08 => 2, + 0 => 8, + _ => bail!("invalid LMp2 bitmap palette"), + }; + let palette_len = if bits < 8 { 1 << bits } else { 0 }; + let palette = reader.bytes(palette_len)?; + let data = reader.bytes(MIP_SIZE * MIP_SIZE * bits / 8)?; + if let Some(mask) = mask { + for z in 0..MIP_SIZE { + for x in 0..MIP_SIZE { + let bit = (z * MIP_SIZE + x) * bits; + let value = (usize::from(data[bit / 8]) >> (bit % 8)) & ((1 << bits) - 1); + let material = if palette.is_empty() { value as u8 } else { palette[value] }; + mask.fill( + [origin[0] + x * texel, origin[1] + z * texel], + texel, + material_is_road(is_road, material), + ); + } + } + } + Ok(()) +} + +struct Decal<'a> { + vertices: Vec<[f32; 2]>, + uvs: Vec<[f32; 2]>, + groups: Vec>, +} + +struct DecalFaces<'a> { + material: u8, + faces: &'a [u8], + texture_id: u16, + uv_faces: &'a [u8], +} + +fn read_points(reader: &mut Reader<'_>) -> Result> { + let count = usize::from(reader.u16()?); + (0..count) + .map(|_| { + let point = [reader.f32()?, reader.f32()?]; + ensure!(point.iter().all(|v| v.is_finite()), "non-finite LMp2 decal vertex"); + Ok(point) + }) + .collect() +} + +fn read_decals<'a>(reader: &mut Reader<'a>, version: u32) -> Result>> { + let count = reader.u16()?; + let mut decals = Vec::new(); + for _ in 0..count { + let vertices = read_points(reader)?; + let uvs = if version > 0 { read_points(reader)? } else { Vec::new() }; + let mut groups = Vec::new(); + loop { + let material = reader.u8()?; + let face_bytes = usize::from(reader.u16()?) * 6; + if face_bytes == 0 { + break; + } + let faces = reader.bytes(face_bytes)?; + let (texture_id, uv_faces) = if version > 0 { + (reader.u16()?, reader.bytes(face_bytes)?) + } else { + (u16::MAX, &[][..]) + }; + groups.push(DecalFaces { + material, + faces, + texture_id, + uv_faces, + }); + } + decals.push(Decal { vertices, uvs, groups }); + } + Ok(decals) +} + +fn indexed_points(indices: &[u8], points: &[[f32; 2]]) -> Result<[[f32; 2]; 3]> { + let mut reader = Reader::new(indices); + let mut triangle = [[0.0; 2]; 3]; + for point in &mut triangle { + *point = *points.get(usize::from(reader.u16()?)).context("LMp2 decal index outside its vertex list")?; + } + Ok(triangle) +} + +fn material_is_road(is_road: &[bool], material: u8) -> u8 { + u8::from(is_road.get(usize::from(material)).copied().unwrap_or(false)) +} + +fn edge(a: [f32; 2], b: [f32; 2], p: [f32; 2]) -> f32 { + (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]) +} + +fn mask_covers(texture: &[u8], uv: [[f32; 2]; 3], weights: [f32; 3]) -> bool { + let texel = |axis: usize| { + let value = uv[0][axis] * weights[0] + uv[1][axis] * weights[1] + uv[2][axis] * weights[2]; + ((value - value.floor()) * (MASK_TEXTURE_SIZE - 1) as f32) as usize + }; + let x = texel(0); + let z = texel(1); + texture[z * size_of::() + x / 8] & (1 << (x % 8)) != 0 +} diff --git a/tools/navgen/mission-bounds.mts b/tools/navgen/mission-bounds.mts index 4ea682a..3ebb15a 100644 --- a/tools/navgen/mission-bounds.mts +++ b/tools/navgen/mission-bounds.mts @@ -11,6 +11,8 @@ */ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import { join, resolve } from 'node:path'; +import { TuningReader } from '../../apps/server/src/tuning/tuning-reader.ts'; +import { parseJsonc } from '../../packages/jsonc/src/index.ts'; import { readArchive, getFile, NAME_MAP_PATH } from '../../packages/vromfs/src/index.ts'; import { decodeBlk, parseSharedNameMap, findBlock, findParam, type BlkBlock, type SharedNameContext } from '../../packages/blk/src/index.ts'; @@ -32,6 +34,7 @@ interface LevelPois { readonly team1Spawns: readonly PoiPoint[]; readonly team2Spawns: readonly PoiPoint[]; readonly captureZones: readonly PoiPoint[]; + readonly coverBake: ReturnType; } function parseArgs(argv: string[]) { @@ -58,7 +61,7 @@ function openPack(packPath: string) { const dicts = [...arc.files.keys()].filter((k) => k.endsWith('.dict')); const dictionary = dicts.length ? arc.files.get(dicts[0]!) : undefined; const names = arc.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(arc, NAME_MAP_PATH), dictionary).names : []; - const shared: SharedNameContext = { names, dictionary }; + const shared: SharedNameContext = dictionary === undefined ? { names } : { names, dictionary }; const lowerMap = new Map(); for (const k of arc.files.keys()) lowerMap.set(k.toLowerCase(), k); return { @@ -145,8 +148,21 @@ function dedupePois(pts: PoiPoint[], minDistM: number): PoiPoint[] { return out; } +function readCoverBake() { + const path = join(import.meta.dirname, '../../apps/server/tuning/ground-ai.jsonc'); + const cover = new TuningReader(path, parseJsonc(readFileSync(path, 'utf8'))).object('coverMap'); + const peekMinM = cover.number('peekMinM', { min: 0.5 }); + return { + minCoverHeightM: cover.number('minCoverHeightM', { min: 0.5 }), + peekMinM, + peekMaxM: cover.number('peekMaxM', { min: peekMinM }), + retreatMinM: cover.number('retreatMinM', { min: 0.5 }), + }; +} + function main() { const { gameDir, outDir, levelsFilter } = parseArgs(process.argv.slice(2)); + const coverBake = readCoverBake(); mkdirSync(outDir, { recursive: true }); const charPack = openPack(join(gameDir, 'char.vromfs.bin')); @@ -193,7 +209,7 @@ function main() { if (!mPath) continue; const doc = misPack.readBlk(mPath); const ms = findBlock(doc, 'mission_settings'); - const mis = findBlock(ms, 'mission'); + const mis = ms ? findBlock(ms, 'mission') : undefined; if (val(mis, 'isTanksAllowed') === false) continue; const levelPath = String(val(mis, 'level') ?? ''); if (!levelPath) continue; @@ -268,6 +284,7 @@ function main() { team1Spawns: t1, team2Spawns: t2, captureZones: caps, + coverBake, }; const outPath = join(outDir, `${levelKey}.pois.json`); writeFileSync(outPath, `${JSON.stringify(out, null, 2)}\n`, 'utf8'); diff --git a/tools/navgen/render-preview.py b/tools/navgen/render-preview.py index d83112d..6b33d84 100644 --- a/tools/navgen/render-preview.py +++ b/tools/navgen/render-preview.py @@ -89,20 +89,23 @@ def main() -> None: with open(args.pois, "r", encoding="utf-8") as f: pois = json.load(f) - assert data[:8] == b"WTOPREV1", "bad preview magic" + magic = data[:8] + if magic not in (b"WTOPREV1", b"WTOPREV2"): + raise ValueError("bad preview magic") off = 8 pw, ph, min_x, min_z, max_x, max_z, water_y = struct.unpack_from(" None: # Bright green = T2 (wide heavy) + T1 + T0 walkable # Mid-green = T1 + T0 walkable (standard tank fits, wide heavy doesn't) # Yellow-green = T0 only (narrow tank alley) - # Orange = chokepoint, Purple-tint = crushable/forest, Teal = bridge + # Tan = road, Orange = chokepoint, Olive = crushable/forest, Teal = bridge r, g, b = base, base, base if fl & 16: # deep water r, g, b = 22, 58, 125 @@ -166,6 +169,8 @@ def main() -> None: r, g, b = 220, 145, 45 elif fl & 64: # crushable/forest r, g, b = int(base * 0.6 + 65), int(base * 0.8 + 85), int(base * 0.5 + 35) + elif fl & 256: # road + r, g, b = 174, 149, 108 elif fl & 4: # T2 wide walkable r, g, b = int(base * 0.5 + 48), int(base * 0.7 + 125), int(base * 0.5 + 52) elif fl & 2: # T1 standard walkable @@ -221,25 +226,25 @@ def main() -> None: draw_circle(rgb, pw, ph, x, y, 4, (255, 230, 40), fill=True) # Overlay covers on cover map: Blue=FULL, Green=HULLDOWN, Yellow=PEEK + peeks = [] for c in covers: px_w, py_w, pz_w = c[0], c[1], c[2] dx, dz = c[3], c[4] - peek_l = (c[7], c[9]) - peek_r = (c[10], c[12]) kind = c[16] - has_pl, has_pr = c[17], c[18] x, y = world_to_px(px_w, pz_w) col = (60, 165, 255) if kind == 1 else (55, 240, 100) draw_circle(cov_rgb, pw, ph, x, y, 2, col, fill=True) # Direction tick pointing toward blocked threat x2, y2 = world_to_px(px_w + dx * 8.0, pz_w + dz * 8.0) draw_line(cov_rgb, pw, ph, x, y, x2, y2, col, thick=1) - if has_pl: - lx, ly = world_to_px(*peek_l) - draw_circle(cov_rgb, pw, ph, lx, ly, 1, (255, 240, 60), fill=True) - if has_pr: - rx2, ry2 = world_to_px(*peek_r) - draw_circle(cov_rgb, pw, ph, rx2, ry2, 1, (255, 240, 60), fill=True) + if c[17]: + peeks.append(world_to_px(c[7], c[9])) + if c[18]: + peeks.append(world_to_px(c[10], c[12])) + + # Draw both corners last so neighboring covers cannot paint over their markers. + for x, y in peeks: + draw_circle(cov_rgb, pw, ph, x, y, 1, (255, 240, 60), fill=True) nav_out = os.path.join(args.out_dir, f"{args.name}_nav.png") cov_out = os.path.join(args.out_dir, f"{args.name}_cover.png")