0.2.0-dev Download ZIP
446 lines ·16.7 KB Raw
| 1 | using System.Buffers.Binary; |
| 2 | using System.Globalization; |
| 3 | using System.Numerics; |
| 4 | using System.Text; |
| 5 | using EvilEngine.Mounts; |
| 6 | |
| 7 | namespace EvilEngine.Adapters.Quake.Maps; |
| 8 | |
| 9 | public sealed class QuakeMapException(string file, string message) : Exception($"{file} {message}") |
| 10 | { |
| 11 | public string File { get; } = file; |
| 12 | } |
| 13 | |
| 14 | public enum QuakeBspVersion |
| 15 | { |
| 16 | Bsp29, |
| 17 | Bsp2 |
| 18 | } |
| 19 | |
| 20 | public static class QuakeContents |
| 21 | { |
| 22 | public const int Empty = -1; |
| 23 | public const int Solid = -2; |
| 24 | public const int Water = -3; |
| 25 | public const int Slime = -4; |
| 26 | public const int Lava = -5; |
| 27 | public const int Sky = -6; |
| 28 | public const int Origin = -7; |
| 29 | public const int Clip = -8; |
| 30 | public const int CurrentLast = -14; |
| 31 | } |
| 32 | |
| 33 | public readonly record struct QuakePlane(Vector3 Normal, float Distance); |
| 34 | |
| 35 | public readonly record struct QuakeNode(int Plane, int Front, int Back, int FirstFace, int FaceCount); |
| 36 | |
| 37 | public readonly record struct QuakeLeaf(int Contents, int FirstMark, int MarkCount); |
| 38 | |
| 39 | public readonly record struct QuakeTexInfo(Vector4 S, Vector4 T, int MipTex, int Flags) |
| 40 | { |
| 41 | public const int Special = 1; |
| 42 | } |
| 43 | |
| 44 | public readonly record struct QuakeFace( |
| 45 | int Plane, |
| 46 | bool Back, |
| 47 | int FirstEdge, |
| 48 | int EdgeCount, |
| 49 | int TexInfo, |
| 50 | uint Styles, |
| 51 | int LightOffset) |
| 52 | { |
| 53 | public const byte NoStyle = 255; |
| 54 | |
| 55 | public int StyleCount |
| 56 | { |
| 57 | get |
| 58 | { |
| 59 | var count = 0; |
| 60 | while (count < 4 && Style(count) != NoStyle) |
| 61 | count++; |
| 62 | return count; |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | public byte Style(int slot) |
| 67 | { |
| 68 | return (byte)(Styles >> (slot * 8)); |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | public readonly record struct QuakeModel( |
| 73 | Vector3 Min, |
| 74 | Vector3 Max, |
| 75 | Vector3 Origin, |
| 76 | int HeadNode, |
| 77 | int FirstFace, |
| 78 | int FaceCount); |
| 79 | |
| 80 | public sealed record QuakeMipTex(string Name, int Width, int Height, IReadOnlyList<ReadOnlyMemory<byte>>? Levels); |
| 81 | |
| 82 | public sealed class QuakeBsp |
| 83 | { |
| 84 | public const int MipLevels = 4; |
| 85 | public const int LuxelSize = 16; |
| 86 | |
| 87 | private const int LumpCount = 15; |
| 88 | private const int HeaderSize = 4 + LumpCount * 8; |
| 89 | private const int Bsp2Magic = 0x32505342; |
| 90 | |
| 91 | private readonly Lazy<IReadOnlyList<(int A, int B)>> _edges; |
| 92 | private readonly Lazy<IReadOnlyList<QuakeEntity>> _entities; |
| 93 | private readonly Lazy<IReadOnlyList<string>> _extra; |
| 94 | private readonly Lazy<IReadOnlyList<QuakeFace>> _faces; |
| 95 | private readonly Lazy<IReadOnlyList<QuakeLeaf>> _leafs; |
| 96 | private readonly Lazy<ReadOnlyMemory<byte>> _lighting; |
| 97 | private readonly (int Offset, int Length)[] _lumps; |
| 98 | private readonly Lazy<IReadOnlyList<int>> _markSurfaces; |
| 99 | private readonly Lazy<IReadOnlyList<QuakeMipTex?>> _mipTex; |
| 100 | private readonly Lazy<IReadOnlyList<QuakeModel>> _models; |
| 101 | private readonly Lazy<IReadOnlyList<QuakeNode>> _nodes; |
| 102 | private readonly Lazy<IReadOnlyList<QuakePlane>> _planes; |
| 103 | private readonly Func<long, int, ReadOnlyMemory<byte>> _read; |
| 104 | private readonly Lazy<IReadOnlyList<int>> _surfEdges; |
| 105 | private readonly Lazy<IReadOnlyList<QuakeTexInfo>> _texInfo; |
| 106 | private readonly Lazy<IReadOnlyList<Vector3>> _vertices; |
| 107 | |
| 108 | private QuakeBsp(string file, long length, Func<long, int, ReadOnlyMemory<byte>> read) |
| 109 | { |
| 110 | File = file; |
| 111 | _read = read; |
| 112 | if (length < HeaderSize) |
| 113 | throw new QuakeMapException(file, $"is {length} bytes, too short for a BSP header."); |
| 114 | var header = read(0, HeaderSize).Span; |
| 115 | var magic = BinaryPrimitives.ReadInt32LittleEndian(header); |
| 116 | Version = magic switch |
| 117 | { |
| 118 | 29 => QuakeBspVersion.Bsp29, |
| 119 | Bsp2Magic => QuakeBspVersion.Bsp2, |
| 120 | _ => throw new QuakeMapException(file, $"is BSP version {Describe(header[..4])}, not 29 or BSP2.") |
| 121 | }; |
| 122 | _lumps = new (int, int)[LumpCount]; |
| 123 | for (var i = 0; i < LumpCount; i++) |
| 124 | { |
| 125 | var offset = BinaryPrimitives.ReadInt32LittleEndian(header[(4 + i * 8)..]); |
| 126 | var size = BinaryPrimitives.ReadInt32LittleEndian(header[(8 + i * 8)..]); |
| 127 | if (offset < 0 || size < 0 || (long)offset + size > length) |
| 128 | throw new QuakeMapException(file, $"puts lump {i} at {offset} for {size} bytes, past its {length}."); |
| 129 | _lumps[i] = (offset, size); |
| 130 | } |
| 131 | |
| 132 | var wide = Version == QuakeBspVersion.Bsp2; |
| 133 | _planes = Lazy(() => Records(1, 20, span => new QuakePlane(Vector(span), Single(span, 12)))); |
| 134 | _vertices = Lazy(() => Records(3, 12, Vector)); |
| 135 | _nodes = Lazy(() => CheckNodes(wide |
| 136 | ? Records(5, 44, |
| 137 | span => new QuakeNode(Int(span, 0), Int(span, 4), Int(span, 8), Int(span, 36), Int(span, 40))) |
| 138 | : Records(5, 24, span => new QuakeNode(Int(span, 0), Short(span, 4), Short(span, 6), UShort(span, 20), |
| 139 | UShort(span, 22))))); |
| 140 | _texInfo = Lazy(() => CheckTexInfo(Records(6, 40, span => new QuakeTexInfo( |
| 141 | new Vector4(Single(span, 0), Single(span, 4), Single(span, 8), Single(span, 12)), |
| 142 | new Vector4(Single(span, 16), Single(span, 20), Single(span, 24), Single(span, 28)), |
| 143 | Int(span, 32), Int(span, 36))))); |
| 144 | _faces = Lazy(() => CheckFaces(wide |
| 145 | ? Records(7, 28, span => new QuakeFace(Int(span, 0), Int(span, 4) != 0, Int(span, 8), Int(span, 12), |
| 146 | Int(span, 16), BinaryPrimitives.ReadUInt32LittleEndian(span[20..]), Int(span, 24))) |
| 147 | : Records(7, 20, span => new QuakeFace(Short(span, 0), Short(span, 2) != 0, Int(span, 4), |
| 148 | Short(span, 8), Short(span, 10), BinaryPrimitives.ReadUInt32LittleEndian(span[12..]), Int(span, 16))))); |
| 149 | _lighting = new Lazy<ReadOnlyMemory<byte>>(() => Lump(8)); |
| 150 | _leafs = Lazy(() => wide |
| 151 | ? Records(10, 44, span => new QuakeLeaf(Int(span, 0), Int(span, 32), Int(span, 36))) |
| 152 | : Records(10, 28, span => new QuakeLeaf(Int(span, 0), UShort(span, 20), UShort(span, 22)))); |
| 153 | _markSurfaces = Lazy(() => |
| 154 | wide ? Records(11, 4, span => Int(span, 0)) : Records(11, 2, span => (int)UShort(span, 0))); |
| 155 | _edges = Lazy(() => wide |
| 156 | ? Records(12, 8, span => (Int(span, 0), Int(span, 4))) |
| 157 | : Records(12, 4, span => ((int)UShort(span, 0), (int)UShort(span, 2)))); |
| 158 | _surfEdges = Lazy(() => Records(13, 4, span => Int(span, 0))); |
| 159 | _models = Lazy(() => CheckModels(Records(14, 64, span => new QuakeModel(Vector(span), Vector(span[12..]), |
| 160 | Vector(span[24..]), Int(span, 36), Int(span, 56), Int(span, 60))))); |
| 161 | _entities = Lazy(() => QuakeEntities.Read(Lump(0).Span, file).ToArray()); |
| 162 | _mipTex = Lazy(() => ReadMipTex(Lump(2))); |
| 163 | _extra = Lazy(() => ReadExtra(length)); |
| 164 | } |
| 165 | |
| 166 | public string File { get; } |
| 167 | |
| 168 | public QuakeBspVersion Version { get; } |
| 169 | |
| 170 | public IReadOnlyList<QuakePlane> Planes => _planes.Value; |
| 171 | |
| 172 | public IReadOnlyList<Vector3> Vertices => _vertices.Value; |
| 173 | |
| 174 | public IReadOnlyList<QuakeNode> Nodes => _nodes.Value; |
| 175 | |
| 176 | public IReadOnlyList<QuakeTexInfo> TexInfo => _texInfo.Value; |
| 177 | |
| 178 | public IReadOnlyList<QuakeFace> Faces => _faces.Value; |
| 179 | |
| 180 | public ReadOnlyMemory<byte> Lighting => _lighting.Value; |
| 181 | |
| 182 | public IReadOnlyList<QuakeLeaf> Leafs => _leafs.Value; |
| 183 | |
| 184 | public IReadOnlyList<int> MarkSurfaces => _markSurfaces.Value; |
| 185 | |
| 186 | public IReadOnlyList<(int A, int B)> Edges => _edges.Value; |
| 187 | |
| 188 | public IReadOnlyList<int> SurfEdges => _surfEdges.Value; |
| 189 | |
| 190 | public IReadOnlyList<QuakeModel> Models => _models.Value; |
| 191 | |
| 192 | public IReadOnlyList<QuakeEntity> Entities => _entities.Value; |
| 193 | |
| 194 | public IReadOnlyList<QuakeMipTex?> MipTex => _mipTex.Value; |
| 195 | |
| 196 | public IReadOnlyList<string> Extra => _extra.Value; |
| 197 | |
| 198 | public static QuakeBsp Read(ReadOnlyMemory<byte> data, string file) |
| 199 | { |
| 200 | return new QuakeBsp(file, data.Length, (offset, length) => data.Slice((int)offset, length)); |
| 201 | } |
| 202 | |
| 203 | public static QuakeBsp Open(IRandomAccess access, string file) |
| 204 | { |
| 205 | return new QuakeBsp(file, access.Length, (offset, length) => |
| 206 | { |
| 207 | var buffer = new byte[length]; |
| 208 | access.ReadExactly(offset, buffer); |
| 209 | return buffer; |
| 210 | }); |
| 211 | } |
| 212 | |
| 213 | public int FaceVertex(QuakeFace face, int corner) |
| 214 | { |
| 215 | var edge = SurfEdges[face.FirstEdge + corner]; |
| 216 | return edge >= 0 ? Edges[edge].A : Edges[-edge].B; |
| 217 | } |
| 218 | |
| 219 | public (int MinS, int MinT, int Width, int Height) Extents(QuakeFace face) |
| 220 | { |
| 221 | var info = TexInfo[face.TexInfo]; |
| 222 | float minS = float.MaxValue, minT = float.MaxValue, maxS = float.MinValue, maxT = float.MinValue; |
| 223 | for (var corner = 0; corner < face.EdgeCount; corner++) |
| 224 | { |
| 225 | var point = Vertices[FaceVertex(face, corner)]; |
| 226 | var s = Texel(point, info.S); |
| 227 | var t = Texel(point, info.T); |
| 228 | (minS, maxS) = (Math.Min(minS, s), Math.Max(maxS, s)); |
| 229 | (minT, maxT) = (Math.Min(minT, t), Math.Max(maxT, t)); |
| 230 | } |
| 231 | |
| 232 | var lowS = (int)MathF.Floor(minS / LuxelSize); |
| 233 | var lowT = (int)MathF.Floor(minT / LuxelSize); |
| 234 | return (lowS * LuxelSize, lowT * LuxelSize, (int)MathF.Ceiling(maxS / LuxelSize) - lowS + 1, |
| 235 | (int)MathF.Ceiling(maxT / LuxelSize) - lowT + 1); |
| 236 | } |
| 237 | |
| 238 | public static float Texel(Vector3 point, Vector4 axis) |
| 239 | { |
| 240 | return (float)((double)point.X * axis.X + (double)point.Y * axis.Y + (double)point.Z * axis.Z + axis.W); |
| 241 | } |
| 242 | |
| 243 | public static int Leaf(int child) |
| 244 | { |
| 245 | return -child - 1; |
| 246 | } |
| 247 | |
| 248 | private QuakeFace[] CheckFaces(QuakeFace[] faces) |
| 249 | { |
| 250 | var planes = Planes.Count; |
| 251 | var texInfo = TexInfo.Count; |
| 252 | var surfEdges = SurfEdges; |
| 253 | var edges = Edges; |
| 254 | var vertices = Vertices.Count; |
| 255 | foreach (var face in faces) |
| 256 | { |
| 257 | if (face.Plane < 0 || face.Plane >= planes || face.TexInfo < 0 || face.TexInfo >= texInfo || |
| 258 | face.EdgeCount < 0 || face.FirstEdge < 0 || (long)face.FirstEdge + face.EdgeCount > surfEdges.Count) |
| 259 | throw new QuakeMapException(File, "has a face whose plane, texinfo or edges are out of range."); |
| 260 | for (var corner = 0; corner < face.EdgeCount; corner++) |
| 261 | { |
| 262 | var edge = surfEdges[face.FirstEdge + corner]; |
| 263 | if (edge == int.MinValue || Math.Abs(edge) >= edges.Count) |
| 264 | throw new QuakeMapException(File, $"has a face naming edge {edge} of {edges.Count}."); |
| 265 | var (a, b) = edges[Math.Abs(edge)]; |
| 266 | if (a < 0 || b < 0 || a >= vertices || b >= vertices) |
| 267 | throw new QuakeMapException(File, |
| 268 | $"has edge {Math.Abs(edge)} naming a vertex past its {vertices}."); |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | return faces; |
| 273 | } |
| 274 | |
| 275 | private QuakeNode[] CheckNodes(QuakeNode[] nodes) |
| 276 | { |
| 277 | var planes = Planes.Count; |
| 278 | var leafs = Leafs.Count; |
| 279 | foreach (var node in nodes) |
| 280 | { |
| 281 | if (node.Plane < 0 || node.Plane >= planes) |
| 282 | throw new QuakeMapException(File, $"has a node on plane {node.Plane} of {planes}."); |
| 283 | if (Bad(node.Front) || Bad(node.Back)) |
| 284 | throw new QuakeMapException(File, "has a node whose child is out of range."); |
| 285 | } |
| 286 | |
| 287 | return nodes; |
| 288 | |
| 289 | bool Bad(int child) |
| 290 | { |
| 291 | return child >= nodes.Length || (child < 0 && Leaf(child) >= leafs); |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | private QuakeTexInfo[] CheckTexInfo(QuakeTexInfo[] texInfo) |
| 296 | { |
| 297 | var count = MipTex.Count; |
| 298 | foreach (var info in texInfo) |
| 299 | if (info.MipTex < 0 || info.MipTex >= count) |
| 300 | throw new QuakeMapException(File, $"has a texinfo naming texture {info.MipTex} of {count}."); |
| 301 | return texInfo; |
| 302 | } |
| 303 | |
| 304 | private QuakeModel[] CheckModels(QuakeModel[] models) |
| 305 | { |
| 306 | if (models.Length == 0) |
| 307 | throw new QuakeMapException(File, "has no models, so no world."); |
| 308 | foreach (var model in models) |
| 309 | if (model.HeadNode >= Nodes.Count || model.FirstFace < 0 || |
| 310 | (long)model.FirstFace + model.FaceCount > Faces.Count) |
| 311 | throw new QuakeMapException(File, "has a model whose head node or faces are out of range."); |
| 312 | return models; |
| 313 | } |
| 314 | |
| 315 | private QuakeMipTex?[] ReadMipTex(ReadOnlyMemory<byte> lump) |
| 316 | { |
| 317 | var span = lump.Span; |
| 318 | if (span.Length == 0) |
| 319 | return []; |
| 320 | var count = Int(span, 0); |
| 321 | if (count < 0 || 4L + count * 4L > span.Length) |
| 322 | throw new QuakeMapException(File, |
| 323 | $"says it holds {count} textures, more than its texture lump has room for."); |
| 324 | var textures = new QuakeMipTex?[count]; |
| 325 | for (var i = 0; i < count; i++) |
| 326 | { |
| 327 | var offset = Int(span, 4 + i * 4); |
| 328 | if (offset < 0) |
| 329 | continue; |
| 330 | if ((long)offset + 40 > span.Length) |
| 331 | throw new QuakeMapException(File, $"puts texture {i} at {offset}, past its texture lump."); |
| 332 | var header = span[offset..]; |
| 333 | var nameBytes = header[..16]; |
| 334 | var end = nameBytes.IndexOf((byte)0); |
| 335 | var name = Encoding.Latin1.GetString(end < 0 ? nameBytes : nameBytes[..end]); |
| 336 | var width = Int(header, 16); |
| 337 | var height = Int(header, 20); |
| 338 | if (width >> (MipLevels - 1) <= 0 || height >> (MipLevels - 1) <= 0) |
| 339 | throw new QuakeMapException(File, |
| 340 | $"has texture '{name}' at {width}x{height}, too small for its {MipLevels} mip levels."); |
| 341 | var levels = new ReadOnlyMemory<byte>[MipLevels]; |
| 342 | var stored = true; |
| 343 | for (var level = 0; level < MipLevels; level++) |
| 344 | { |
| 345 | var start = Int(header, 24 + level * 4); |
| 346 | var size = (width >> level) * (height >> level); |
| 347 | if (start == 0) |
| 348 | { |
| 349 | stored = false; |
| 350 | break; |
| 351 | } |
| 352 | |
| 353 | if (start < 0 || (long)offset + start + size > span.Length) |
| 354 | throw new QuakeMapException(File, $"puts texture '{name}' level {level} past its texture lump."); |
| 355 | levels[level] = lump.Slice(offset + start, size); |
| 356 | } |
| 357 | |
| 358 | textures[i] = new QuakeMipTex(name, width, height, stored ? levels : null); |
| 359 | } |
| 360 | |
| 361 | return textures; |
| 362 | } |
| 363 | |
| 364 | private string[] ReadExtra(long length) |
| 365 | { |
| 366 | var end = _lumps.Max(lump => (long)lump.Offset + lump.Length); |
| 367 | var start = (end + 3) & ~3L; |
| 368 | if (start + 8 > length) |
| 369 | return []; |
| 370 | var header = _read(start, 8).Span; |
| 371 | if (!header[..4].SequenceEqual("BSPX"u8)) |
| 372 | return []; |
| 373 | var count = Int(header, 4); |
| 374 | if (count < 0 || start + 8 + count * 32L > length) |
| 375 | throw new QuakeMapException(File, $"has a BSPX table of {count} lumps past its end."); |
| 376 | var table = _read(start + 8, count * 32).Span; |
| 377 | var names = new string[count]; |
| 378 | for (var i = 0; i < count; i++) |
| 379 | { |
| 380 | var name = table.Slice(i * 32, 24); |
| 381 | var zero = name.IndexOf((byte)0); |
| 382 | names[i] = Encoding.ASCII.GetString(zero < 0 ? name : name[..zero]); |
| 383 | } |
| 384 | |
| 385 | return names; |
| 386 | } |
| 387 | |
| 388 | private ReadOnlyMemory<byte> Lump(int index) |
| 389 | { |
| 390 | var (offset, length) = _lumps[index]; |
| 391 | return length == 0 ? ReadOnlyMemory<byte>.Empty : _read(offset, length); |
| 392 | } |
| 393 | |
| 394 | private T[] Records<T>(int index, int size, SpanReader<T> read) |
| 395 | { |
| 396 | var length = _lumps[index].Length; |
| 397 | if (length % size != 0) |
| 398 | throw new QuakeMapException(File, |
| 399 | $"has lump {index} of {length} bytes, not a whole number of {size}-byte records."); |
| 400 | var span = Lump(index).Span; |
| 401 | var records = new T[length / size]; |
| 402 | for (var i = 0; i < records.Length; i++) |
| 403 | records[i] = read(span.Slice(i * size, size)); |
| 404 | return records; |
| 405 | } |
| 406 | |
| 407 | private static Lazy<IReadOnlyList<T>> Lazy<T>(Func<T[]> read) |
| 408 | { |
| 409 | return new Lazy<IReadOnlyList<T>>(() => read()); |
| 410 | } |
| 411 | |
| 412 | private static string Describe(ReadOnlySpan<byte> magic) |
| 413 | { |
| 414 | foreach (var b in magic) |
| 415 | if (b is < 0x20 or >= 0x7F) |
| 416 | return BinaryPrimitives.ReadInt32LittleEndian(magic).ToString(CultureInfo.InvariantCulture); |
| 417 | return $"'{Encoding.ASCII.GetString(magic)}'"; |
| 418 | } |
| 419 | |
| 420 | private static Vector3 Vector(ReadOnlySpan<byte> span) |
| 421 | { |
| 422 | return new Vector3(Single(span, 0), Single(span, 4), Single(span, 8)); |
| 423 | } |
| 424 | |
| 425 | private static float Single(ReadOnlySpan<byte> span, int at) |
| 426 | { |
| 427 | return BinaryPrimitives.ReadSingleLittleEndian(span[at..]); |
| 428 | } |
| 429 | |
| 430 | private static int Int(ReadOnlySpan<byte> span, int at) |
| 431 | { |
| 432 | return BinaryPrimitives.ReadInt32LittleEndian(span[at..]); |
| 433 | } |
| 434 | |
| 435 | private static short Short(ReadOnlySpan<byte> span, int at) |
| 436 | { |
| 437 | return BinaryPrimitives.ReadInt16LittleEndian(span[at..]); |
| 438 | } |
| 439 | |
| 440 | private static ushort UShort(ReadOnlySpan<byte> span, int at) |
| 441 | { |
| 442 | return BinaryPrimitives.ReadUInt16LittleEndian(span[at..]); |
| 443 | } |
| 444 | |
| 445 | private delegate T SpanReader<out T>(ReadOnlySpan<byte> span); |
| 446 | } |