merge ws/sourcemdl: Source MDL v44-49 (+vvd/vtx/phy/ani, flexes, animations), VMT materials, codecs/model/SourceAnim

This commit is contained in:
4DBug committed 2026-11-01 19:25:04 -06:00
commit c19a68dfae
33 files changed
+14429 -1224

No files matched your search

+5 -3
View File
@@ -46,7 +46,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list
## Formats ## Formats
<!-- formats:begin --> <!-- formats:begin -->
176 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) 178 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
adds each format's capabilities. adds each format's capabilities.
| Category | Format | Extensions | Read | Write | | Category | Format | Extensions | Read | Write |
@@ -136,6 +136,7 @@ adds each format's capabilities.
| 3D models | robloxmesh | .mesh | yes | yes | | 3D models | robloxmesh | .mesh | yes | yes |
| 3D models | schematic | .schem .schematic .litematic | yes | yes | | 3D models | schematic | .schem .schematic .litematic | yes | yes |
| 3D models | smd | .smd | yes | yes | | 3D models | smd | .smd | yes | yes |
| 3D models | sourcemdl | .mdl | yes | - |
| 3D models | stl | .stl | yes | yes | | 3D models | stl | .stl | yes | yes |
| 3D models | usda | .usda .usd .usdz | yes | yes | | 3D models | usda | .usda .usd .usdz | yes | yes |
| 3D models | vox | .vox | yes | yes | | 3D models | vox | .vox | yes | yes |
@@ -194,6 +195,7 @@ adds each format's capabilities.
| Data | plist | .plist | yes | yes | | Data | plist | .plist | yes | yes |
| Data | snbt | .snbt | yes | yes | | Data | snbt | .snbt | yes | yes |
| Data | toml | .toml | yes | yes | | Data | toml | .toml | yes | yes |
| Data | vdf | .vdf .acf .res .kv | yes | yes |
| Data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | | Data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes |
| Data | yaml | .yaml .yml | yes | yes | | Data | yaml | .yaml .yml | yes | yes |
| Vector graphics and tile maps | svg | .svg | yes | yes | | Vector graphics and tile maps | svg | .svg | yes | yes |
@@ -242,8 +244,8 @@ Shared by the formats, not loadable on their own (`src/Rosetta/codecs/<domain>/`
| entropy | Huffman, RangeCoder | | entropy | Huffman, RangeCoder |
| font | Bitmap, Cff, GlyphNames, TrueType | | font | Bitmap, Cff, GlyphNames, TrueType |
| image | Bcn, Blend, Dct, Etc, Half, Jpeg, Pixels, Quantize, Raster, Texel, Texture, Vp8, Vp8L, Yuv | | image | Bcn, Blend, Dct, Etc, Half, Jpeg, Pixels, Quantize, Raster, Texel, Texture, Vp8, Vp8L, Yuv |
| model | Draco, Mat4, MeshFlatten, Minecraft, Polygon, Rbx, Rig, Sampler, Vrml | | model | Draco, Mat4, MeshFlatten, Minecraft, Polygon, Rbx, Rig, Sampler, SourceAnim, Vrml |
| text | Json, Nbt, Text, Url, Xml | | text | Json, KeyValues, Nbt, Text, Url, Xml |
| video | Dsp, H263, H264, Legacy, Mpeg1, Mpeg2, Theora, Video | | video | Dsp, H263, H264, Legacy, Mpeg1, Mpeg2, Theora, Video |
| containers | Archive, AudioWrap, Avi, Chunks, Cpio, Demux, Ebml, Fat, Iso9660, IsoBmff, MacFile, MpegEs, MpegPs, MpegTs, Ogg, Riff, Tar, Zip | | containers | Archive, AudioWrap, Avi, Chunks, Cpio, Demux, Ebml, Fat, Iso9660, IsoBmff, MacFile, MpegEs, MpegPs, MpegTs, Ogg, Riff, Tar, Zip |
<!-- codecs:end --> <!-- codecs:end -->
+2901 -29
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
Binary file not shown.
+7 -7
View File
@@ -1,5 +1,5 @@
{ {
"Core_1": [[8, "src/Rosetta/init.luau"], [852, "src/Rosetta/Registry.luau"], [2985, "src/Rosetta/Types.luau"], [4068, "src/Rosetta/codecs/audio/Adpcm/init.luau"], [4822, "src/Rosetta/codecs/image/Yuv.luau"], [5090, "src/Rosetta/codecs/model/Rbx/init.luau"], [5327, "src/Rosetta/codecs/video/Video/init.luau"], [5884, "src/Rosetta/containers/AudioWrap.luau"], [6387, "src/Rosetta/containers/Ogg/Mux.luau"], [6582, "src/Rosetta/containers/Ogg/Page.luau"], [6751, "src/Rosetta/core/Bytes.luau"], [7278, "src/Rosetta/core/Crc32.luau"], [7390, "src/Rosetta/core/Err.luau"], [7472, "src/Rosetta/core/Input.luau"], [7548, "src/Rosetta/host/init.luau"]], "Core_1": [[8, "src/Rosetta/init.luau"], [852, "src/Rosetta/Registry.luau"], [3009, "src/Rosetta/Types.luau"], [4092, "src/Rosetta/codecs/audio/Adpcm/init.luau"], [4846, "src/Rosetta/codecs/image/Yuv.luau"], [5114, "src/Rosetta/codecs/model/Rbx/init.luau"], [5351, "src/Rosetta/codecs/video/Video/init.luau"], [5908, "src/Rosetta/containers/AudioWrap.luau"], [6411, "src/Rosetta/containers/Ogg/Mux.luau"], [6606, "src/Rosetta/containers/Ogg/Page.luau"], [6775, "src/Rosetta/core/Bytes.luau"], [7302, "src/Rosetta/core/Crc32.luau"], [7414, "src/Rosetta/core/Err.luau"], [7496, "src/Rosetta/core/Input.luau"], [7572, "src/Rosetta/host/init.luau"]],
"Core_2": [[8, "src/Rosetta/ops/ImageOps/init.luau"], [652, "src/Rosetta/ops/ImageOps/Kernels.luau"]], "Core_2": [[8, "src/Rosetta/ops/ImageOps/init.luau"], [652, "src/Rosetta/ops/ImageOps/Kernels.luau"]],
"Mpeg2": [[8, "src/Rosetta/codecs/video/Dsp.luau"], [731, "src/Rosetta/codecs/video/Mpeg1/init.luau"], [743, "src/Rosetta/codecs/video/Mpeg2/init.luau"], [1110, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], [2617, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], [2756, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"]], "Mpeg2": [[8, "src/Rosetta/codecs/video/Dsp.luau"], [731, "src/Rosetta/codecs/video/Mpeg1/init.luau"], [743, "src/Rosetta/codecs/video/Mpeg2/init.luau"], [1110, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], [2617, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], [2756, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"]],
"H263": [[8, "src/Rosetta/codecs/video/H263/init.luau"], [164, "src/Rosetta/codecs/video/H263/Decoder.luau"], [1022, "src/Rosetta/codecs/video/H263/Tables.luau"]], "H263": [[8, "src/Rosetta/codecs/video/H263/init.luau"], [164, "src/Rosetta/codecs/video/H263/Decoder.luau"], [1022, "src/Rosetta/codecs/video/H263/Tables.luau"]],
@@ -36,12 +36,12 @@
"codecs_entropy": [[8, "src/Rosetta/codecs/entropy/Huffman.luau"], [290, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], [301, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], [515, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"]], "codecs_entropy": [[8, "src/Rosetta/codecs/entropy/Huffman.luau"], [290, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], [301, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], [515, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"]],
"codecs_font": [[8, "src/Rosetta/codecs/font/Bitmap.luau"], [209, "src/Rosetta/codecs/font/Cff/init.luau"], [850, "src/Rosetta/codecs/font/GlyphNames.luau"], [1000, "src/Rosetta/codecs/font/TrueType/init.luau"], [1314, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], [1706, "src/Rosetta/codecs/font/TrueType/Tables.luau"]], "codecs_font": [[8, "src/Rosetta/codecs/font/Bitmap.luau"], [209, "src/Rosetta/codecs/font/Cff/init.luau"], [850, "src/Rosetta/codecs/font/GlyphNames.luau"], [1000, "src/Rosetta/codecs/font/TrueType/init.luau"], [1314, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], [1706, "src/Rosetta/codecs/font/TrueType/Tables.luau"]],
"codecs_image": [[8, "src/Rosetta/codecs/image/Blend.luau"], [387, "src/Rosetta/codecs/image/Etc.luau"], [685, "src/Rosetta/codecs/image/Half.luau"], [754, "src/Rosetta/codecs/image/Pixels.luau"], [1018, "src/Rosetta/codecs/image/Quantize/init.luau"], [1477, "src/Rosetta/codecs/image/Raster.luau"], [2174, "src/Rosetta/codecs/image/Texel.luau"], [2547, "src/Rosetta/codecs/image/Texture.luau"]], "codecs_image": [[8, "src/Rosetta/codecs/image/Blend.luau"], [387, "src/Rosetta/codecs/image/Etc.luau"], [685, "src/Rosetta/codecs/image/Half.luau"], [754, "src/Rosetta/codecs/image/Pixels.luau"], [1018, "src/Rosetta/codecs/image/Quantize/init.luau"], [1477, "src/Rosetta/codecs/image/Raster.luau"], [2174, "src/Rosetta/codecs/image/Texel.luau"], [2547, "src/Rosetta/codecs/image/Texture.luau"]],
"codecs_model": [[8, "src/Rosetta/codecs/model/Mat4.luau"], [267, "src/Rosetta/codecs/model/MeshFlatten.luau"], [795, "src/Rosetta/codecs/model/Minecraft/init.luau"], [1347, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], [1426, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], [1533, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], [1739, "src/Rosetta/codecs/model/Polygon.luau"], [1973, "src/Rosetta/codecs/model/Rbx/Binary.luau"], [2727, "src/Rosetta/codecs/model/Rig.luau"], [2970, "src/Rosetta/codecs/model/Sampler.luau"], [3130, "src/Rosetta/codecs/model/Vrml/init.luau"], [3278, "src/Rosetta/codecs/model/Vrml/Build.luau"], [3852, "src/Rosetta/codecs/model/Vrml/Fields.luau"], [4015, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], [4764, "src/Rosetta/codecs/model/Vrml/Parse.luau"], [5286, "src/Rosetta/codecs/model/Vrml/Write.luau"], [6013, "src/Rosetta/codecs/model/Vrml/Xml.luau"]], "codecs_model": [[8, "src/Rosetta/codecs/model/Mat4.luau"], [267, "src/Rosetta/codecs/model/MeshFlatten.luau"], [795, "src/Rosetta/codecs/model/Minecraft/init.luau"], [1347, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], [1426, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], [1533, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], [1739, "src/Rosetta/codecs/model/Polygon.luau"], [1973, "src/Rosetta/codecs/model/Rbx/Binary.luau"], [2727, "src/Rosetta/codecs/model/Rig.luau"], [2970, "src/Rosetta/codecs/model/Sampler.luau"], [3130, "src/Rosetta/codecs/model/SourceAnim.luau"], [3351, "src/Rosetta/codecs/model/Vrml/init.luau"], [3499, "src/Rosetta/codecs/model/Vrml/Build.luau"], [4073, "src/Rosetta/codecs/model/Vrml/Fields.luau"], [4236, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], [4985, "src/Rosetta/codecs/model/Vrml/Parse.luau"], [5507, "src/Rosetta/codecs/model/Vrml/Write.luau"], [6234, "src/Rosetta/codecs/model/Vrml/Xml.luau"]],
"codecs_text": [[8, "src/Rosetta/codecs/text/Json/init.luau"], [277, "src/Rosetta/codecs/text/Json/Decode.luau"], [691, "src/Rosetta/codecs/text/Json/Encode.luau"], [993, "src/Rosetta/codecs/text/Nbt/init.luau"], [1346, "src/Rosetta/codecs/text/Nbt/Binary.luau"], [2038, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], [2678, "src/Rosetta/codecs/text/Nbt/Value.luau"], [2916, "src/Rosetta/codecs/text/Text/init.luau"], [3007, "src/Rosetta/codecs/text/Url/init.luau"], [3212, "src/Rosetta/codecs/text/Xml/init.luau"], [3615, "src/Rosetta/codecs/text/Xml/Parse.luau"]], "codecs_text": [[8, "src/Rosetta/codecs/text/Json/init.luau"], [277, "src/Rosetta/codecs/text/Json/Decode.luau"], [691, "src/Rosetta/codecs/text/Json/Encode.luau"], [993, "src/Rosetta/codecs/text/KeyValues/init.luau"], [1550, "src/Rosetta/codecs/text/KeyValues/Binary.luau"], [1855, "src/Rosetta/codecs/text/Nbt/init.luau"], [2208, "src/Rosetta/codecs/text/Nbt/Binary.luau"], [2900, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], [3540, "src/Rosetta/codecs/text/Nbt/Value.luau"], [3778, "src/Rosetta/codecs/text/Text/init.luau"], [3869, "src/Rosetta/codecs/text/Url/init.luau"], [4074, "src/Rosetta/codecs/text/Xml/init.luau"], [4477, "src/Rosetta/codecs/text/Xml/Parse.luau"]],
"codecs_video": [[8, "src/Rosetta/codecs/video/Video/Source.luau"]], "codecs_video": [[8, "src/Rosetta/codecs/video/Video/Source.luau"]],
"containers": [[8, "src/Rosetta/containers/Archive.luau"], [275, "src/Rosetta/containers/Avi/init.luau"], [827, "src/Rosetta/containers/Chunks.luau"], [962, "src/Rosetta/containers/Cpio.luau"], [1390, "src/Rosetta/containers/Demux.luau"], [1665, "src/Rosetta/containers/Ebml/init.luau"], [1978, "src/Rosetta/containers/Fat.luau"], [2666, "src/Rosetta/containers/Iso9660.luau"], [3171, "src/Rosetta/containers/IsoBmff/init.luau"], [3341, "src/Rosetta/containers/IsoBmff/Box.luau"], [3529, "src/Rosetta/containers/IsoBmff/Demux.luau"], [4374, "src/Rosetta/containers/IsoBmff/Meta.luau"], [4895, "src/Rosetta/containers/IsoBmff/Mux.luau"], [5411, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], [5528, "src/Rosetta/containers/MacFile.luau"], [5677, "src/Rosetta/containers/Ogg/init.luau"], [6102, "src/Rosetta/containers/Riff/init.luau"], [6419, "src/Rosetta/containers/Tar.luau"], [6833, "src/Rosetta/containers/Zip/init.luau"]], "containers": [[8, "src/Rosetta/containers/Archive.luau"], [275, "src/Rosetta/containers/Avi/init.luau"], [827, "src/Rosetta/containers/Chunks.luau"], [962, "src/Rosetta/containers/Cpio.luau"], [1390, "src/Rosetta/containers/Demux.luau"], [1665, "src/Rosetta/containers/Ebml/init.luau"], [1978, "src/Rosetta/containers/Fat.luau"], [2666, "src/Rosetta/containers/Iso9660.luau"], [3171, "src/Rosetta/containers/IsoBmff/init.luau"], [3341, "src/Rosetta/containers/IsoBmff/Box.luau"], [3529, "src/Rosetta/containers/IsoBmff/Demux.luau"], [4374, "src/Rosetta/containers/IsoBmff/Meta.luau"], [4895, "src/Rosetta/containers/IsoBmff/Mux.luau"], [5411, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], [5528, "src/Rosetta/containers/MacFile.luau"], [5677, "src/Rosetta/containers/Ogg/init.luau"], [6102, "src/Rosetta/containers/Riff/init.luau"], [6419, "src/Rosetta/containers/Tar.luau"], [6833, "src/Rosetta/containers/Zip/init.luau"]],
"core": [[8, "src/Rosetta/core/Adler32.luau"], [54, "src/Rosetta/core/Base64.luau"], [213, "src/Rosetta/core/Bits.luau"], [506, "src/Rosetta/core/Crc16.luau"], [558, "src/Rosetta/core/Md5.luau"], [717, "src/Rosetta/core/Sniff.luau"]], "core": [[8, "src/Rosetta/core/Adler32.luau"], [54, "src/Rosetta/core/Base64.luau"], [213, "src/Rosetta/core/Bits.luau"], [506, "src/Rosetta/core/Crc16.luau"], [558, "src/Rosetta/core/Md5.luau"], [717, "src/Rosetta/core/Sniff.luau"]],
"data": [[8, "src/Rosetta/data/cbor/init.luau"], [107, "src/Rosetta/data/cbor/Codec.luau"], [676, "src/Rosetta/data/csv/init.luau"], [988, "src/Rosetta/data/ini/init.luau"], [1234, "src/Rosetta/data/json/init.luau"], [1326, "src/Rosetta/data/msgpack/init.luau"], [1415, "src/Rosetta/data/msgpack/Codec.luau"], [1857, "src/Rosetta/data/nbt/init.luau"], [1916, "src/Rosetta/data/plist/init.luau"], [2222, "src/Rosetta/data/plist/Binary.luau"], [2489, "src/Rosetta/data/snbt/init.luau"], [2552, "src/Rosetta/data/toml/init.luau"], [2619, "src/Rosetta/data/toml/Decode.luau"], [3247, "src/Rosetta/data/toml/Encode.luau"], [3456, "src/Rosetta/data/xml/init.luau"], [3512, "src/Rosetta/data/yaml/init.luau"], [3585, "src/Rosetta/data/yaml/Emit.luau"], [3875, "src/Rosetta/data/yaml/Parse.luau"]], "data": [[8, "src/Rosetta/data/cbor/init.luau"], [107, "src/Rosetta/data/cbor/Codec.luau"], [676, "src/Rosetta/data/csv/init.luau"], [988, "src/Rosetta/data/ini/init.luau"], [1234, "src/Rosetta/data/json/init.luau"], [1326, "src/Rosetta/data/msgpack/init.luau"], [1415, "src/Rosetta/data/msgpack/Codec.luau"], [1857, "src/Rosetta/data/nbt/init.luau"], [1916, "src/Rosetta/data/plist/init.luau"], [2222, "src/Rosetta/data/plist/Binary.luau"], [2489, "src/Rosetta/data/snbt/init.luau"], [2552, "src/Rosetta/data/toml/init.luau"], [2619, "src/Rosetta/data/toml/Decode.luau"], [3247, "src/Rosetta/data/toml/Encode.luau"], [3456, "src/Rosetta/data/vdf/init.luau"], [3557, "src/Rosetta/data/xml/init.luau"], [3613, "src/Rosetta/data/yaml/init.luau"], [3686, "src/Rosetta/data/yaml/Emit.luau"], [3976, "src/Rosetta/data/yaml/Parse.luau"]],
"font": [[8, "src/Rosetta/font/bdf/init.luau"], [297, "src/Rosetta/font/bmfont/init.luau"], [724, "src/Rosetta/font/bmfont/Parse.luau"], [1177, "src/Rosetta/font/eot/init.luau"], [1409, "src/Rosetta/font/fon/init.luau"], [1692, "src/Rosetta/font/hershey/init.luau"], [1887, "src/Rosetta/font/pcf/init.luau"], [2167, "src/Rosetta/font/psf/init.luau"], [2487, "src/Rosetta/font/ttf/init.luau"], [2538, "src/Rosetta/font/type1/init.luau"], [2897, "src/Rosetta/font/type1/Charstring.luau"], [3175, "src/Rosetta/font/woff/init.luau"], [3307, "src/Rosetta/font/woff2/init.luau"], [3364, "src/Rosetta/font/woff2/Rebuild.luau"]], "font": [[8, "src/Rosetta/font/bdf/init.luau"], [297, "src/Rosetta/font/bmfont/init.luau"], [724, "src/Rosetta/font/bmfont/Parse.luau"], [1177, "src/Rosetta/font/eot/init.luau"], [1409, "src/Rosetta/font/fon/init.luau"], [1692, "src/Rosetta/font/hershey/init.luau"], [1887, "src/Rosetta/font/pcf/init.luau"], [2167, "src/Rosetta/font/psf/init.luau"], [2487, "src/Rosetta/font/ttf/init.luau"], [2538, "src/Rosetta/font/type1/init.luau"], [2897, "src/Rosetta/font/type1/Charstring.luau"], [3175, "src/Rosetta/font/woff/init.luau"], [3307, "src/Rosetta/font/woff2/init.luau"], [3364, "src/Rosetta/font/woff2/Rebuild.luau"]],
"host": [[8, "src/Rosetta/host/Love.luau"], [151, "src/Rosetta/host/LuaJIT.luau"], [201, "src/Rosetta/host/Luau.luau"], [224, "src/Rosetta/host/Roblox.luau"]], "host": [[8, "src/Rosetta/host/Love.luau"], [151, "src/Rosetta/host/LuaJIT.luau"], [201, "src/Rosetta/host/Luau.luau"], [224, "src/Rosetta/host/Roblox.luau"]],
"image_1": [[8, "src/Rosetta/image/ani/init.luau"], [188, "src/Rosetta/image/art/init.luau"], [676, "src/Rosetta/image/blp/init.luau"], [934, "src/Rosetta/image/bmp/init.luau"], [1349, "src/Rosetta/image/dds/init.luau"], [1832, "src/Rosetta/image/exr/init.luau"], [2592, "src/Rosetta/image/exr/Codec.luau"], [2703, "src/Rosetta/image/exr/Piz.luau"], [3060, "src/Rosetta/image/gif/init.luau"], [3576, "src/Rosetta/image/gif/Decode.luau"], [3639, "src/Rosetta/image/hdr/init.luau"], [3868, "src/Rosetta/image/hdr/Codec.luau"], [4079, "src/Rosetta/image/icns/init.luau"], [4410, "src/Rosetta/image/ico/init.luau"], [4687, "src/Rosetta/image/ico/Dib.luau"], [4782, "src/Rosetta/image/ilbm/init.luau"], [5101, "src/Rosetta/image/jpeg/init.luau"], [5237, "src/Rosetta/image/ktx/init.luau"], [5897, "src/Rosetta/image/pcx/init.luau"], [6161, "src/Rosetta/image/pnm/init.luau"], [6539, "src/Rosetta/image/pnm/Codec.luau"], [6816, "src/Rosetta/image/qoi/init.luau"], [6938, "src/Rosetta/image/qoi/Codec.luau"], [7088, "src/Rosetta/image/sgi/init.luau"], [7373, "src/Rosetta/image/sunras/init.luau"], [7619, "src/Rosetta/image/tga/init.luau"]], "image_1": [[8, "src/Rosetta/image/ani/init.luau"], [188, "src/Rosetta/image/art/init.luau"], [676, "src/Rosetta/image/blp/init.luau"], [934, "src/Rosetta/image/bmp/init.luau"], [1349, "src/Rosetta/image/dds/init.luau"], [1832, "src/Rosetta/image/exr/init.luau"], [2592, "src/Rosetta/image/exr/Codec.luau"], [2703, "src/Rosetta/image/exr/Piz.luau"], [3060, "src/Rosetta/image/gif/init.luau"], [3576, "src/Rosetta/image/gif/Decode.luau"], [3639, "src/Rosetta/image/hdr/init.luau"], [3868, "src/Rosetta/image/hdr/Codec.luau"], [4079, "src/Rosetta/image/icns/init.luau"], [4410, "src/Rosetta/image/ico/init.luau"], [4687, "src/Rosetta/image/ico/Dib.luau"], [4782, "src/Rosetta/image/ilbm/init.luau"], [5101, "src/Rosetta/image/jpeg/init.luau"], [5237, "src/Rosetta/image/ktx/init.luau"], [5897, "src/Rosetta/image/pcx/init.luau"], [6161, "src/Rosetta/image/pnm/init.luau"], [6539, "src/Rosetta/image/pnm/Codec.luau"], [6816, "src/Rosetta/image/qoi/init.luau"], [6938, "src/Rosetta/image/qoi/Codec.luau"], [7088, "src/Rosetta/image/sgi/init.luau"], [7373, "src/Rosetta/image/sunras/init.luau"], [7619, "src/Rosetta/image/tga/init.luau"]],
@@ -49,9 +49,9 @@
"layered": [[8, "src/Rosetta/layered/aseprite/init.luau"], [746, "src/Rosetta/layered/ora/init.luau"], [1033, "src/Rosetta/layered/psd/init.luau"], [1768, "src/Rosetta/layered/psd/Channels.luau"]], "layered": [[8, "src/Rosetta/layered/aseprite/init.luau"], [746, "src/Rosetta/layered/ora/init.luau"], [1033, "src/Rosetta/layered/psd/init.luau"], [1768, "src/Rosetta/layered/psd/Channels.luau"]],
"model_1": [[8, "src/Rosetta/model/3ds/init.luau"], [91, "src/Rosetta/model/3ds/Build.luau"], [738, "src/Rosetta/model/3ds/Read.luau"], [1234, "src/Rosetta/model/3ds/Write.luau"], [2039, "src/Rosetta/model/3mf/init.luau"], [2121, "src/Rosetta/model/3mf/Read.luau"], [2709, "src/Rosetta/model/3mf/Write.luau"], [3114, "src/Rosetta/model/b3d/init.luau"], [3169, "src/Rosetta/model/b3d/Read.luau"], [3740, "src/Rosetta/model/bsp/init.luau"], [3885, "src/Rosetta/model/bsp/Brush.luau"], [4163, "src/Rosetta/model/bsp/Quake3.luau"], [4418, "src/Rosetta/model/buildmap/init.luau"], [4690, "src/Rosetta/model/buildmap/Geometry.luau"], [5093, "src/Rosetta/model/dae/init.luau"], [5282, "src/Rosetta/model/dae/Math.luau"], [5329, "src/Rosetta/model/dae/Read.luau"], [7179, "src/Rosetta/model/dae/Write.luau"], [7548, "src/Rosetta/model/fbx/init.luau"]], "model_1": [[8, "src/Rosetta/model/3ds/init.luau"], [91, "src/Rosetta/model/3ds/Build.luau"], [738, "src/Rosetta/model/3ds/Read.luau"], [1234, "src/Rosetta/model/3ds/Write.luau"], [2039, "src/Rosetta/model/3mf/init.luau"], [2121, "src/Rosetta/model/3mf/Read.luau"], [2709, "src/Rosetta/model/3mf/Write.luau"], [3114, "src/Rosetta/model/b3d/init.luau"], [3169, "src/Rosetta/model/b3d/Read.luau"], [3740, "src/Rosetta/model/bsp/init.luau"], [3885, "src/Rosetta/model/bsp/Brush.luau"], [4163, "src/Rosetta/model/bsp/Quake3.luau"], [4418, "src/Rosetta/model/buildmap/init.luau"], [4690, "src/Rosetta/model/buildmap/Geometry.luau"], [5093, "src/Rosetta/model/dae/init.luau"], [5282, "src/Rosetta/model/dae/Math.luau"], [5329, "src/Rosetta/model/dae/Read.luau"], [7179, "src/Rosetta/model/dae/Write.luau"], [7548, "src/Rosetta/model/fbx/init.luau"]],
"model_2": [[8, "src/Rosetta/model/fbx/Ascii.luau"], [278, "src/Rosetta/model/fbx/Binary.luau"], [733, "src/Rosetta/model/fbx/Read.luau"], [2095, "src/Rosetta/model/fbx/Write.luau"], [3080, "src/Rosetta/model/fbx/Xform.luau"], [3121, "src/Rosetta/model/gltf/init.luau"], [3358, "src/Rosetta/model/gltf/Pack.luau"], [3427, "src/Rosetta/model/gltf/Read.luau"], [4158, "src/Rosetta/model/gltf/Write.luau"], [4838, "src/Rosetta/model/iqm/init.luau"], [4914, "src/Rosetta/model/iqm/Read.luau"], [5269, "src/Rosetta/model/iqm/Write.luau"], [5956, "src/Rosetta/model/ldraw/init.luau"], [6034, "src/Rosetta/model/ldraw/Colors.luau"], [6352, "src/Rosetta/model/ldraw/Read.luau"], [6929, "src/Rosetta/model/lwo/init.luau"], [7005, "src/Rosetta/model/lwo/Build.luau"]], "model_2": [[8, "src/Rosetta/model/fbx/Ascii.luau"], [278, "src/Rosetta/model/fbx/Binary.luau"], [733, "src/Rosetta/model/fbx/Read.luau"], [2095, "src/Rosetta/model/fbx/Write.luau"], [3080, "src/Rosetta/model/fbx/Xform.luau"], [3121, "src/Rosetta/model/gltf/init.luau"], [3358, "src/Rosetta/model/gltf/Pack.luau"], [3427, "src/Rosetta/model/gltf/Read.luau"], [4158, "src/Rosetta/model/gltf/Write.luau"], [4838, "src/Rosetta/model/iqm/init.luau"], [4914, "src/Rosetta/model/iqm/Read.luau"], [5269, "src/Rosetta/model/iqm/Write.luau"], [5956, "src/Rosetta/model/ldraw/init.luau"], [6034, "src/Rosetta/model/ldraw/Colors.luau"], [6352, "src/Rosetta/model/ldraw/Read.luau"], [6929, "src/Rosetta/model/lwo/init.luau"], [7005, "src/Rosetta/model/lwo/Build.luau"]],
"model_3": [[8, "src/Rosetta/model/lwo/Parse.luau"], [551, "src/Rosetta/model/mca/init.luau"], [893, "src/Rosetta/model/mca/Chunk.luau"], [1026, "src/Rosetta/model/mca/Lz4Block.luau"], [1096, "src/Rosetta/model/md2/init.luau"], [1295, "src/Rosetta/model/md3/init.luau"], [1523, "src/Rosetta/model/md5/init.luau"], [1604, "src/Rosetta/model/md5/Read.luau"], [2037, "src/Rosetta/model/mdl/init.luau"], [2119, "src/Rosetta/model/mdl/HalfLife.luau"], [2447, "src/Rosetta/model/mdl/Quake.luau"], [2665, "src/Rosetta/model/ms3d/init.luau"], [2737, "src/Rosetta/model/ms3d/Read.luau"], [3183, "src/Rosetta/model/ms3d/Write.luau"], [3652, "src/Rosetta/model/obj/init.luau"], [4394, "src/Rosetta/model/obj/Mtl.luau"], [4681, "src/Rosetta/model/off/init.luau"], [5143, "src/Rosetta/model/ply/init.luau"], [6248, "src/Rosetta/model/ply/Binary.luau"], [6449, "src/Rosetta/model/pmx/init.luau"], [6518, "src/Rosetta/model/pmx/Build.luau"], [6814, "src/Rosetta/model/pmx/Pmd.luau"], [7149, "src/Rosetta/model/pmx/Read.luau"], [7553, "src/Rosetta/model/qb/init.luau"]], "model_3": [[8, "src/Rosetta/model/lwo/Parse.luau"], [551, "src/Rosetta/model/mca/init.luau"], [893, "src/Rosetta/model/mca/Chunk.luau"], [1026, "src/Rosetta/model/mca/Lz4Block.luau"], [1096, "src/Rosetta/model/md2/init.luau"], [1295, "src/Rosetta/model/md3/init.luau"], [1523, "src/Rosetta/model/md5/init.luau"], [1604, "src/Rosetta/model/md5/Read.luau"], [2037, "src/Rosetta/model/mdl/init.luau"], [2119, "src/Rosetta/model/mdl/HalfLife.luau"], [2423, "src/Rosetta/model/mdl/Quake.luau"], [2641, "src/Rosetta/model/ms3d/init.luau"], [2713, "src/Rosetta/model/ms3d/Read.luau"], [3159, "src/Rosetta/model/ms3d/Write.luau"], [3628, "src/Rosetta/model/obj/init.luau"], [4370, "src/Rosetta/model/obj/Mtl.luau"], [4657, "src/Rosetta/model/off/init.luau"], [5119, "src/Rosetta/model/ply/init.luau"], [6224, "src/Rosetta/model/ply/Binary.luau"], [6425, "src/Rosetta/model/pmx/init.luau"], [6494, "src/Rosetta/model/pmx/Build.luau"], [6790, "src/Rosetta/model/pmx/Pmd.luau"], [7125, "src/Rosetta/model/pmx/Read.luau"], [7529, "src/Rosetta/model/qb/init.luau"]],
"model_4": [[8, "src/Rosetta/model/rbxm/init.luau"], [600, "src/Rosetta/model/rbxmx/init.luau"], [1253, "src/Rosetta/model/robloxmesh/init.luau"], [1912, "src/Rosetta/model/robloxmesh/Parse.luau"], [2369, "src/Rosetta/model/robloxmesh/Write.luau"], [2478, "src/Rosetta/model/schematic/init.luau"], [2799, "src/Rosetta/model/schematic/Common.luau"], [2919, "src/Rosetta/model/schematic/Litematic.luau"], [3130, "src/Rosetta/model/schematic/Mcedit.luau"], [3374, "src/Rosetta/model/schematic/Sponge.luau"], [3503, "src/Rosetta/model/smd/init.luau"], [3570, "src/Rosetta/model/smd/Read.luau"], [3839, "src/Rosetta/model/smd/Write.luau"], [4082, "src/Rosetta/model/stl/init.luau"], [4532, "src/Rosetta/model/stl/Decode.luau"], [4606, "src/Rosetta/model/usda/init.luau"], [4815, "src/Rosetta/model/usda/Build.luau"], [6093, "src/Rosetta/model/usda/Parse.luau"], [6891, "src/Rosetta/model/usda/Write.luau"]], "model_4": [[8, "src/Rosetta/model/rbxm/init.luau"], [600, "src/Rosetta/model/rbxmx/init.luau"], [1253, "src/Rosetta/model/robloxmesh/init.luau"], [1912, "src/Rosetta/model/robloxmesh/Parse.luau"], [2369, "src/Rosetta/model/robloxmesh/Write.luau"], [2478, "src/Rosetta/model/schematic/init.luau"], [2799, "src/Rosetta/model/schematic/Common.luau"], [2919, "src/Rosetta/model/schematic/Litematic.luau"], [3130, "src/Rosetta/model/schematic/Mcedit.luau"], [3374, "src/Rosetta/model/schematic/Sponge.luau"], [3503, "src/Rosetta/model/smd/init.luau"], [3570, "src/Rosetta/model/smd/Read.luau"], [3839, "src/Rosetta/model/smd/Write.luau"], [4082, "src/Rosetta/model/sourcemdl/init.luau"], [4253, "src/Rosetta/model/sourcemdl/Build.luau"], [4683, "src/Rosetta/model/sourcemdl/Material.luau"], [4844, "src/Rosetta/model/sourcemdl/Mdl.luau"], [5371, "src/Rosetta/model/sourcemdl/Phy.luau"], [5494, "src/Rosetta/model/sourcemdl/Vtx.luau"], [5676, "src/Rosetta/model/sourcemdl/Vvd.luau"], [5770, "src/Rosetta/model/stl/init.luau"], [6220, "src/Rosetta/model/stl/Decode.luau"], [6294, "src/Rosetta/model/usda/init.luau"], [6503, "src/Rosetta/model/usda/Build.luau"]],
"model_5": [[8, "src/Rosetta/model/vox/init.luau"], [894, "src/Rosetta/model/vox/Grid.luau"], [951, "src/Rosetta/model/vrml/init.luau"], [1017, "src/Rosetta/model/x/init.luau"], [1147, "src/Rosetta/model/x/Build.luau"], [1710, "src/Rosetta/model/x/Parse.luau"], [2007, "src/Rosetta/model/x3d/init.luau"]], "model_5": [[8, "src/Rosetta/model/usda/Parse.luau"], [806, "src/Rosetta/model/usda/Write.luau"], [1623, "src/Rosetta/model/vox/init.luau"], [2509, "src/Rosetta/model/vox/Grid.luau"], [2566, "src/Rosetta/model/vrml/init.luau"], [2632, "src/Rosetta/model/x/init.luau"], [2762, "src/Rosetta/model/x/Build.luau"], [3325, "src/Rosetta/model/x/Parse.luau"], [3622, "src/Rosetta/model/x3d/init.luau"]],
"music": [[8, "src/Rosetta/music/669/init.luau"], [214, "src/Rosetta/music/ahx/init.luau"], [265, "src/Rosetta/music/far/init.luau"], [494, "src/Rosetta/music/hmp/init.luau"], [758, "src/Rosetta/music/hvl/init.luau"], [809, "src/Rosetta/music/it/init.luau"], [1227, "src/Rosetta/music/it/Itsex.luau"], [1343, "src/Rosetta/music/med/init.luau"], [1990, "src/Rosetta/music/midi/init.luau"], [2133, "src/Rosetta/music/midi/Smf.luau"], [2544, "src/Rosetta/music/mod/init.luau"], [2897, "src/Rosetta/music/mtm/init.luau"], [3119, "src/Rosetta/music/mus/init.luau"], [3276, "src/Rosetta/music/okt/init.luau"], [3557, "src/Rosetta/music/ptm/init.luau"], [3779, "src/Rosetta/music/s3m/init.luau"], [4015, "src/Rosetta/music/sf2/init.luau"], [4058, "src/Rosetta/music/stm/init.luau"], [4289, "src/Rosetta/music/ult/init.luau"], [4593, "src/Rosetta/music/umx/init.luau"], [4809, "src/Rosetta/music/xm/init.luau"], [5370, "src/Rosetta/music/xmi/init.luau"]], "music": [[8, "src/Rosetta/music/669/init.luau"], [214, "src/Rosetta/music/ahx/init.luau"], [265, "src/Rosetta/music/far/init.luau"], [494, "src/Rosetta/music/hmp/init.luau"], [758, "src/Rosetta/music/hvl/init.luau"], [809, "src/Rosetta/music/it/init.luau"], [1227, "src/Rosetta/music/it/Itsex.luau"], [1343, "src/Rosetta/music/med/init.luau"], [1990, "src/Rosetta/music/midi/init.luau"], [2133, "src/Rosetta/music/midi/Smf.luau"], [2544, "src/Rosetta/music/mod/init.luau"], [2897, "src/Rosetta/music/mtm/init.luau"], [3119, "src/Rosetta/music/mus/init.luau"], [3276, "src/Rosetta/music/okt/init.luau"], [3557, "src/Rosetta/music/ptm/init.luau"], [3779, "src/Rosetta/music/s3m/init.luau"], [4015, "src/Rosetta/music/sf2/init.luau"], [4058, "src/Rosetta/music/stm/init.luau"], [4289, "src/Rosetta/music/ult/init.luau"], [4593, "src/Rosetta/music/umx/init.luau"], [4809, "src/Rosetta/music/xm/init.luau"], [5370, "src/Rosetta/music/xmi/init.luau"]],
"ops": [[8, "src/Rosetta/ops/AudioOps.luau"], [457, "src/Rosetta/ops/LayerOps.luau"], [550, "src/Rosetta/ops/MeshOps/init.luau"], [1586, "src/Rosetta/ops/MeshOps/Greedy.luau"], [1753, "src/Rosetta/ops/MusicOps.luau"]], "ops": [[8, "src/Rosetta/ops/AudioOps.luau"], [457, "src/Rosetta/ops/LayerOps.luau"], [550, "src/Rosetta/ops/MeshOps/init.luau"], [1586, "src/Rosetta/ops/MeshOps/Greedy.luau"], [1753, "src/Rosetta/ops/MusicOps.luau"]],
"playlist": [[8, "src/Rosetta/playlist/m3u/init.luau"], [361, "src/Rosetta/playlist/pls/init.luau"], [539, "src/Rosetta/playlist/xspf/init.luau"]], "playlist": [[8, "src/Rosetta/playlist/m3u/init.luau"], [361, "src/Rosetta/playlist/pls/init.luau"], [539, "src/Rosetta/playlist/xspf/init.luau"]],
+2931 -48
View File
File diff suppressed because it is too large. Load diff
+2901 -29
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+4
View File
@@ -90,6 +90,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| model | robloxmesh | .mesh | yes | yes | skinning: true, lods: true, versions: "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" | `tests/model/robloxmesh.luau` | | model | robloxmesh | .mesh | yes | yes | skinning: true, lods: true, versions: "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" | `tests/model/robloxmesh.luau` |
| model | schematic | .schem .schematic .litematic | yes | yes | voxels: true, blocks: true, variants: "schem", "schematic", "litematic" | `tests/model/schematic.luau` | | model | schematic | .schem .schematic .litematic | yes | yes | voxels: true, blocks: true, variants: "schem", "schematic", "litematic" | `tests/model/schematic.luau` |
| model | smd | .smd | yes | yes | skins: true, animation: true | `tests/model/smd.luau` | | model | smd | .smd | yes | yes | skins: true, animation: true | `tests/model/smd.luau` |
| model | sourcemdl | .mdl | yes | - | skins: true, morph: true, animation: true, lods: true | `tests/model/sourcemdl.luau` |
| model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` |
| model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` |
| model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` |
@@ -148,6 +149,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| data | plist | .plist | yes | yes | binary: "read", ordered: true | `tests/data/plist.luau` | | data | plist | .plist | yes | yes | binary: "read", ordered: true | `tests/data/plist.luau` |
| data | snbt | .snbt | yes | yes | ordered: true, typed: true | `tests/data/snbt.luau` | | data | snbt | .snbt | yes | yes | ordered: true, typed: true | `tests/data/snbt.luau` |
| data | toml | .toml | yes | yes | ordered: true, dates: true | `tests/data/toml.luau` | | data | toml | .toml | yes | yes | ordered: true, dates: true | `tests/data/toml.luau` |
| data | vdf | .vdf .acf .res .kv | yes | yes | ordered: true, binary: true | `tests/data/vdf.luau` |
| data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | namespaces: true, streaming: true | `tests/data/xml.luau` | | data | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | namespaces: true, streaming: true | `tests/data/xml.luau` |
| data | yaml | .yaml .yml | yes | yes | ordered: true, multiDocument: true, anchors: true | `tests/data/yaml.luau` | | data | yaml | .yaml .yml | yes | yes | ordered: true, multiDocument: true, anchors: true | `tests/data/yaml.luau` |
| vector | svg | .svg | yes | yes | rasterize: true, text: false | `tests/vector/svg.luau` | | vector | svg | .svg | yes | yes | rasterize: true, text: false | `tests/vector/svg.luau` |
@@ -255,9 +257,11 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- codecs/model/Rbx: the Roblox instance tree and property values shared by model/rbxm and model/rbxmx. - codecs/model/Rbx: the Roblox instance tree and property values shared by model/rbxm and model/rbxmx.
- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...). New code. - codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...). New code.
- codecs/model/Sampler: Scene animation sampling, STEP / LINEAR (slerp) / CUBICSPLINE as in glTF 2.0 animations. New code. - codecs/model/Sampler: Scene animation sampling, STEP / LINEAR (slerp) / CUBICSPLINE as in glTF 2.0 animations. New code.
- codecs/model/SourceAnim: studio model animation data: the run-length coded mstudioanimvalue_t shorts (GoldSrc and
- codecs/model/Vrml: VRML97 / X3D scene-graph engine (classic and XML encodings) for model/vrml and model/x3d. - codecs/model/Vrml: VRML97 / X3D scene-graph engine (classic and XML encodings) for model/vrml and model/x3d.
- **text** - **text**
- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code.
- codecs/text/KeyValues: Valve KeyValues text (tier1/KeyValues.cpp of the Source SDK 2013, srctools' reading of it)
- codecs/text/Nbt: Minecraft's Named Binary Tag format and SNBT (Minecraft wiki "NBT format", wiki.vg "NBT"). - codecs/text/Nbt: Minecraft's Named Binary Tag format and SNBT (Minecraft wiki "NBT format", wiki.vg "NBT").
- codecs/text/Text: text decoding helpers: BOM stripping, Windows-1252 for text that is not UTF-8, line splitting. - codecs/text/Text: text decoding helpers: BOM stripping, Windows-1252 for text that is not UTF-8, line splitting.
- codecs/text/Url: RFC 3986 reference resolution (section 5.2), local-path classification and percent-encoding. - codecs/text/Url: RFC 3986 reference resolution (section 5.2), local-path classification and percent-encoding.
+4 -2
View File
@@ -33,9 +33,9 @@ src/Rosetta/
audio/ Aac Ac3 Adpcm Alac Ape ApeTag Flac Hively Mdct MidiRender Mpa Musepack Opus Pcm Qoa Resample audio/ Aac Ac3 Adpcm Alac Ape ApeTag Flac Hively Mdct MidiRender Mpa Musepack Opus Pcm Qoa Resample
SoundFont Stream Tracker Tta Vorbis VorbisComment WavPack SoundFont Stream Tracker Tta Vorbis VorbisComment WavPack
video/ Dsp H263 H264 Legacy Mpeg1 Mpeg2 Theora Video (the video codec registry) video/ Dsp H263 H264 Legacy Mpeg1 Mpeg2 Theora Video (the video codec registry)
text/ Json Nbt Text Url Xml text/ Json KeyValues Nbt Text Url Xml
font/ Bitmap Cff GlyphNames TrueType font/ Bitmap Cff GlyphNames TrueType
model/ Draco Mat4 MeshFlatten Minecraft Polygon Rbx Rig Sampler Vrml model/ Draco Mat4 MeshFlatten Minecraft Polygon Rbx Rig Sampler SourceAnim Vrml
host/ host (layer 2) runtime adapters; only the api uses them host/ host (layer 2) runtime adapters; only the api uses them
Types.luau types (layer 1) standard types + constructors Types.luau types (layer 1) standard types + constructors
core/ core (layer 0) Adler32 Base64 Bits Bytes Crc16 Crc32 Err Input core/ core (layer 0) Adler32 Base64 Bits Bytes Crc16 Crc32 Err Input
@@ -242,7 +242,9 @@ them. Anything generic goes down a layer and is called:
| GPU texture pixels (BCn, ETC / EAC, uncompressed texel layouts, half floats) | `codecs/image/Texture` (`Bcn`, `Etc`, `Texel`, `Half`) | | GPU texture pixels (BCn, ETC / EAC, uncompressed texel layouts, half floats) | `codecs/image/Texture` (`Bcn`, `Etc`, `Texel`, `Half`) |
| animation channels sampled at a time; game-model frames, joints and skins -> Scene | `codecs/model/Sampler`, `codecs/model/Rig` | | animation channels sampled at a time; game-model frames, joints and skins -> Scene | `codecs/model/Sampler`, `codecs/model/Rig` |
| polygons with holes -> triangles | `codecs/model/Polygon` | | polygons with holes -> triangles | `codecs/model/Polygon` |
| studio model animation values (GoldSrc / Source run-length shorts, Quaternion48 / 64, bone records) | `codecs/model/SourceAnim` |
| NBT / SNBT values; Minecraft block states and colours | `codecs/text/Nbt`, `codecs/model/Minecraft` | | NBT / SNBT values; Minecraft block states and colours | `codecs/text/Nbt`, `codecs/model/Minecraft` |
| Valve KeyValues (text, binary, the BSP entity lump) | `codecs/text/KeyValues` |
| Roblox instance trees and property values | `codecs/model/Rbx` | | Roblox instance trees and property values | `codecs/model/Rbx` |
| bitmap fonts as a Font; PostScript glyph names | `codecs/font/Bitmap`, `codecs/font/GlyphNames` | | bitmap fonts as a Font; PostScript glyph names | `codecs/font/Bitmap`, `codecs/font/GlyphNames` |
| CRC-16 (XMODEM / ARC), xxHash32 | `core/Crc16`, `codecs/compress/Xxh32` | | CRC-16 (XMODEM / ARC), xxHash32 | `core/Crc16`, `codecs/compress/Xxh32` |
+22 -1
View File
@@ -306,6 +306,26 @@ local xml = assert(F.saveString(p, { format = "plist" }))
assert(string.find(xml, "<key>CFBundleName</key>\n\t<string>Demo</string>", 1, true)) assert(string.find(xml, "<key>CFBundleName</key>\n\t<string>Demo</string>", 1, true))
``` ```
## VDF (Valve KeyValues)
`.vdf`, `.acf`, `.res` and other KeyValues files decode to `Types.object`s of strings; a key that repeats gets an array
of its values (`duplicates = "last"` / `"first"` keep one). `[$CONDITION]`s are evaluated for a PC (`defines =
{ OSX = true }` changes the flags, `defines = false` keeps every pair), `#include` / `#base` files come through
`resolve`, `escapes = false` reads backslashes as they are. `pairs = true` gives the ordered pair list of
`codecs/text/KeyValues` (`{ key, value, cond?, type? }`), which keeps everything. Binary KeyValues (`shortcuts.vdf`)
are sniffed; encode with `binary = true`.
```luau
local acf = assert(F.data.load('"AppState"\n{\n\t"appid"\t"440"\n\t"x" "1"\n\t"x" "2"\n}\n', { format = "vdf" }))
assert(acf.AppState.appid == "440" and acf.AppState.x[2] == "2")
local text = assert(F.saveString(acf, { format = "vdf" }))
assert(string.find(text, '\t"x"\t"1"\n\t"x"\t"2"\n', 1, true))
local pairs = assert(F.data.load('"r" { "a" "1" [$X360] }', { format = "vdf", pairs = true, defines = false }))
assert(pairs[1].value[1].cond == "$X360")
local bin = assert(F.save(acf, nil, { format = "vdf", binary = true }))
assert(F.data.load(bin, { format = "vdf" }).AppState.appid == "440")
```
## Save and convert ## Save and convert
Data values have no `kind`, so saving needs `opts.format` or a destination extension (an `XmlNode` document too): Data values have no `kind`, so saving needs `opts.format` or a destination extension (an `XmlNode` document too):
@@ -337,6 +357,7 @@ is an error there), CSV needs rows, INI needs sections of scalars, JSON has no b
| toml (`.toml`) | yes | yes | ordered tables, Dates | | toml (`.toml`) | yes | yes | ordered tables, Dates |
| csv (`.csv`, `.tsv`) | yes | yes | rows (arrays or records) | | csv (`.csv`, `.tsv`) | yes | yes | rows (arrays or records) |
| ini (`.ini`, `.cfg`, `.conf`, `.desktop`) | yes | yes | sections of strings | | ini (`.ini`, `.cfg`, `.conf`, `.desktop`) | yes | yes | sections of strings |
| vdf (`.vdf`, `.acf`, `.res`, `.kv`) | text + binary | text + binary | ordered objects of strings, or pairs |
| msgpack (`.msgpack`, `.mpk`) | yes | yes | values, buffers, Dates | | msgpack (`.msgpack`, `.mpk`) | yes | yes | values, buffers, Dates |
| cbor (`.cbor`) | yes | yes | values, buffers, Dates, tagged values | | cbor (`.cbor`) | yes | yes | values, buffers, Dates, tagged values |
| plist (`.plist`) | XML + binary | XML | values, buffers, Dates | | plist (`.plist`) | XML + binary | XML | values, buffers, Dates |
@@ -351,7 +372,7 @@ Full capability list: [FORMATS.md](../FORMATS.md).
- Luau has one number type: `1.0` reads back as `1`, and TOML / plist write integral floats as integers. Integers - Luau has one number type: `1.0` reads back as `1`, and TOML / plist write integral floats as integers. Integers
past 2^53 need `bigInts = "string"` to survive. past 2^53 need `bigInts = "string"` to survive.
- An empty plain table `{}` is written as an array; use `F.Types.object()` (or `emptyTable = "object"`) for `{}`. - An empty plain table `{}` is written as an array; use `F.Types.object()` (or `emptyTable = "object"`) for `{}`.
- Text formats sniff weakly: give `format` (or a file name) for YAML, TOML, INI, CSV, MessagePack and CBOR without - Text formats sniff weakly: give `format` (or a file name) for YAML, TOML, INI, VDF, CSV, MessagePack and CBOR without
its self-describe tag. its self-describe tag.
- XML whitespace-only text between elements is dropped by default (`whitespace = true` keeps it); text is never - XML whitespace-only text between elements is dropped by default (`whitespace = true` keeps it); text is never
trimmed otherwise. trimmed otherwise.
+42
View File
@@ -528,6 +528,47 @@ local again = assert(F.save(map, nil, { format = "buildmap" }))
assert(buffer.tostring(again) == buffer.tostring(buildmapBytes)) assert(buffer.tostring(again) == buffer.tostring(buildmapBytes))
local Build = F.format("buildmap") -- the floor height under a point, slopes included local Build = F.format("buildmap") -- the floor height under a point, slopes included
assert(Build.slopeZ(level, 0, true, 100, 100) == level.sectors[1].floorz) assert(Build.slopeZ(level, 0, true, 100, 100) == level.sectors[1].floorz)
## Source engine models (MDL v44-49)
`sourcemdl` reads Source studio models (Half-Life 2 to CS:GO-era v44-49; GoldSrc v10 stays `mdl`). The geometry is
in sibling files found through `files` / `resolve` (or `vvd` / `vtx` / `phy` / `ani` buffers): `<name>.vvd`
vertices, `<name>.dx90.vtx` (else `.dx80` / `.sw` / `.vtx`) strips, optional `<name>.phy` collision and the `.ani`
animation blocks; `<name>` is the stem of `opts.name`, else of the name stored in the MDL. Without them the Scene has
the skeleton and the animations only (`meta.source.warnings` says what was missing).
- Bones become a skin (`poseToBone` as the inverse bind matrices); procedural bones (jiggle, aim-at, ...) are data in
the joint nodes' `extras.procedural`.
- Each body part model is a mesh (one primitive per studio mesh); `bodies` picks the model per body part for the
nodes (default 1), the others are in `scene.meshes` and `meta.source.bodyParts`. `lod` picks the LOD of
`prim.indices`; every LOD's indices are in `prim.extras.lods`.
- Flexes are morph targets (stereo flexes split by side), named in `mesh.extras.targetNames`; attachments are nodes
under their bones; hitboxes, sequences (activities, events, blends), pose parameters and flex rules are in
`meta.source`.
- Each animation (decoded from the run-length / Quaternion48 / 64 data, sections and `.ani` blocks; delta
animations added to the rest pose) is named after the first sequence that plays it.
- Materials: each texture name is looked up as `materials/<cdmaterials dir><name>.vmt`; `$basetexture` / `$bumpmap`
become `.vtf` texture URIs (`F.model.loadTextures` with a `resolve` for the game's files decodes them),
`$translucent` / `$alphatest` / `$nocull` / `$color` map to the material, and every parameter is kept in
`material.extras.vmt`.
```luau
local files = {
["model.vvd"] = sourceVvdBytes,
["model.dx90.vtx"] = sourceVtxBytes,
["model.phy"] = sourcePhyBytes,
["materials/models/test/skin_a.vmt"] = skinVmtText,
}
local model = assert(F.model.load(sourceMdlBytes, { name = "model.mdl", files = files }))
local src = model.meta.source
assert(src.format == "sourcemdl" and src.version == 49 and model.meta.up == "z")
assert(#model.skins[1].joints == 6)
local body = model.meshes[src.bodyParts[1].models[1].mesh]
assert(#body.primitives == 2 and body.extras.targetNames[1] == "AU1L")
assert(#body.primitives[1].extras.lods == 2)
assert(model.animations[1].name == "idle" and src.sequences[1].activity == "ACT_IDLE")
local skinA = model.materials[1]
assert(model.textures[skinA.baseColorTexture.texture].uri == "materials/models/test/skin_a.vtf")
assert(#src.physics.solids[1].hulls == 2)
``` ```
## Blitz3D (B3D) ## Blitz3D (B3D)
@@ -769,6 +810,7 @@ assert(back.meshes[1].primitives[1].indices.count == 3)
| STEP | via the CAD plug-in | | see [cad.md](cad.md) | | STEP | via the CAD plug-in | | see [cad.md](cad.md) |
| MD2, MD3, MDL, MD5, BSP | yes | - | game models and maps: see "Game models" above | | MD2, MD3, MDL, MD5, BSP | yes | - | game models and maps: see "Game models" above |
| Build engine MAP (v7-9) | yes | yes | sloped sectors, walls, sprites as nodes, raw tables in `meta.build`; see "Build engine maps" above | | Build engine MAP (v7-9) | yes | yes | sloped sectors, walls, sprites as nodes, raw tables in `meta.build`; see "Build engine maps" above |
| Source MDL (v44-49) + VVD / VTX / PHY | yes | - | skeleton, body parts, LODs, flexes, animations, VMT materials: see above |
| SMD | yes | yes | Valve studiomdl data | | SMD | yes | yes | Valve studiomdl data |
| Roblox `.mesh` (robloxmesh) | yes | yes | see [roblox.md](roblox.md) | | Roblox `.mesh` (robloxmesh) | yes | yes | see [roblox.md](roblox.md) |
| Roblox `.rbxm` / `.rbxl`, `.rbxmx` / `.rbxlx` | as an `RbxTree` | yes | instance trees with typed properties: see [roblox.md](roblox.md) | | Roblox `.rbxm` / `.rbxl`, `.rbxmx` / `.rbxlx` | as an `RbxTree` | yes | instance trees with typed properties: see [roblox.md](roblox.md) |
+25 -1
View File
@@ -896,7 +896,7 @@ local list: { Entry } = {
path = "model/mdl", path = "model/mdl",
extensions = { "mdl" }, extensions = { "mdl" },
mime = { "model/x-mdl" }, mime = { "model/x-mdl" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" }, deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/SourceAnim" },
caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true }, caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true },
load = function() load = function()
return require("@rosetta/model/mdl") return require("@rosetta/model/mdl")
@@ -1034,6 +1034,18 @@ local list: { Entry } = {
return require("@rosetta/model/smd") return require("@rosetta/model/smd")
end, end,
}, },
{
name = "sourcemdl",
category = "model",
path = "model/sourcemdl",
extensions = { "mdl" },
mime = { "model/x-source-mdl" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Half", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/SourceAnim", "codecs/text/KeyValues" },
caps = { decode = true, encode = false, skins = true, morph = true, animation = true, lods = true },
load = function()
return require("@rosetta/model/sourcemdl")
end,
},
{ {
name = "stl", name = "stl",
category = "model", category = "model",
@@ -1730,6 +1742,18 @@ local list: { Entry } = {
return require("@rosetta/data/toml") return require("@rosetta/data/toml")
end, end,
}, },
{
name = "vdf",
category = "data",
path = "data/vdf",
extensions = { "vdf", "acf", "res", "kv" },
mime = { "text/x-vdf" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/KeyValues" },
caps = { decode = true, encode = true, ordered = true, binary = true },
load = function()
return require("@rosetta/data/vdf")
end,
},
{ {
name = "xml", name = "xml",
category = "data", category = "data",
+219
View File
@@ -0,0 +1,219 @@
--!strict
--!native
-- codecs/model/SourceAnim: studio model animation data: the run-length coded mstudioanimvalue_t shorts (GoldSrc and
-- Source), Source mstudioanim_t bone records with Quaternion48 / Quaternion64 / Vector48, from the Source SDK 2013
-- studio.h / bone_setup.cpp layouts and SourceIO (MIT) notes; no code taken.
local Half = require("@rosetta/codecs/image/Half")
local SourceAnim = {}
local readu8, readi16, readu16, readu32 = buffer.readu8, buffer.readi16, buffer.readu16, buffer.readu32
local sqrt, sin, cos = math.sqrt, math.sin, math.cos
local HALF = Half.TABLE
export type Bone = {
pos: { number },
quat: { number },
rot: { number }, -- radian euler x, y, z
posScale: { number },
rotScale: { number },
}
export type Track = { pos: { number }, rot: { number } } -- frames * 3 / frames * 4 (quaternion x, y, z, w)
-- ExtractAnimValue: frame k of a run list ({ valid, total } then valid shorts); a frame past valid repeats
-- value[valid] (with valid = 0 that is the run header itself, as the engine reads it)
function SourceAnim.value(b: buffer, at: number, limit: number, k: number): number?
local p = at
for _ = 1, 65536 do
if p + 2 > limit then
return nil
end
local valid, total = readu8(b, p), readu8(b, p + 1)
if total == 0 then
return nil
end
if total > k then
local idx = if valid > k then k + 1 else valid
if p + idx * 2 + 2 > limit then
return nil
end
return readi16(b, p + idx * 2)
end
k -= total
p += (valid + 1) * 2
end
return nil
end
function SourceAnim.values(b: buffer, at: number, limit: number, count: number): { number }?
local out = table.create(count, 0)
local p, f = at, 0
while f < count do
if p + 2 > limit then
return nil
end
local valid, total = readu8(b, p), readu8(b, p + 1)
if total == 0 or p + 2 + valid * 2 > limit then
return nil
end
local n = math.min(total, count - f)
for i = 0, n - 1 do
local idx = if i < valid then i + 1 else valid
out[f + i + 1] = readi16(b, p + idx * 2)
end
f += n
p += (valid + 1) * 2
end
return out
end
-- Quaternion48: x, y u16 (bias 32768), z 15 bits (bias 16384), w sign bit
function SourceAnim.quat48(b: buffer, o: number): (number, number, number, number)
local x = (readu16(b, o) - 32768) / 32768
local y = (readu16(b, o + 2) - 32768) / 32768
local zw = readu16(b, o + 4)
local z = (zw % 32768 - 16384) / 16384
local w = sqrt(math.max(0, 1 - x * x - y * y - z * z))
return x, y, z, if zw >= 32768 then -w else w
end
-- Quaternion64: x, y, z 21 bits each (bias 1048576, scale 1 / 1048576.5), w sign bit 63
function SourceAnim.quat64(b: buffer, o: number): (number, number, number, number)
local lo, hi = readu32(b, o), readu32(b, o + 4)
local xs = lo % 2097152
local ys = (hi % 1024) * 2048 + (lo - xs) / 2097152
local zs = math.floor(hi / 1024) % 2097152
local x, y, z = (xs - 1048576) / 1048576.5, (ys - 1048576) / 1048576.5, (zs - 1048576) / 1048576.5
local w = sqrt(math.max(0, 1 - x * x - y * y - z * z))
return x, y, z, if hi >= 0x80000000 then -w else w
end
function SourceAnim.vec48(b: buffer, o: number): (number, number, number)
return HALF[readu16(b, o)], HALF[readu16(b, o + 2)], HALF[readu16(b, o + 4)]
end
-- AngleQuaternion (RadianEuler: x roll, y pitch, z yaw)
function SourceAnim.angles(x: number, y: number, z: number): (number, number, number, number)
local sy, cy = sin(z / 2), cos(z / 2)
local sp, cp = sin(y / 2), cos(y / 2)
local sr, cr = sin(x / 2), cos(x / 2)
return sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy, cr * cp * cy + sr * sp * sy
end
local RAWPOS, RAWROT, ANIMPOS, ANIMROT, DELTA, RAWROT2 = 0x01, 0x02, 0x04, 0x08, 0x10, 0x20
local function channels(b: buffer, vp: number, limit: number, frames: number, scale: { number }): ({ { number }? }?)
if vp + 6 > limit then
return nil
end
local out: { { number }? } = {}
for k = 0, 2 do
local off = readi16(b, vp + k * 2)
if off > 0 then
local v = SourceAnim.values(b, vp + off, limit, frames)
if not v then
return nil
end
local s = scale[k + 1]
for i = 1, frames do
v[i] *= s
end
out[k + 1] = v
end
end
return out
end
-- mstudioanim_t chain at `at` (bone u8, flags u8, next i16, data): `frames` frames of every bone it lists, as the
-- engine's CalcBoneQuaternion / CalcBonePosition (delta records add nothing of the bone's rest pose)
function SourceAnim.decode(b: buffer, at: number, limit: number, bones: { Bone }, frames: number): ({ [number]: Track }?, string?)
local out: { [number]: Track } = {}
local p = at
for _ = 1, #bones + 1 do
if p + 4 > limit then
return nil, "truncated animation"
end
local bone, flags, nxt = readu8(b, p), readu8(b, p + 1), readi16(b, p + 2)
if bone == 255 then
break
end
local bn = bones[bone + 1]
if not bn then
return nil, "animation bone out of range"
end
local delta = bit32.band(flags, DELTA) ~= 0
local d = p + 4
local rot = table.create(frames * 4, 0)
if bit32.band(flags, RAWROT) ~= 0 then
if d + 6 > limit then
return nil, "truncated animation"
end
local x, y, z, w = SourceAnim.quat48(b, d)
for f = 0, frames - 1 do
rot[f * 4 + 1], rot[f * 4 + 2], rot[f * 4 + 3], rot[f * 4 + 4] = x, y, z, w
end
d += 6
elseif bit32.band(flags, RAWROT2) ~= 0 then
if d + 8 > limit then
return nil, "truncated animation"
end
local x, y, z, w = SourceAnim.quat64(b, d)
for f = 0, frames - 1 do
rot[f * 4 + 1], rot[f * 4 + 2], rot[f * 4 + 3], rot[f * 4 + 4] = x, y, z, w
end
d += 8
elseif bit32.band(flags, ANIMROT) ~= 0 then
local ch = channels(b, d, limit, frames, bn.rotScale)
if not ch then
return nil, "bad rotation values"
end
local bx, by, bz = if delta then 0 else bn.rot[1], if delta then 0 else bn.rot[2], if delta then 0 else bn.rot[3]
local cx, cy, cz = ch[1], ch[2], ch[3]
for f = 0, frames - 1 do
local x, y, z, w = SourceAnim.angles(bx + (if cx then cx[f + 1] else 0), by + (if cy then cy[f + 1] else 0), bz + (if cz then cz[f + 1] else 0))
rot[f * 4 + 1], rot[f * 4 + 2], rot[f * 4 + 3], rot[f * 4 + 4] = x, y, z, w
end
d += 6
else
local q = if delta then { 0, 0, 0, 1 } else bn.quat
for f = 0, frames - 1 do
rot[f * 4 + 1], rot[f * 4 + 2], rot[f * 4 + 3], rot[f * 4 + 4] = q[1], q[2], q[3], q[4]
end
end
local pos = table.create(frames * 3, 0)
if bit32.band(flags, RAWPOS) ~= 0 then
if d + 6 > limit then
return nil, "truncated animation"
end
local x, y, z = SourceAnim.vec48(b, d)
for f = 0, frames - 1 do
pos[f * 3 + 1], pos[f * 3 + 2], pos[f * 3 + 3] = x, y, z
end
elseif bit32.band(flags, ANIMPOS) ~= 0 then
local ch = channels(b, d, limit, frames, bn.posScale)
if not ch then
return nil, "bad position values"
end
local bx, by, bz = if delta then 0 else bn.pos[1], if delta then 0 else bn.pos[2], if delta then 0 else bn.pos[3]
local cx, cy, cz = ch[1], ch[2], ch[3]
for f = 0, frames - 1 do
pos[f * 3 + 1] = bx + (if cx then cx[f + 1] else 0)
pos[f * 3 + 2] = by + (if cy then cy[f + 1] else 0)
pos[f * 3 + 3] = bz + (if cz then cz[f + 1] else 0)
end
elseif not delta then
for f = 0, frames - 1 do
pos[f * 3 + 1], pos[f * 3 + 2], pos[f * 3 + 3] = bn.pos[1], bn.pos[2], bn.pos[3]
end
end
out[bone + 1] = { pos = pos, rot = rot }
if nxt <= 0 then
break
end
p += nxt
end
return out, nil
end
return SourceAnim
@@ -0,0 +1,303 @@
--!strict
-- codecs/text/KeyValues/Binary: binary KeyValues (KeyValues::ReadAsBinary; Steam shortcuts.vdf / appinfo values).
-- Types: 0 block, 1 string, 2 int32, 3 float32, 4 pointer, 5 wide string (UTF-16LE), 6 color, 7 uint64, 8 end,
-- 10 int64, 11 end (alternative). 64-bit values are numbers below 2^53, decimal strings above.
local Err = require("@rosetta/core/Err")
local Text = require("@rosetta/codecs/text/Text")
local Binary = {}
export type Pair = {
key: string,
value: any, -- string | number | Block
cond: string?, -- text: the [$CONDITION] kept when not evaluated
type: string?, -- binary: "int32" | "float32" | "pointer" | "wstring" | "color" | "uint64" | "int64" (nil: string / block)
}
export type Block = { Pair }
local readu8, readu32, readi32, readf32 = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32
local TYPES: { [number]: string } = { [2] = "int32", [3] = "float32", [4] = "pointer", [5] = "wstring", [6] = "color", [7] = "uint64", [10] = "int64" }
local CODES: { [string]: number } = { int32 = 2, float32 = 3, pointer = 4, wstring = 5, color = 6, uint64 = 7, int64 = 10 }
-- (hi, lo) u32 halves -> number below 2^53, else the decimal digits
local function u64text(hi: number, lo: number): number | string
if hi < 2 ^ 21 then
return hi * 4294967296 + lo
end
local digits: { string } = {}
-- base 10^6 long division over 16-bit limbs
local limbs = { hi // 65536, hi % 65536, lo // 65536, lo % 65536 }
while limbs[1] + limbs[2] + limbs[3] + limbs[4] > 0 do
local rem = 0
for i = 1, 4 do
local cur = rem * 65536 + limbs[i]
limbs[i] = cur // 1000000
rem = cur % 1000000
end
table.insert(digits, 1, string.format("%06d", rem))
end
local s = string.gsub(table.concat(digits), "^0+", "")
return if s == "" then 0 else s
end
-- number or decimal string -> (hi, lo), two's complement for negatives
local function u64parts(v: any): (number?, number?)
if type(v) == "number" then
if v ~= v or math.abs(v) >= 2 ^ 63 then
return nil, nil
end
v = math.floor(v)
local m = math.abs(v)
local hi = m // 4294967296
local lo = m - hi * 4294967296
if v < 0 then
return (4294967295 - hi + (if lo == 0 then 1 else 0)) % 4294967296, (4294967296 - lo) % 4294967296
end
return hi, lo
elseif type(v) == "string" then
local neg, digits = string.match(v, "^(%-?)(%d+)$")
if not digits or #digits > 20 then
return nil, nil
end
local limbs = { 0, 0, 0, 0 } -- 16-bit, most significant first
for i = 1, #digits do
local carry = tonumber(string.sub(digits, i, i)) :: number
for k = 4, 1, -1 do
local cur = limbs[k] * 10 + carry
limbs[k] = cur % 65536
carry = cur // 65536
end
if carry > 0 then
return nil, nil
end
end
if neg == "-" then
local carry = 1
for k = 4, 1, -1 do
local cur = (65535 - limbs[k]) + carry
limbs[k] = cur % 65536
carry = cur // 65536
end
end
return limbs[1] * 65536 + limbs[2], limbs[3] * 65536 + limbs[4]
end
return nil, nil
end
function Binary.read(buf: buffer | string, offset: number?, length: number?, opts: { maxDepth: number? }?): (Block?, Err.Err?)
local b: buffer = if type(buf) == "string" then buffer.fromstring(buf) else buf
if type(b) ~= "buffer" then
return nil, Err.new(Err.ARG, "KeyValues.readBinary: expected a buffer")
end
local o = offset or 0
local e = o + (length or (buffer.len(b) - o))
if o < 0 or e > buffer.len(b) or e < o then
return nil, Err.new(Err.ARG, "KeyValues.readBinary: range out of the buffer")
end
local maxDepth = opts and opts.maxDepth or 256
local p = o
local function cstr(): string?
local q = p
while q < e and readu8(b, q) ~= 0 do
q += 1
end
if q >= e then
return nil
end
local s = buffer.readstring(b, p, q - p)
p = q + 1
return s
end
local root: Block = {}
local stack: { Block } = { root }
while true do
if p >= e then
if #stack > 1 then
return nil, Err.new(Err.TRUNCATED, "unclosed block", p - o)
end
break
end
local t = readu8(b, p)
p += 1
if t == 8 or t == 11 then
if #stack == 1 then
break
end
table.remove(stack)
else
local cur = stack[#stack]
local key = cstr()
if not key then
return nil, Err.new(Err.TRUNCATED, "key", p - o)
end
if t == 0 then
if #stack >= maxDepth then
return nil, Err.new(Err.LIMIT, "nesting deeper than maxDepth", p - o)
end
local sub: Block = {}
table.insert(cur, { key = key, value = sub })
table.insert(stack, sub)
elseif t == 1 then
local v = cstr()
if not v then
return nil, Err.new(Err.TRUNCATED, "string value", p - o)
end
table.insert(cur, { key = key, value = v })
elseif t == 5 then
local q = p
while q + 1 < e and buffer.readu16(b, q) ~= 0 do
q += 2
end
if q + 1 >= e then
return nil, Err.new(Err.TRUNCATED, "wide string value", p - o)
end
table.insert(cur, { key = key, value = Text.utf16(b, p, q - p), type = "wstring" })
p = q + 2
elseif t == 2 or t == 3 or t == 4 or t == 6 then
if p + 4 > e then
return nil, Err.new(Err.TRUNCATED, "value", p - o)
end
local v = if t == 2 then readi32(b, p) elseif t == 3 then readf32(b, p) else readu32(b, p)
table.insert(cur, { key = key, value = v, type = TYPES[t] })
p += 4
elseif t == 7 or t == 10 then
if p + 8 > e then
return nil, Err.new(Err.TRUNCATED, "value", p - o)
end
local lo, hi = readu32(b, p), readu32(b, p + 4)
local v: number | string
if t == 10 and hi >= 2 ^ 31 then
-- negative: magnitude of the two's complement
local nlo = (4294967296 - lo) % 4294967296
local nhi = 4294967295 - hi + (if lo == 0 then 1 else 0)
local m = u64text(nhi, nlo)
v = if type(m) == "number" then -m else "-" .. m
else
v = u64text(hi, lo)
end
table.insert(cur, { key = key, value = v, type = TYPES[t] })
p += 8
else
return nil, Err.new(Err.CORRUPT, "unknown value type " .. t, p - o - 1)
end
end
end
return root, nil
end
local function utf16(s: string): string
local out: { string } = {}
for _, c in utf8.codes(s) do
if c >= 0x10000 then
local v = c - 0x10000
local hs = 0xD800 + v // 1024
table.insert(out, string.char(hs % 256, hs // 256))
local lo = 0xDC00 + v % 1024
table.insert(out, string.char(lo % 256, lo // 256))
else
table.insert(out, string.char(c % 256, c // 256))
end
end
return table.concat(out)
end
local function writeBlock(blk: Block, out: { string }, depth: number): string?
if depth > 256 then
return "nesting deeper than 256"
end
for _, pr in blk do
if type(pr) ~= "table" or type(pr.key) ~= "string" or string.find(pr.key, "%z") then
return "a pair needs a string key without NUL"
end
local v: any = pr.value
local k = pr.key .. "\0"
if type(v) == "table" then
table.insert(out, "\0" .. k)
local err = writeBlock(v, out, depth + 1)
if err then
return err
end
table.insert(out, "\8")
else
local code = if pr.type then CODES[pr.type] else (if type(v) == "number" then (if v % 1 == 0 and v >= -2 ^ 31 and v < 2 ^ 31 then 2 else 3) else 1)
if not code then
return "unknown value type " .. tostring(pr.type)
end
local w = buffer.create(8)
if code == 1 then
if type(v) ~= "string" or string.find(v, "%z") then
return "string value expected for key " .. pr.key
end
table.insert(out, "\1" .. k .. v .. "\0")
elseif code == 5 then
if type(v) ~= "string" or not utf8.len(v) then
return "UTF-8 string value expected for key " .. pr.key
end
table.insert(out, "\5" .. k .. utf16(v) .. "\0\0")
elseif code == 7 or code == 10 then
local hi, lo = u64parts(v)
if not hi then
return "64-bit value expected for key " .. pr.key
end
buffer.writeu32(w, 0, lo :: number)
buffer.writeu32(w, 4, hi :: number)
table.insert(out, string.char(code) .. k .. buffer.readstring(w, 0, 8))
else
if type(v) ~= "number" then
return "number value expected for key " .. pr.key
end
if code == 3 then
buffer.writef32(w, 0, v)
elseif code == 2 then
if v % 1 ~= 0 or v < -2 ^ 31 or v >= 2 ^ 31 then
return "int32 out of range for key " .. pr.key
end
buffer.writei32(w, 0, v)
else
if v % 1 ~= 0 or v < 0 or v >= 2 ^ 32 then
return "u32 out of range for key " .. pr.key
end
buffer.writeu32(w, 0, v)
end
table.insert(out, string.char(code) .. k .. buffer.readstring(w, 0, 4))
end
end
end
return nil
end
function Binary.write(blk: Block): (buffer?, Err.Err?)
if type(blk) ~= "table" then
return nil, Err.new(Err.ARG, "KeyValues.writeBinary: expected a pair list")
end
local out: { string } = {}
local err = writeBlock(blk, out, 0)
if err then
return nil, Err.new(Err.ARG, err)
end
table.insert(out, "\8")
return buffer.fromstring(table.concat(out)), nil
end
-- a type byte 0 / 1 / 2 then a printable NUL-terminated key
function Binary.sniff(b: buffer, o: number, n: number): boolean
if n < 3 then
return false
end
local t = readu8(b, o)
if t ~= 0 and t ~= 1 and t ~= 2 then
return false
end
for i = 1, math.min(n - 1, 64) do
local c = readu8(b, o + i)
if c == 0 then
return i > 1
elseif c < 32 then
return false
end
end
return false
end
return Binary
+555
View File
@@ -0,0 +1,555 @@
--!strict
-- codecs/text/KeyValues: Valve KeyValues text (tier1/KeyValues.cpp of the Source SDK 2013, srctools' reading of it)
-- and binary KeyValues (Steam appinfo / shortcuts.vdf). Pair lists keep order, duplicates and [$CONDITION]s;
-- #include / #base go through opts.resolve; the BSP entity lump ({ ... } blocks without keys) too.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Binary = require("@rosetta/codecs/text/KeyValues/Binary")
local KeyValues = {}
export type Pair = Binary.Pair
export type Block = Binary.Block
export type ParseOptions = {
escapes: boolean?, -- \n \t \\ \" ... in quoted strings, default true
-- [$X] conditions: the flags that are true (case-insensitive names, without $); default { WIN32 = true }, the
-- other SDK names (X360, PS3, GAMECONSOLE, OSX, LINUX, POSIX, WINDOWS, DECK) false; false keeps every pair with
-- its cond
defines: ({ [string]: boolean } | false)?,
resolve: ((name: string) -> (buffer | string)?)?, -- #include / #base files
maxDepth: number?, -- default 256
}
export type WriteOptions = {
escapes: boolean?, -- default true
indent: string?, -- default "\t"
}
export type ObjectOptions = {
duplicates: ("array" | "last" | "first")?, -- default "array": a repeated key's values become an array
}
local DEFAULT_DEFINES: { [string]: boolean } = { win32 = true }
local ESCAPE: { [string]: string } = { n = "\n", t = "\t", v = "\v", b = "\b", r = "\r", f = "\f", a = "\a", ["\\"] = "\\", ["?"] = "?", ["'"] = "'", ['"'] = '"' }
type Lexer = { s: string, i: number, n: number, escapes: boolean }
-- kind: "s" string, "{", "}", "[" condition (its text), nil at the end; err on an unterminated string
local function token(lx: Lexer): (string?, string?, number, string?)
local s, n = lx.s, lx.n
local i = lx.i
while true do
local a = string.find(s, "[^ \t\r\n\f\v]", i)
if not a then
lx.i = n + 1
return nil, nil, n, nil
end
i = a
if string.sub(s, i, i + 1) == "//" then
local e = string.find(s, "\n", i, true)
if not e then
lx.i = n + 1
return nil, nil, n, nil
end
i = e + 1
else
break
end
end
local c = string.sub(s, i, i)
if c == "{" or c == "}" then
lx.i = i + 1
return c, nil, i - 1, nil
elseif c == '"' then
local start = i
i += 1
if not lx.escapes then
local e = string.find(s, '"', i, true)
if not e then
lx.i = n + 1
return nil, nil, start - 1, "unterminated string"
end
lx.i = e + 1
return "s", string.sub(s, i, e - 1), start - 1, nil
end
local parts: { string } = {}
while true do
local e = string.find(s, '["\\]', i)
if not e then
lx.i = n + 1
return nil, nil, start - 1, "unterminated string"
end
table.insert(parts, string.sub(s, i, e - 1))
if string.sub(s, e, e) == '"' then
lx.i = e + 1
return "s", table.concat(parts), start - 1, nil
end
local x = string.sub(s, e + 1, e + 1)
local r = ESCAPE[x]
if r then
table.insert(parts, r)
i = e + 2
else
table.insert(parts, "\\")
i = e + 1
end
end
elseif c == "[" then
local e = string.find(s, "]", i, true)
local sp = string.find(s, "[\r\n]", i)
if e and (not sp or sp > e) then
lx.i = e + 1
return "[", string.sub(s, i + 1, e - 1), i - 1, nil
end
end
local e = string.find(s, '[ \t\r\n\f\v"{}]', i)
local stop = if e then e - 1 else n
lx.i = stop + 1
return "s", string.sub(s, i, stop), i - 1, nil
end
-- "$A || !$B && $C": || of && terms; a term is [!]$NAME (KeyValues::EvaluateConditional)
function KeyValues.condition(cond: string, defines: { [string]: boolean }?): boolean
local d = defines or DEFAULT_DEFINES
local function flag(name: string): boolean
local l = string.lower(name)
for k, v in d do
if string.lower(k) == l then
return v == true
end
end
return false
end
local any = false
for alt in string.gmatch(cond .. "||", "(.-)||") do
local all = true
for term in string.gmatch(alt .. "&&", "(.-)&&") do
local neg, name = string.match(term, "^%s*(!?)%s*%$?([%w_]*)%s*$")
if not name then
all = false
else
local v = flag(name :: string)
if neg == "!" then
v = not v
end
all = all and v
end
end
any = any or all
end
return any
end
local function keyEq(a: string, b: string): boolean
return a == b or string.lower(a) == string.lower(b)
end
local function parseText(text: string, opts: ParseOptions?, depth0: number): (Block?, Err.Err?)
local o: ParseOptions = opts or {}
local lx: Lexer = { s = text, i = 1, n = #text, escapes = o.escapes ~= false }
if string.sub(text, 1, 3) == "\239\187\191" then
lx.i = 4
end
local defines: { [string]: boolean }? = nil
local evaluate = o.defines ~= false
if type(o.defines) == "table" then
defines = o.defines
end
local maxDepth = o.maxDepth or 256
local root: Block = {}
local stack: { Block } = { root }
local skipping = 0 -- depth inside a block whose condition failed
local canReplace = false
local includes: { { kind: string, name: string } } = {}
while true do
local kind, v, at, terr = token(lx)
if terr then
return nil, Err.new(Err.TRUNCATED, terr, at)
end
if kind == nil then
if #stack > 1 or skipping > 0 then
return nil, Err.new(Err.TRUNCATED, "unclosed block", at)
end
break
end
local cur = stack[#stack]
if kind == "}" then
if skipping > 0 then
skipping -= 1
elseif #stack == 1 then
return nil, Err.new(Err.CORRUPT, "unbalanced '}'", at)
else
table.remove(stack)
end
canReplace = false
elseif kind ~= "s" then
return nil, Err.new(Err.CORRUPT, if kind == "{" then "block without a key" else "condition without a key", at)
else
local key = v :: string
local k2, v2, at2, terr2 = token(lx)
if terr2 then
return nil, Err.new(Err.TRUNCATED, terr2, at2)
end
local cond: string? = nil
if k2 == "[" then
cond = v2
k2, v2, at2, terr2 = token(lx)
if terr2 then
return nil, Err.new(Err.TRUNCATED, terr2, at2)
end
if k2 ~= "{" then
return nil, Err.new(Err.CORRUPT, "a condition after a key needs a block", at2)
end
end
if k2 == "{" then
if #stack + skipping > maxDepth then
return nil, Err.new(Err.LIMIT, "nesting deeper than maxDepth", at2)
end
local pass = skipping == 0 and (cond == nil or not evaluate or KeyValues.condition(cond :: string, defines))
if not pass then
skipping += 1
else
local pair: Pair = { key = key, value = {}, cond = if evaluate then nil else cond }
local last = cur[#cur]
if cond and evaluate and canReplace and last and type(last.value) == "table" and last.key == key then
cur[#cur] = pair
else
table.insert(cur, pair)
end
table.insert(stack, pair.value :: Block)
end
canReplace = false
elseif k2 == "s" then
local value = v2 :: string
-- a condition after a value: only on the same line
local save = lx.i
local k3, v3 = token(lx)
local c3: string? = nil
if k3 == "[" and not string.find(string.sub(text, save, lx.i - 1), "\n", 1, true) then
c3 = v3
else
lx.i = save
end
if skipping == 0 then
local pass = c3 == nil or not evaluate or KeyValues.condition(c3 :: string, defines)
if pass then
local pair: Pair = { key = key, value = value, cond = if evaluate then nil else c3 }
local last = cur[#cur]
if c3 and evaluate and canReplace and last and type(last.value) == "string" and last.key == key then
cur[#cur] = pair
canReplace = false
else
table.insert(cur, pair)
canReplace = c3 == nil
end
if #stack == 1 and (key == "#include" or key == "#base") and o.resolve then
table.remove(cur)
table.insert(includes, { kind = key, name = value })
end
end
end
elseif k2 == nil then
return nil, Err.new(Err.TRUNCATED, "key without a value", at)
else
return nil, Err.new(Err.CORRUPT, "unexpected '" .. tostring(k2) .. "' after a key", at2)
end
end
end
if #includes > 0 then
if depth0 >= 16 then
return nil, Err.new(Err.LIMIT, "#include / #base nested more than 16 deep")
end
local resolve = o.resolve :: (string) -> (buffer | string)?
for _, inc in includes do
local ok, data = pcall(resolve, inc.name)
if not ok or data == nil then
return nil, Err.new(Err.IO, inc.kind .. ' "' .. inc.name .. '" not found')
end
local s = if type(data) == "buffer" then buffer.tostring(data) else tostring(data)
local sub, err = parseText(s, o, depth0 + 1)
if not sub then
return nil, Err.new((err :: Err.Err).code, inc.name .. ": " .. (err :: Err.Err).message)
end
if inc.kind == "#include" then
for _, p in sub do
table.insert(root, p)
end
else
KeyValues.merge(root, sub)
end
end
end
return root, nil
end
function KeyValues.parse(text: string | buffer, opts: ParseOptions?): (Block?, Err.Err?)
local s = if type(text) == "buffer" then buffer.tostring(text) else text
if type(s) ~= "string" then
return nil, Err.new(Err.ARG, "KeyValues.parse: expected a string or a buffer")
end
return parseText(s, opts, 0)
end
-- #base: keys of base missing from into are added; blocks present in both merge recursively (RecursiveMergeKeyValues)
function KeyValues.merge(into: Block, base: Block)
for _, bp in base do
local found: Pair? = nil
for _, p in into do
if keyEq(p.key, bp.key) then
found = p
break
end
end
if not found then
table.insert(into, KeyValues.copy({ bp })[1])
elseif type(found.value) == "table" and type(bp.value) == "table" then
KeyValues.merge(found.value :: Block, bp.value :: Block)
end
end
end
function KeyValues.copy(b: Block): Block
local out: Block = table.create(#b) :: any
for i, p in b do
local v: any = p.value
out[i] = { key = p.key, value = if type(v) == "table" then KeyValues.copy(v) else v, cond = p.cond, type = p.type }
end
return out
end
-- the first pair with this key (case-insensitive, as KeyValues::FindKey); "a/b/c" walks blocks
function KeyValues.find(b: Block, path: string): Pair?
local cur: Block? = b
local found: Pair? = nil
for part in string.gmatch(path, "[^/]+") do
if not cur then
return nil
end
found = nil
for _, p in cur do
if keyEq(p.key, part) then
found = p
break
end
end
if not found then
return nil
end
cur = if type(found.value) == "table" then found.value :: Block else nil
end
return found
end
function KeyValues.get(b: Block, path: string): any
local p = KeyValues.find(b, path)
return p and p.value
end
function KeyValues.all(b: Block, key: string): { Pair }
local out: { Pair } = {}
for _, p in b do
if keyEq(p.key, key) then
table.insert(out, p)
end
end
return out
end
local function quote(s: string, escapes: boolean): string
if escapes then
s = string.gsub(s, '[\\"\n\t\r]', { ["\\"] = "\\\\", ['"'] = '\\"', ["\n"] = "\\n", ["\t"] = "\\t", ["\r"] = "\\r" })
end
return '"' .. s .. '"'
end
local function writeBlock(b: Block, out: { string }, indent: string, level: number, escapes: boolean, depth: number): string?
if depth > 256 then
return "nesting deeper than 256"
end
local pad = string.rep(indent, level)
for _, p in b do
if type(p) ~= "table" or type(p.key) ~= "string" then
return "a pair needs a string key"
end
local v: any = p.value
local cond = if type(p.cond) == "string" then " [" .. p.cond .. "]" else ""
if type(v) == "table" then
table.insert(out, pad .. quote(p.key, escapes) .. cond .. "\n" .. pad .. "{\n")
local err = writeBlock(v, out, indent, level + 1, escapes, depth + 1)
if err then
return err
end
table.insert(out, pad .. "}\n")
elseif type(v) == "string" or type(v) == "number" or type(v) == "boolean" then
local s = if type(v) == "boolean" then (if v then "1" else "0") else tostring(v)
table.insert(out, pad .. quote(p.key, escapes) .. "\t" .. quote(s, escapes) .. cond .. "\n")
else
return "unwritable value for key " .. p.key
end
end
return nil
end
function KeyValues.write(b: Block, opts: WriteOptions?): (string?, Err.Err?)
if type(b) ~= "table" then
return nil, Err.new(Err.ARG, "KeyValues.write: expected a pair list")
end
local out: { string } = {}
local err = writeBlock(b, out, opts and opts.indent or "\t", 0, not (opts and opts.escapes == false), 0)
if err then
return nil, Err.new(Err.ARG, err)
end
return table.concat(out), nil
end
function KeyValues.toObject(b: Block, opts: ObjectOptions?): any
local mode = opts and opts.duplicates or "array"
local o = Types.object()
local multi: { [string]: boolean } = {}
for _, p in b do
local v: any = p.value
if type(v) == "table" then
v = KeyValues.toObject(v, opts)
end
local old = o[p.key]
if old == nil then
Types.set(o, p.key, v)
elseif mode == "last" then
o[p.key] = v
elseif mode == "array" then
if not multi[p.key] then
o[p.key] = { old }
multi[p.key] = true
end
table.insert(o[p.key], v)
end
end
return o
end
local function fromValue(key: string, v: any, out: Block, depth: number): string?
if depth > 256 then
return "nesting deeper than 256"
end
if type(v) == "table" and not Types.isObject(v) and Types.isArray(v, true) then
for _, x in v do
if type(x) == "table" and not Types.isObject(x) and Types.isArray(x, true) then
return "nested array under key " .. key
end
local err = fromValue(key, x, out, depth + 1)
if err then
return err
end
end
return nil
elseif type(v) == "table" then
local sub: Block = {}
local t: { [any]: any } = v :: any
for _, k in Types.keys(t) do
if type(k) ~= "string" and type(k) ~= "number" then
return "unwritable key"
end
local err = fromValue(tostring(k), t[k], sub, depth + 1)
if err then
return err
end
end
table.insert(out, { key = key, value = sub })
return nil
elseif type(v) == "string" or type(v) == "number" or type(v) == "boolean" then
table.insert(out, { key = key, value = if type(v) == "string" then v elseif type(v) == "boolean" then (if v then "1" else "0") else tostring(v) })
return nil
end
return "unwritable value for key " .. key
end
-- a Types.object / plain table -> pairs (arrays repeat their key; booleans become "1" / "0")
function KeyValues.fromObject(v: any): (Block?, Err.Err?)
if type(v) ~= "table" then
return nil, Err.new(Err.ARG, "KeyValues.fromObject: expected a table")
end
local out: Block = {}
for _, k in Types.keys(v) do
if type(k) ~= "string" and type(k) ~= "number" then
return nil, Err.new(Err.ARG, "unwritable key")
end
local err = fromValue(tostring(k), v[k], out, 0)
if err then
return nil, Err.new(Err.ARG, err)
end
end
return out, nil
end
-- pair list or object
function KeyValues.pairs(v: any): (Block?, Err.Err?)
if type(v) == "table" and not Types.isObject(v) and (#v > 0 or next(v) == nil) then
local first = v[1]
if first == nil or (type(first) == "table" and type(first.key) == "string") then
return v, nil
end
end
return KeyValues.fromObject(v)
end
-- BSP entity lump: { "k" "v" ... } blocks, no escapes (CMapEntities / ParseEntity)
function KeyValues.entities(text: string): ({ Block }?, Err.Err?)
text = string.match(text, "^[^%z]*") :: string
local lx: Lexer = { s = text, i = 1, n = #text, escapes = false }
local out: { Block } = {}
local cur: Block? = nil
while true do
local kind, v, at, terr = token(lx)
if terr then
return nil, Err.new(Err.TRUNCATED, terr, at)
end
if kind == nil then
if cur then
return nil, Err.new(Err.TRUNCATED, "unclosed entity", at)
end
return out, nil
elseif kind == "{" then
if cur then
return nil, Err.new(Err.CORRUPT, "'{' inside an entity", at)
end
cur = {}
elseif kind == "}" then
if not cur then
return nil, Err.new(Err.CORRUPT, "unbalanced '}'", at)
end
table.insert(out, cur :: Block)
cur = nil
elseif not cur then
return nil, Err.new(Err.CORRUPT, "key outside an entity", at)
else
local k2, v2, at2, terr2 = token(lx)
if terr2 then
return nil, Err.new(Err.TRUNCATED, terr2, at2)
end
if k2 ~= "s" then
return nil, Err.new(Err.CORRUPT, "entity key without a value", at)
end
table.insert(cur, { key = v :: string, value = v2 :: string })
end
end
end
function KeyValues.writeEntities(list: { Block }): (string?, Err.Err?)
local out: { string } = {}
for _, e in list do
table.insert(out, "{\n")
for _, p in e do
if type(p.value) ~= "string" then
return nil, Err.new(Err.ARG, "entity values are strings")
end
table.insert(out, '"' .. p.key .. '" "' .. (p.value :: string) .. '"\n')
end
table.insert(out, "}\n")
end
return table.concat(out), nil
end
KeyValues.readBinary = Binary.read
KeyValues.writeBinary = Binary.write
KeyValues.isBinary = Binary.sniff
return KeyValues
+99
View File
@@ -0,0 +1,99 @@
--!strict
-- data/vdf: Valve KeyValues files (.vdf, .acf, .res, ...) as data over codecs/text/KeyValues, read and written; binary
-- KeyValues (shortcuts.vdf) too. Values are ordered objects, a repeated key's values an array (opts.duplicates);
-- opts.pairs gives the pair list with conditions and binary types. Not supported: appinfo.vdf / packageinfo.vdf headers.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Sniff = require("@rosetta/core/Sniff")
local KeyValues = require("@rosetta/codecs/text/KeyValues")
-- ------------------------------------------------------------------------------------------------ contract
local Vdf = {
name = "vdf",
category = "data",
extensions = { "vdf", "acf", "res", "kv" },
mime = { "text/x-vdf" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/KeyValues" },
caps = { decode = true, encode = true, ordered = true, binary = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
pairs: boolean?, -- the KeyValues pair list instead of an object
duplicates: ("array" | "last" | "first")?, -- default "array"
escapes: boolean?, -- default true
defines: ({ [string]: boolean } | false)?, -- [$X] conditions (codecs/text/KeyValues), default PC
resolve: ((name: string) -> (buffer | string)?)?, -- #include / #base
binary: boolean?, -- force binary (default: sniffed)
}
export type EncodeOptions = {
binary: boolean?, -- default false
escapes: boolean?, -- default true
indent: string?, -- default "\t"
}
-- ------------------------------------------------------------------------------------------------ sniff
function Vdf.sniff(r: Bytes.Reader): number
local n = r:remaining()
if KeyValues.isBinary(r.buf, r.pos, n) then
return 0.3
end
local head = Sniff.text(r, 256, true)
if string.find(head, "%z") then
return 0
end
head = string.gsub(head, "^//[^\n]*\n%s*", "")
if string.match(head, '^"[^"\n]+"%s*{') or string.match(head, '^"[^"\n]+"%s*%[[^%]\n]*%]%s*{') then
return 0.6
end
if string.match(head, "^#base%s") or string.match(head, "^#include%s") then
return 0.5
end
if string.match(head, '^[%w_]+%s*\n%s*{%s*\n%s*"') then
return 0.3
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Vdf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local o: DecodeOptions = opts or {}
local n = r.limit - r.base
local blk, err
if o.binary or (o.binary == nil and KeyValues.isBinary(r.buf, r.base, n)) then
blk, err = KeyValues.readBinary(r.buf, r.base, n)
else
blk, err = KeyValues.parse(buffer.readstring(r.buf, r.base, n), {
escapes = o.escapes,
defines = o.defines,
resolve = o.resolve,
})
end
if not blk then
return nil, err
end
if o.pairs then
return blk, nil
end
return KeyValues.toObject(blk, { duplicates = o.duplicates }), nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Vdf.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local blk, err = KeyValues.pairs(value)
if not blk then
return nil, err
end
if opts and opts.binary then
return KeyValues.writeBinary(blk)
end
local s, werr = KeyValues.write(blk, { escapes = opts and opts.escapes, indent = opts and opts.indent })
if not s then
return nil, werr
end
return buffer.fromstring(s), nil
end
return Vdf
+2 -26
View File
@@ -6,6 +6,7 @@ local Types = require("@rosetta/Types")
local Mat4 = require("@rosetta/codecs/model/Mat4") local Mat4 = require("@rosetta/codecs/model/Mat4")
local Pixels = require("@rosetta/codecs/image/Pixels") local Pixels = require("@rosetta/codecs/image/Pixels")
local Rig = require("@rosetta/codecs/model/Rig") local Rig = require("@rosetta/codecs/model/Rig")
local SourceAnim = require("@rosetta/codecs/model/SourceAnim")
local HalfLife = {} local HalfLife = {}
@@ -44,31 +45,6 @@ local function textures(b: buffer, base: number, size: number, maxPixels: number
return out, names return out, names
end end
-- bone default + stored value * scale
local function animValue(b: buffer, at: number, limit: number, f: number): number?
local p = at
local k = f
for _ = 1, 65536 do
if p + 2 > limit then
return nil
end
local valid, total = readu8(b, p), readu8(b, p + 1)
if total == 0 then
return nil
end
if total > k then
local idx = if valid > k then k + 1 else valid
if p + idx * 2 + 2 > limit then
return nil
end
return readi16(b, p + idx * 2)
end
k -= total
p += (valid + 1) * 2
end
return nil
end
function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): (Types.Scene?, string?) function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?): (Types.Scene?, string?)
if size < 244 then if size < 244 then
return nil, "truncated header" return nil, "truncated header"
@@ -293,7 +269,7 @@ function HalfLife.decode(b: buffer, base: number, size: number, opts: Options?):
local v: { number } = {} local v: { number } = {}
for k = 0, 5 do for k = 0, 5 do
local off = readu16(b, ao + k * 2) local off = readu16(b, ao + k * 2)
local raw = if off ~= 0 then animValue(b, ao + off, limit, f) else nil local raw = if off ~= 0 then SourceAnim.value(b, ao + off, limit, f) else nil
v[k + 1] = bn.value[k + 1] + (raw or 0) * bn.scale[k + 1] v[k + 1] = bn.value[k + 1] + (raw or 0) * bn.scale[k + 1]
end end
table.insert(tr, v[1]) table.insert(tr, v[1])
+2 -2
View File
@@ -1,6 +1,6 @@
--!strict --!strict
-- model/mdl: Quake 1 ("IDPO" v6, model/mdl/Quake) and GoldSrc ("IDST" v10, model/mdl/HalfLife) models. Quake skins -- model/mdl: Quake 1 ("IDPO" v6, model/mdl/Quake) and GoldSrc ("IDST" v10, model/mdl/HalfLife) models. Quake skins
-- need gfx/palette.lmp (not redistributable, never built in; else a grey ramp). Not supported: Source MDL (v44+). -- need gfx/palette.lmp (not redistributable, never built in; else a grey ramp). Source MDL (v44+) is model/sourcemdl.
-- ------------------------------------------------------------------------------------------------ requires -- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err") local Err = require("@rosetta/core/Err")
@@ -16,7 +16,7 @@ local Mdl = {
category = "model", category = "model",
extensions = { "mdl" }, extensions = { "mdl" },
mime = { "model/x-mdl" }, mime = { "model/x-mdl" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" }, deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/SourceAnim" },
caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true }, caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true },
} }
+428
View File
@@ -0,0 +1,428 @@
--!strict
-- model/sourcemdl/Build: the parsed MDL / VVD / VTX / PHY into a Scene: bones (poseToBone as inverse bind matrices),
-- body part models as meshes (one primitive per studio mesh, LOD 0 indices; LODs 1+ in primitive extras), flexes as
-- morph targets, attachments as nodes, animations through codecs/model/SourceAnim. Source front faces wind clockwise.
local Types = require("@rosetta/Types")
local Mat4 = require("@rosetta/codecs/model/Mat4")
local Rig = require("@rosetta/codecs/model/Rig")
local SourceAnim = require("@rosetta/codecs/model/SourceAnim")
local Mdl = require("@rosetta/model/sourcemdl/Mdl")
local Vvd = require("@rosetta/model/sourcemdl/Vvd")
local Vtx = require("@rosetta/model/sourcemdl/Vtx")
local Phy = require("@rosetta/model/sourcemdl/Phy")
local Build = {}
local Scene = Types.Scene
local readf32, readu8, readi32, writef32, writeu16, writeu32 = buffer.readf32, buffer.readu8, buffer.readi32, buffer.writef32, buffer.writeu16, buffer.writeu32
export type Options = {
bodies: { number }?, -- 1-based model per body part, default 1
lod: number?, -- 1-based LOD for the primitives' indices, default 1
animations: boolean?, -- default true
maxVertices: number?,
maxFrames: number?, -- per animation, default 65536
}
export type Inputs = { vvd: Vvd.Vertices?, vtx: Vtx.Strips?, phy: Phy.Physics?, ani: buffer?, warnings: { string } }
local STUDIO_DELTA, STUDIO_FRAMEANIM = 0x04, 0x40
local function u32s(list: { number }): Types.Accessor
local b = buffer.create(#list * 4)
for i, v in list do
writeu32(b, (i - 1) * 4, v)
end
return Scene.accessor(b, "u32", 1, #list)
end
local function reversed(tris: { number }, count: number): { number }?
local out: { number } = {}
for i = 1, #tris - 2, 3 do
local a, b, c = tris[i], tris[i + 1], tris[i + 2]
if a >= count or b >= count or c >= count then
return nil
end
out[i], out[i + 1], out[i + 2] = c, b, a
end
return out
end
local function qmul(a: { number }, b: { number }): { number }
local ax, ay, az, aw = a[1], a[2], a[3], a[4]
local bx, by, bz, bw = b[1], b[2], b[3], b[4]
return { aw * bx + ax * bw + ay * bz - az * by, aw * by - ax * bz + ay * bw + az * bx, aw * bz + ax * by - ay * bx + az * bw, aw * bw - ax * bx - ay * by - az * bz }
end
local function primitive(h: Mdl.Header, vvd: Vvd.Vertices, first: number, mesh: Mdl.Mesh, nBones: number): Types.Primitive
local n = mesh.vertexCount
local pos, nrm, uv = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8)
local jb, wb = buffer.create(n * 8), buffer.create(n * 16)
local src = vvd.data
for i = 0, n - 1 do
local o = (first + i) * 48
local cnt = readu8(src, o + 15)
for k = 0, 2 do
if k < cnt then
writef32(wb, i * 16 + k * 4, readf32(src, o + k * 4))
writeu16(jb, i * 8 + k * 2, math.min(readu8(src, o + 12 + k), math.max(nBones - 1, 0)))
end
end
for k = 0, 2 do
writef32(pos, i * 12 + k * 4, readf32(src, o + 16 + k * 4))
writef32(nrm, i * 12 + k * 4, readf32(src, o + 28 + k * 4))
end
writef32(uv, i * 8, readf32(src, o + 40))
writef32(uv, i * 8 + 4, readf32(src, o + 44))
end
local attrs: { [string]: Types.Accessor } = {
POSITION = Scene.accessor(pos, "f32", 3, n),
NORMAL = Scene.accessor(nrm, "f32", 3, n),
TEXCOORD_0 = Scene.accessor(uv, "f32", 2, n),
}
if nBones > 0 then
attrs.JOINTS_0 = Scene.accessor(jb, "u16", 4, n)
attrs.WEIGHTS_0 = Scene.accessor(wb, "f32", 4, n)
end
local tan = vvd.tangents
if tan then
local t = buffer.create(n * 16)
buffer.copy(t, 0, tan, first * 16, n * 16)
attrs.TANGENT = Scene.accessor(t, "f32", 4, n)
end
local fam = h.skins[1]
local tex = if fam then fam[mesh.material + 1] else mesh.material
return {
attributes = attrs,
mode = "triangles" :: any,
material = if tex and tex >= 0 and tex < #h.textures then tex + 1 else nil,
extras = { skinRef = mesh.material, materialType = mesh.materialType, materialParam = mesh.materialParam, id = mesh.id },
}
end
local function flexTargets(meshes: { Mdl.Mesh }, prims: { Types.Primitive }, names: { string }): { string }?
local used: { [number]: boolean } = {}
local order: { number } = {}
for _, m in meshes do
for _, f in m.flexes do
for _, d in { f.desc, if f.partner > 0 then f.partner else -1 } do
if d >= 0 and not used[d] then
used[d] = true
table.insert(order, d)
end
end
end
end
if #order == 0 then
return nil
end
table.sort(order)
local slot: { [number]: number } = {}
for i, d in order do
slot[d] = i
end
for k, m in meshes do
local prim = prims[k]
local n = m.vertexCount
local targets: { { [string]: Types.Accessor } } = {}
for i = 1, #order do
targets[i] = { POSITION = Scene.accessor(nil, "f32", 3, n), NORMAL = Scene.accessor(nil, "f32", 3, n) }
end
for _, f in m.flexes do
local stereo = f.partner > 0
for _, d in f.deltas do
local v = d[1]
if v < n then
for side = 0, if stereo then 1 else 0 do
local w = if not stereo then 1 elseif side == 0 then d[8] else 1 - d[8]
local t = targets[slot[if side == 0 then f.desc else f.partner]]
if t and w ~= 0 then
local pb, nb = t.POSITION.data, t.NORMAL.data
for c = 0, 2 do
writef32(pb, v * 12 + c * 4, readf32(pb, v * 12 + c * 4) + d[2 + c] * w)
writef32(nb, v * 12 + c * 4, readf32(nb, v * 12 + c * 4) + d[5 + c] * w)
end
end
end
end
end
end
prim.targets = targets
end
local out = {}
for i, d in order do
out[i] = names[d + 1] or ("flex" .. d)
end
return out
end
local function animate(scene: Types.Scene, h: Mdl.Header, b: buffer, base: number, size: number, inp: Inputs, jointNodes: { number }, opts: Options?)
local bones: { SourceAnim.Bone } = h.bones :: any
local maxFrames = opts and opts.maxFrames or 65536
local firstSeq: { [number]: string } = {}
for _, s in h.sequences do
local a = s.anims[1]
if a and a >= 0 and not firstSeq[a + 1] then
firstSeq[a + 1] = s.name
end
end
local list = {}
for i, a in h.anims do
local info: { [string]: any } = { name = a.name, fps = a.fps, frames = a.frames, flags = a.flags, delta = bit32.band(a.flags, STUDIO_DELTA) ~= 0 }
list[i] = info
local frames = a.frames
if bit32.band(a.flags, STUDIO_FRAMEANIM) ~= 0 then
info.skipped = "frame animation (v52+)"
elseif frames <= 0 or frames > maxFrames then
info.skipped = "frame count"
elseif #bones == 0 then
info.skipped = "no bones"
else
local function locate(block: number, index: number): (buffer?, number, number)
if block == 0 then
return b, base + a.at + index, base + size
end
local ani, blk = inp.ani, h.animBlocks[block + 1]
if not ani or not blk then
return nil, 0, 0
end
local lim = math.min(blk[2], buffer.len(ani))
return ani, blk[1] + index, lim
end
local nSections = 0
if a.sectionFrames > 0 and a.sectionIndex ~= 0 then
nSections = frames // a.sectionFrames + 2
local so = a.at + a.sectionIndex
if so < 0 or so + nSections * 8 > size then
info.skipped = "bad section table"
nSections = -1
end
end
local per: { [number]: { frames: number, block: number, index: number } } = {}
local where: { { number } } = {}
if nSections >= 0 then
for f = 0, frames - 1 do
local sec, loc = 0, f
if nSections > 0 then
if frames > a.sectionFrames and f == frames - 1 then
sec, loc = frames // a.sectionFrames + 1, 0
else
sec = f // a.sectionFrames
loc = f - sec * a.sectionFrames
end
end
local e = per[sec]
if not e then
if nSections > 0 then
local so = base + a.at + a.sectionIndex + sec * 8
e = { frames = 0, block = readi32(b, so), index = readi32(b, so + 4) }
else
e = { frames = 0, block = a.block, index = a.index }
end
per[sec] = e
end
e.frames = math.max(e.frames, loc + 1)
where[f + 1] = { sec, loc }
end
end
local decoded: { [number]: { [number]: SourceAnim.Track } } = {}
for sec, e in per do
local src, at, lim = locate(e.block, e.index)
if e.block < 0 or not src then
info.skipped = if e.block < 0 then "missing animation block" else "animation block " .. e.block .. " not resolved (" .. h.animBlockName .. ")"
break
end
local tr, err = SourceAnim.decode(src, at, lim, bones, e.frames)
if not tr then
info.skipped = err
break
end
decoded[sec] = tr
end
if not info.skipped then
local animated: { [number]: boolean } = {}
for _, tr in decoded do
for j in tr do
animated[j] = true
end
end
local fps = if a.fps > 0 then a.fps else 30
local times = table.create(frames, 0)
local tracks: { [number]: Rig.Track } = {}
for j in animated do
tracks[j] = { translation = table.create(frames * 3, 0), rotation = table.create(frames * 4, 0) }
end
local delta = info.delta
for f = 0, frames - 1 do
times[f + 1] = f / fps
local w = where[f + 1]
local tr = decoded[w[1]]
for j, out in tracks do
local bn = bones[j]
local t = tr[j]
local tt, rr = out.translation :: { number }, out.rotation :: { number }
local px, py, pz, q
if t then
px, py, pz = t.pos[w[2] * 3 + 1], t.pos[w[2] * 3 + 2], t.pos[w[2] * 3 + 3]
q = { t.rot[w[2] * 4 + 1], t.rot[w[2] * 4 + 2], t.rot[w[2] * 4 + 3], t.rot[w[2] * 4 + 4] }
else
px, py, pz, q = if delta then 0 else bn.pos[1], if delta then 0 else bn.pos[2], if delta then 0 else bn.pos[3], if delta then { 0, 0, 0, 1 } else bn.quat
end
if delta then
px, py, pz = bn.pos[1] + px, bn.pos[2] + py, bn.pos[3] + pz
q = qmul(bn.quat, q)
end
tt[f * 3 + 1], tt[f * 3 + 2], tt[f * 3 + 3] = px, py, pz
for c = 1, 4 do
rr[f * 4 + c] = q[c]
end
end
end
info.animation = Rig.animation(scene, firstSeq[i] or a.name, jointNodes, times, tracks, "LINEAR")
end
end
end
return list
end
function Build.scene(h: Mdl.Header, b: buffer, base: number, size: number, inp: Inputs, opts: Options?): (Types.Scene?, string?)
local scene = Scene.new()
scene.meta.up = "z"
local root: Types.Node = { name = h.name, children = {} }
table.insert(scene.nodes, root)
scene.roots[1] = 1
local joints: { Rig.Joint } = {}
for i, bn in h.bones do
joints[i] = { name = bn.name, parent = bn.parent + 1, translation = table.clone(bn.pos), rotation = table.clone(bn.quat) }
end
local nBones = #h.bones
local jointNodes, skinIndex = {}, nil
if nBones > 0 then
local nodes, si = Rig.skeleton(scene, joints, "local", 1)
jointNodes, skinIndex = nodes, si
local ibm = (scene.skins[si].inverseBindMatrices :: Types.Accessor).data
for i, bn in h.bones do
local m = Mat4.fromRows(bn.poseToBone)
for k = 1, 16 do
writef32(ibm, ((i - 1) * 16 + k - 1) * 4, m[k])
end
local ex: { [string]: any } = { bone = i - 1, flags = bn.flags, surfaceProp = bn.surfaceProp, contents = bn.contents, physicsBone = bn.physicsBone }
if bn.procedural then
ex.procedural = bn.procedural
end
scene.nodes[nodes[i]].extras = ex
end
end
for _, t in h.textures do
local mat = Scene.material(t.name)
mat.metallic = 0
table.insert(scene.materials, mat)
end
local vvd, vtx = inp.vvd, inp.vtx
local lodPick = math.max(1, opts and opts.lod or 1)
local bodyInfo = {}
for p, part in h.bodyParts do
local pick = (opts and opts.bodies and opts.bodies[p]) or 1
local info = { name = part.name, base = part.base, models = {}, selected = pick }
bodyInfo[p] = info
for m, model in part.models do
local minfo: { [string]: any } = { name = model.name, vertices = model.vertexCount, eyeballs = model.eyeballs }
info.models[m] = minfo
local vlods = vtx and vtx.parts[p] and vtx.parts[p][m]
if #model.meshes > 0 and vvd and vlods and #vlods > 0 then
local first = model.vertexIndex // 48
if first + model.vertexCount > vvd.count then
return nil, "model " .. model.name .. ": vertices outside the vvd"
end
local mesh: Types.Mesh = { name = model.name, primitives = {}, extras = { bodyPart = part.name, lods = #vlods } }
for k, sm in model.meshes do
local prim = primitive(h, vvd, first + sm.vertexOffset, sm, nBones)
local lods = {}
for l, lod in vlods do
local vm = lod.meshes[k]
local idx = if vm then reversed(vm.indices, sm.vertexCount) else {}
if not idx then
return nil, "vtx index outside mesh " .. (k - 1) .. " of " .. model.name
end
lods[l] = { indices = u32s(idx), switchPoint = lod.switchPoint }
end
local use = lods[math.min(lodPick, #lods)]
prim.indices = use.indices
local ex = prim.extras :: { [string]: any }
ex.lods = lods
table.insert(mesh.primitives, prim)
end
local names = flexTargets(model.meshes, mesh.primitives, h.flexDescs)
if names then
mesh.weights = table.create(#names, 0)
local mex = mesh.extras :: { [string]: any }
mex.targetNames = names
end
table.insert(scene.meshes, mesh)
minfo.mesh = #scene.meshes
if m == pick then
table.insert(scene.nodes, { name = part.name, children = {}, mesh = #scene.meshes, skin = skinIndex })
table.insert(root.children, #scene.nodes)
end
end
end
end
local attachments = {}
for i, a in h.attachments do
local t, r, s = Mat4.decompose(Mat4.fromRows(a.matrix))
local node: Types.Node = { name = a.name, children = {}, translation = t, rotation = r, scale = if math.abs(s[1] - 1) + math.abs(s[2] - 1) + math.abs(s[3] - 1) > 1e-5 then s else nil, extras = { attachment = i - 1, flags = a.flags } }
table.insert(scene.nodes, node)
local parent = jointNodes[a.bone + 1]
table.insert(scene.nodes[parent or 1].children, #scene.nodes)
attachments[i] = { name = a.name, bone = a.bone, flags = a.flags, node = #scene.nodes }
end
local anims = if opts and opts.animations == false then {} else animate(scene, h, b, base, size, inp, jointNodes, opts)
local skins = {}
for f, fam in h.skins do
local list = {}
for r, t in fam do
list[r] = t + 1
end
skins[f] = list
end
local phy = inp.phy
scene.meta.source = {
format = "sourcemdl",
version = h.version,
checksum = h.checksum,
name = h.name,
flags = h.flags,
eye = h.eye,
illum = h.illum,
hull = { h.hullMin, h.hullMax },
view = { h.viewMin, h.viewMax },
mass = h.mass,
contents = h.contents,
surfaceProp = h.surfaceProp,
keyValues = h.keyValues,
cdmaterials = h.cdmaterials,
textures = h.textures,
skins = skins,
bodyParts = bodyInfo,
attachments = attachments,
hitboxSets = h.hitboxSets,
boneControllers = h.controllers,
sequences = h.sequences,
animations = anims,
poseParameters = h.poseParameters,
flexDescs = h.flexDescs,
flexControllers = h.flexControllers,
flexRules = h.flexRules,
includeModels = h.includeModels,
animBlockName = h.animBlockName,
nodes = h.nodes,
rootLod = h.rootLod,
lods = if vtx then vtx.lods else 0,
lodVertices = if vvd then vvd.lodCounts else nil,
lodReplacements = if vtx then vtx.replacements else nil,
physics = phy,
warnings = inp.warnings,
}
return scene, nil
end
return Build
+159
View File
@@ -0,0 +1,159 @@
--!strict
-- model/sourcemdl/Material: the MDL's texture names through $cdmaterials to materials/<dir><name>.vmt (the engine's
-- search order, then the bare name), parsed with codecs/text/KeyValues; "patch" materials (include + insert /
-- replace) applied. $basetexture / $bumpmap ($normalmap) become .vtf texture references for F.model.loadTextures;
-- $translucent / $alphatest / $nocull / $color map to the PBR fields, every parameter is kept in extras.vmt.
local Types = require("@rosetta/Types")
local Input = require("@rosetta/core/Input")
local KeyValues = require("@rosetta/codecs/text/KeyValues")
local Material = {}
local function dir(s: string): string
local d: string = string.gsub(string.gsub(s, "\\", "/"), "^/+", "")
return if d ~= "" and string.sub(d, -1) ~= "/" then d .. "/" else d
end
local function path(s: string): string
local p = string.gsub(string.gsub(s, "\\", "/"), "^/+", "")
return (string.gsub(p, "%.[vV][mMtT][tTfF]$", ""))
end
local function load(opts: any, uri: string): (string, KeyValues.Block?)
local b = Input.sibling(opts, uri) or Input.sibling(opts, string.lower(uri))
if not b then
return uri, nil
end
local kv = KeyValues.parse(b, { escapes = false, resolve = function(name: string): (buffer | string)?
return Input.sibling(opts, name)
end })
return uri, kv
end
-- { shader, params (lower-case keys) } of a parsed .vmt, patch includes applied (depth 8)
local function flatten(opts: any, kv: KeyValues.Block, depth: number): (string?, { [string]: any })
local first = kv[1]
if not first or type(first.value) ~= "table" then
return nil, {}
end
local shader, body = first.key, first.value :: KeyValues.Block
local params: { [string]: any } = {}
if string.lower(shader) == "patch" and depth < 8 then
local inc = KeyValues.get(body, "include")
local base: KeyValues.Block? = nil
if type(inc) == "string" then
local _, b = load(opts, path(inc) .. ".vmt")
base = b
end
if base then
shader, params = flatten(opts, base, depth + 1)
end
for _, p in body do
local k = string.lower(p.key)
if (k == "insert" or k == "replace") and type(p.value) == "table" then
for _, q in p.value :: KeyValues.Block do
local qk = string.lower(q.key)
if k == "insert" or params[qk] ~= nil then
params[qk] = if q.value == "" then nil else q.value
end
end
end
end
return shader, params
end
for _, p in body do
params[string.lower(p.key)] = p.value
end
return shader, params
end
local function num(v: any): number?
return if type(v) == "number" then v elseif type(v) == "string" then tonumber(v) else nil
end
local function color(v: any): { number }?
if type(v) ~= "string" then
return nil
end
local r, g, b = string.match(v, "^%s*[%[{]%s*([%d.eE+-]+)%s+([%d.eE+-]+)%s+([%d.eE+-]+)")
if not r then
return nil
end
local scale = if string.match(v, "^%s*{") then 1 / 255 else 1
return { (tonumber(r) :: number) * scale, (tonumber(g) :: number) * scale, (tonumber(b) :: number) * scale }
end
function Material.apply(scene: Types.Scene, textures: { any }, cdmaterials: { string }, opts: any?, warnings: { string })
if type(opts) ~= "table" or (opts.files == nil and opts.resolve == nil) then
return
end
local dirs: { string } = {}
for _, d in cdmaterials do
local nd = dir(d)
if not table.find(dirs, nd) then
table.insert(dirs, nd)
end
end
if not table.find(dirs, "") then
table.insert(dirs, "")
end
local texIndex: { [string]: number } = {}
local function texture(v: any): number?
if type(v) ~= "string" or v == "" then
return nil
end
local uri = "materials/" .. path(v) .. ".vtf"
local i = texIndex[string.lower(uri)]
if not i then
table.insert(scene.textures, { name = path(v), uri = uri, mime = "image/x-vtf" })
i = #scene.textures
texIndex[string.lower(uri)] = i
end
return i
end
for i, t in textures do
local mat = scene.materials[i]
local name = path(t.name)
local found, kv = nil, nil
for _, d in dirs do
local uri, b = load(opts, "materials/" .. d .. name .. ".vmt")
if b then
found, kv = uri, b
break
end
end
if not kv then
table.insert(warnings, "material " .. t.name .. ": no .vmt")
continue
end
local shader, p = flatten(opts, kv, 0)
local ex: { [string]: any } = mat.extras or {}
mat.extras = ex
ex.vmt = { path = found, shader = shader, params = p }
local base = texture(p["$basetexture"])
if base then
mat.baseColorTexture = { texture = base }
end
local bump = texture(p["$bumpmap"] or p["$normalmap"])
if bump then
mat.normalTexture = { texture = bump }
end
local c = color(p["$color2"]) or color(p["$color"])
if c then
mat.baseColor = { c[1], c[2], c[3], num(p["$alpha"]) or 1 }
elseif num(p["$alpha"]) then
mat.baseColor[4] = num(p["$alpha"]) :: number
end
if num(p["$translucent"]) == 1 then
mat.alphaMode = "blend"
elseif num(p["$alphatest"]) == 1 then
mat.alphaMode = "mask"
mat.alphaCutoff = num(p["$alphatestreference"]) or 0.5
end
if num(p["$nocull"]) == 1 then
mat.doubleSided = true
end
end
end
return Material
+525
View File
@@ -0,0 +1,525 @@
--!strict
-- model/sourcemdl/Mdl: the studiohdr_t tables of Source MDL v44-49 (Source SDK 2013 public/studio.h layouts, SourceIO
-- (MIT) and srctools (MIT) notes; no code taken). Geometry lives in the .vvd / .vtx files.
local Half = require("@rosetta/codecs/image/Half")
local Mdl = {}
local readi32, readu32, readi16, readu16, readu8, readf32 = buffer.readi32, buffer.readu32, buffer.readi16, buffer.readu16, buffer.readu8, buffer.readf32
local HALF = Half.TABLE
export type Bone = {
name: string,
parent: number, -- 0-based, -1 = none
pos: { number },
quat: { number },
rot: { number },
posScale: { number },
rotScale: { number },
poseToBone: { number }, -- 3x4 rows
flags: number,
contents: number,
surfaceProp: string,
physicsBone: number,
controllers: { number },
procedural: { [string]: any }?,
}
export type Flex = {
desc: number, -- 0-based flexdesc
partner: number,
targets: { number },
kind: number, -- 0 normal, 1 wrinkle
deltas: { { number } }, -- { index (mesh vertex), dx, dy, dz, nx, ny, nz, side, speed, wrinkle }
}
export type Mesh = { material: number, vertexOffset: number, vertexCount: number, materialType: number, materialParam: number, id: number, center: { number }, flexes: { Flex }, lodVertices: { number } }
export type Model = { name: string, kind: number, radius: number, vertexIndex: number, vertexCount: number, tangentIndex: number, meshes: { Mesh }, eyeballs: number }
export type BodyPart = { name: string, base: number, models: { Model } }
export type AnimDesc = { name: string, fps: number, flags: number, frames: number, block: number, index: number, sectionIndex: number, sectionFrames: number, at: number, movements: number, ikRules: number }
export type Header = {
version: number,
checksum: number,
name: string,
length: number,
eye: { number },
illum: { number },
hullMin: { number },
hullMax: { number },
viewMin: { number },
viewMax: { number },
flags: number,
bones: { Bone },
controllers: { any },
hitboxSets: { any },
anims: { AnimDesc },
sequences: { any },
textures: { { name: string, flags: number } },
cdmaterials: { string },
skins: { { number } }, -- families of 0-based texture indices per skin reference
skinRefs: number,
bodyParts: { BodyPart },
attachments: { any },
flexDescs: { string },
flexControllers: { any },
flexRules: { any },
poseParameters: { any },
includeModels: { any },
surfaceProp: string,
keyValues: string,
mass: number,
contents: number,
animBlockName: string,
animBlocks: { { number } }, -- { datastart, dataend }
vertAnimScale: number,
rootLod: number,
allowedRootLods: number,
ikChains: number,
nodes: { string },
}
local PROCEDURAL = { "axisinterp", "quatinterp", "aimatbone", "aimatattach", "jiggle" }
local JIGGLE = {
"length", "tipMass", "yawStiffness", "yawDamping", "pitchStiffness", "pitchDamping", "alongStiffness", "alongDamping",
"angleLimit", "minYaw", "maxYaw", "yawFriction", "yawBounce", "minPitch", "maxPitch", "pitchFriction", "pitchBounce",
"baseMass", "baseStiffness", "baseDamping", "baseMinLeft", "baseMaxLeft", "baseLeftFriction", "baseMinUp", "baseMaxUp",
"baseUpFriction", "baseMinForward", "baseMaxForward", "baseForwardFriction",
}
function Mdl.parse(b: buffer, base: number, size: number, opts: { maxVertices: number? }?): (Header?, string?)
if size < 408 then
return nil, "truncated header"
end
local function i32(o: number): number
return readi32(b, base + o)
end
local function inside(o: number, n: number): boolean
return o >= 0 and n >= 0 and o + n <= size
end
local function table_(count: number, at: number, stride: number, max: number, what: string): string?
if count < 0 or count > max or (count > 0 and not inside(at, count * stride)) then
return "bad " .. what .. " table"
end
return nil
end
local function str(o: number): string
if o < 0 or o >= size then
return ""
end
local n = math.min(size - o, 4096)
return (string.match(buffer.readstring(b, base + o, n), "^[^%z]*")) :: string
end
local function vec(o: number, n: number?): { number }
local v = {}
for k = 0, (n or 3) - 1 do
v[k + 1] = readf32(b, base + o + k * 4)
end
return v
end
local h: any = {
version = i32(4),
checksum = readu32(b, base + 8),
name = (string.match(buffer.readstring(b, base + 12, 64), "^[^%z]*")) :: string,
length = i32(76),
eye = vec(80),
illum = vec(92),
hullMin = vec(104),
hullMax = vec(116),
viewMin = vec(128),
viewMax = vec(140),
flags = readu32(b, base + 152),
mass = readf32(b, base + 328),
contents = i32(332),
rootLod = readu8(b, base + 377),
allowedRootLods = readu8(b, base + 378),
vertAnimScale = readf32(b, base + 392),
ikChains = i32(284),
}
local hdr2 = i32(400)
if hdr2 > 0 and inside(hdr2, 24) then
local long = readi32(b, base + hdr2 + 20)
if long > 0 then
local s = str(hdr2 + long)
if s ~= "" then
h.name = s
end
end
end
local nBones, oBones = i32(156), i32(160)
local e = table_(nBones, oBones, 216, 4096, "bone")
if e then
return nil, e
end
h.bones = {}
for i = 0, nBones - 1 do
local o = oBones + i * 216
local bone: Bone = {
name = str(o + i32(o)),
parent = i32(o + 4),
controllers = {},
pos = vec(o + 32),
quat = vec(o + 44, 4),
rot = vec(o + 60),
posScale = vec(o + 72),
rotScale = vec(o + 84),
poseToBone = vec(o + 96, 12),
flags = readu32(b, base + o + 160),
physicsBone = i32(o + 172),
surfaceProp = str(o + i32(o + 176)),
contents = i32(o + 180),
}
for k = 0, 5 do
bone.controllers[k + 1] = i32(o + 8 + k * 4)
end
if bone.parent < -1 or bone.parent >= i then
return nil, "bone " .. i .. ": bad parent"
end
local ptype, pidx = i32(o + 164), i32(o + 168)
if ptype > 0 and pidx ~= 0 then
local po = o + pidx
local rule: { [string]: any } = { type = PROCEDURAL[ptype] or ptype }
if ptype == 1 and inside(po, 176) then
rule.control = i32(po)
rule.axis = i32(po + 4)
rule.pos, rule.quat = {}, {}
for k = 0, 5 do
rule.pos[k + 1] = vec(po + 8 + k * 12)
rule.quat[k + 1] = vec(po + 80 + k * 16, 4)
end
elseif ptype == 2 and inside(po, 12) then
rule.control = i32(po)
local n, t = i32(po + 4), i32(po + 8)
rule.triggers = {}
if n > 0 and n <= 256 and inside(po + t, n * 48) then
for k = 0, n - 1 do
local to = po + t + k * 48
rule.triggers[k + 1] = { invTolerance = readf32(b, base + to), trigger = vec(to + 4, 4), pos = vec(to + 20), quat = vec(to + 32, 4) }
end
end
elseif (ptype == 3 or ptype == 4) and inside(po, 44) then
rule.parent = i32(po)
rule.aim = i32(po + 4)
rule.aimVector = vec(po + 8)
rule.upVector = vec(po + 20)
rule.basePos = vec(po + 32)
elseif ptype == 5 and inside(po, 120) then
rule.flags = i32(po)
for k, key in JIGGLE do
rule[key] = readf32(b, base + po + k * 4)
end
end
bone.procedural = rule
end
h.bones[i + 1] = bone
end
local nCtl, oCtl = i32(164), i32(168)
e = table_(nCtl, oCtl, 56, 4096, "bone controller")
if e then
return nil, e
end
h.controllers = {}
for i = 0, nCtl - 1 do
local o = oCtl + i * 56
h.controllers[i + 1] = { bone = i32(o), type = i32(o + 4), start = readf32(b, base + o + 8), ["end"] = readf32(b, base + o + 12), rest = i32(o + 16), input = i32(o + 20) }
end
local nSets, oSets = i32(172), i32(176)
e = table_(nSets, oSets, 12, 256, "hitbox set")
if e then
return nil, e
end
h.hitboxSets = {}
for i = 0, nSets - 1 do
local o = oSets + i * 12
local n, at = i32(o + 4), i32(o + 8)
local set = { name = str(o + i32(o)), boxes = {} }
if n > 0 and n <= 65536 and inside(o + at, n * 68) then
for k = 0, n - 1 do
local bo = o + at + k * 68
local nameOff = i32(bo + 32)
table.insert(set.boxes, { bone = i32(bo), group = i32(bo + 4), min = vec(bo + 8), max = vec(bo + 20), name = if nameOff ~= 0 then str(bo + nameOff) else "" })
end
end
h.hitboxSets[i + 1] = set
end
local nAnim, oAnim = i32(180), i32(184)
e = table_(nAnim, oAnim, 100, 65536, "animation")
if e then
return nil, e
end
h.anims = {}
for i = 0, nAnim - 1 do
local o = oAnim + i * 100
h.anims[i + 1] = {
at = o,
name = str(o + i32(o + 4)),
fps = readf32(b, base + o + 8),
flags = i32(o + 12),
frames = i32(o + 16),
movements = i32(o + 20),
block = i32(o + 52),
index = i32(o + 56),
ikRules = i32(o + 60),
sectionIndex = i32(o + 80),
sectionFrames = i32(o + 84),
}
end
local nSeq, oSeq = i32(188), i32(192)
e = table_(nSeq, oSeq, 212, 65536, "sequence")
if e then
return nil, e
end
h.sequences = {}
for i = 0, nSeq - 1 do
local o = oSeq + i * 212
local g0, g1 = i32(o + 68), i32(o + 72)
local anims = {}
local ai = i32(o + 60)
if g0 > 0 and g1 > 0 and g0 * g1 <= 4096 and inside(o + ai, g0 * g1 * 2) then
for k = 0, g0 * g1 - 1 do
anims[k + 1] = readi16(b, base + o + ai + k * 2)
end
end
local events = {}
local ne, eo = i32(o + 24), i32(o + 28)
if ne > 0 and ne <= 4096 and inside(o + eo, ne * 80) then
for k = 0, ne - 1 do
local ev = o + eo + k * 80
local nameOff = i32(ev + 76)
table.insert(events, {
cycle = readf32(b, base + ev),
event = i32(ev + 4),
type = i32(ev + 8),
options = (string.match(buffer.readstring(b, base + ev + 12, 64), "^[^%z]*")) :: string,
name = if nameOff ~= 0 then str(ev + nameOff) else "",
})
end
end
local kvSize = i32(o + 176)
h.sequences[i + 1] = {
name = str(o + i32(o + 4)),
activity = str(o + i32(o + 8)),
flags = i32(o + 12),
activityId = i32(o + 16),
weight = i32(o + 20),
events = events,
bboxMin = vec(o + 32),
bboxMax = vec(o + 44),
blends = i32(o + 56),
groupSize = { g0, g1 },
anims = anims,
paramIndex = { i32(o + 76), i32(o + 80) },
paramStart = vec(o + 84, 2),
paramEnd = vec(o + 92, 2),
fadeIn = readf32(b, base + o + 104),
fadeOut = readf32(b, base + o + 108),
nextSequence = i32(o + 136),
keyValues = if kvSize > 0 then str(o + i32(o + 172)) else "",
}
end
local nTex, oTex = i32(204), i32(208)
e = table_(nTex, oTex, 64, 65536, "texture")
if e then
return nil, e
end
h.textures = {}
for i = 0, nTex - 1 do
local o = oTex + i * 64
h.textures[i + 1] = { name = str(o + i32(o)), flags = i32(o + 4) }
end
local nCd, oCd = i32(212), i32(216)
e = table_(nCd, oCd, 4, 4096, "cdmaterials")
if e then
return nil, e
end
h.cdmaterials = {}
for i = 0, nCd - 1 do
h.cdmaterials[i + 1] = str(i32(oCd + i * 4))
end
local nRef, nFam, oSkin = i32(220), i32(224), i32(228)
if nRef < 0 or nFam < 0 or nRef * nFam > 1048576 or (nRef * nFam > 0 and not inside(oSkin, nRef * nFam * 2)) then
return nil, "bad skin table"
end
h.skins, h.skinRefs = {}, nRef
for f = 0, nFam - 1 do
local fam = {}
for r = 0, nRef - 1 do
fam[r + 1] = readi16(b, base + oSkin + (f * nRef + r) * 2)
end
h.skins[f + 1] = fam
end
local nParts, oParts = i32(232), i32(236)
e = table_(nParts, oParts, 16, 4096, "body part")
if e then
return nil, e
end
local maxVerts = opts and opts.maxVertices or 2 ^ 24
local totalFlex = 0
h.bodyParts = {}
for p = 0, nParts - 1 do
local po = oParts + p * 16
local nModels, oModels = i32(po + 4), i32(po + 12)
local part: BodyPart = { name = str(po + i32(po)), base = i32(po + 8), models = {} }
if nModels < 0 or nModels > 4096 or (nModels > 0 and not inside(po + oModels, nModels * 148)) then
return nil, "body part " .. p .. ": bad model table"
end
for m = 0, nModels - 1 do
local mo = po + oModels + m * 148
local nMesh, oMesh = i32(mo + 72), i32(mo + 76)
local model: Model = {
name = (string.match(buffer.readstring(b, base + mo, 64), "^[^%z]*")) :: string,
kind = i32(mo + 64),
radius = readf32(b, base + mo + 68),
vertexCount = i32(mo + 80),
vertexIndex = i32(mo + 84),
tangentIndex = i32(mo + 88),
eyeballs = i32(mo + 100),
meshes = {},
}
if nMesh < 0 or nMesh > 4096 or (nMesh > 0 and not inside(mo + oMesh, nMesh * 116)) or model.vertexCount < 0 or model.vertexCount > maxVerts or model.vertexIndex < 0 then
return nil, "model " .. model.name .. ": bad mesh table"
end
for k = 0, nMesh - 1 do
local me = mo + oMesh + k * 116
local mesh: Mesh = {
material = i32(me),
vertexCount = i32(me + 8),
vertexOffset = i32(me + 12),
materialType = i32(me + 24),
materialParam = i32(me + 28),
id = i32(me + 32),
center = vec(me + 36),
flexes = {},
lodVertices = {},
}
for l = 0, 7 do
mesh.lodVertices[l + 1] = i32(me + 52 + l * 4)
end
if mesh.vertexCount < 0 or mesh.vertexOffset < 0 or mesh.vertexOffset + mesh.vertexCount > model.vertexCount then
return nil, "mesh " .. k .. ": vertex range outside its model"
end
local nFlex, oFlex = i32(me + 16), i32(me + 20)
if nFlex < 0 or nFlex > 4096 or (nFlex > 0 and not inside(me + oFlex, nFlex * 60)) then
return nil, "mesh " .. k .. ": bad flex table"
end
for f = 0, nFlex - 1 do
local fo = me + oFlex + f * 60
local nv, vo = i32(fo + 20), i32(fo + 24)
local kind = readu8(b, base + fo + 32)
local stride = if kind == 1 then 18 else 16
totalFlex += math.max(nv, 0)
if nv < 0 or totalFlex > maxVerts or (nv > 0 and not inside(fo + vo, nv * stride)) then
return nil, "flex " .. f .. ": bad vertex animation table"
end
local flex: Flex = { desc = i32(fo), targets = vec(fo + 4, 4), partner = i32(fo + 28), kind = kind, deltas = {} }
local fixed = bit32.band(h.flags, 0x200000) ~= 0
local scale = h.vertAnimScale
for v = 0, nv - 1 do
local a = base + fo + vo + v * stride
local d = { readu16(b, a) }
for c = 0, 5 do
d[c + 2] = if fixed then readi16(b, a + 4 + c * 2) * scale else HALF[readu16(b, a + 4 + c * 2)]
end
d[8] = readu8(b, a + 3) / 255
d[9] = readu8(b, a + 2) / 255
d[10] = if kind == 1 then readi16(b, a + 16) / 32767 else 0
flex.deltas[v + 1] = d
end
table.insert(mesh.flexes, flex)
end
table.insert(model.meshes, mesh)
end
table.insert(part.models, model)
end
h.bodyParts[p + 1] = part
end
local nAtt, oAtt = i32(240), i32(244)
e = table_(nAtt, oAtt, 92, 4096, "attachment")
if e then
return nil, e
end
h.attachments = {}
for i = 0, nAtt - 1 do
local o = oAtt + i * 92
h.attachments[i + 1] = { name = str(o + i32(o)), flags = i32(o + 4), bone = i32(o + 8), matrix = vec(o + 12, 12) }
end
local nNodes, oNodeNames = i32(248), i32(256)
h.nodes = {}
if nNodes > 0 and nNodes <= 1024 and inside(oNodeNames, nNodes * 4) then
for i = 0, nNodes - 1 do
h.nodes[i + 1] = str(i32(oNodeNames + i * 4))
end
end
local nDesc, oDesc = i32(260), i32(264)
e = table_(nDesc, oDesc, 4, 65536, "flex description")
if e then
return nil, e
end
h.flexDescs = {}
for i = 0, nDesc - 1 do
local o = oDesc + i * 4
h.flexDescs[i + 1] = str(o + i32(o))
end
local nFc, oFc = i32(268), i32(272)
e = table_(nFc, oFc, 20, 65536, "flex controller")
if e then
return nil, e
end
h.flexControllers = {}
for i = 0, nFc - 1 do
local o = oFc + i * 20
h.flexControllers[i + 1] = { type = str(o + i32(o)), name = str(o + i32(o + 4)), localToGlobal = i32(o + 8), min = readf32(b, base + o + 12), max = readf32(b, base + o + 16) }
end
local nRule, oRule = i32(276), i32(280)
e = table_(nRule, oRule, 12, 65536, "flex rule")
if e then
return nil, e
end
h.flexRules = {}
for i = 0, nRule - 1 do
local o = oRule + i * 12
local n, at = i32(o + 4), i32(o + 8)
local ops = {}
if n > 0 and n <= 65536 and inside(o + at, n * 8) then
for k = 0, n - 1 do
local oo = o + at + k * 8
local op = i32(oo)
ops[k + 1] = { op = op, value = if op == 1 then readf32(b, base + oo + 4) else i32(oo + 4) }
end
end
h.flexRules[i + 1] = { flex = i32(o), ops = ops }
end
local nPose, oPose = i32(300), i32(304)
e = table_(nPose, oPose, 20, 4096, "pose parameter")
if e then
return nil, e
end
h.poseParameters = {}
for i = 0, nPose - 1 do
local o = oPose + i * 20
h.poseParameters[i + 1] = { name = str(o + i32(o)), flags = i32(o + 4), start = readf32(b, base + o + 8), ["end"] = readf32(b, base + o + 12), loop = readf32(b, base + o + 16) }
end
h.surfaceProp = str(i32(308))
local kvAt, kvSize = i32(312), i32(316)
h.keyValues = if kvSize > 0 and inside(kvAt, 1) then string.sub(str(kvAt), 1, kvSize) else ""
local nInc, oInc = i32(336), i32(340)
e = table_(nInc, oInc, 8, 4096, "include model")
if e then
return nil, e
end
h.includeModels = {}
for i = 0, nInc - 1 do
local o = oInc + i * 8
local l, f = i32(o), i32(o + 4)
h.includeModels[i + 1] = { label = if l ~= 0 then str(o + l) else "", file = if f ~= 0 then str(o + f) else "" }
end
local nameAt = i32(348)
h.animBlockName = if nameAt > 0 then str(nameAt) else ""
local nBlk, oBlk = i32(352), i32(356)
h.animBlocks = {}
if nBlk > 0 and nBlk <= 65536 and inside(oBlk, nBlk * 8) then
for i = 0, nBlk - 1 do
h.animBlocks[i + 1] = { i32(oBlk + i * 8), i32(oBlk + i * 8 + 4) }
end
end
return h :: Header, nil
end
return Mdl
+121
View File
@@ -0,0 +1,121 @@
--!strict
-- model/sourcemdl/Phy: ".phy" collision models (phyheader_t; "VPHY" or legacy IVP compact surfaces: the ledge tree's
-- leaf convex hulls; the trailing KeyValues text), from Source SDK 2013 public/phyfile.h, the IVP compact surface
-- layout (ivp_compact_surface.hxx, ivp_compact_ledge.hxx) and SourceIO (MIT) notes; no code taken.
local Phy = {}
local readi32, readu32, readu16, readi16, readf32 = buffer.readi32, buffer.readu32, buffer.readu16, buffer.readi16, buffer.readf32
export type Hull = { positions: { number }, indices: { number }, bone: number }
export type Solid = { hulls: { Hull }, version: number?, kind: number? }
export type Physics = { checksum: number, solids: { Solid }, text: string }
local METERS = 1 / 0.0254
local function surface(b: buffer, at: number, limit: number, out: Solid, budget: { number }): string?
if at + 48 > limit then
return "truncated collision surface"
end
local root = readi32(b, at + 32)
local seen = 0
local function ledge(lo: number): string?
if lo + 16 > limit then
return "truncated ledge"
end
local pts, client, nTri = readi32(b, lo), readi32(b, lo + 4), readi16(b, lo + 12)
if nTri < 0 or lo + 16 + nTri * 16 > limit then
return "bad ledge"
end
budget[1] -= nTri
if budget[1] < 0 then
return "limit: too many collision triangles"
end
local map: { [number]: number } = {}
local hull: Hull = { positions = {}, indices = {}, bone = client }
for t = 0, nTri - 1 do
local to = lo + 16 + t * 16
for e = 0, 2 do
local id = readu16(b, to + 4 + e * 4)
local v = map[id]
if not v then
local po = lo + pts + id * 16
if po < 0 or po + 12 > limit then
return "collision vertex out of range"
end
local x, y, z = readf32(b, po), readf32(b, po + 4), readf32(b, po + 8)
table.insert(hull.positions, x * METERS)
table.insert(hull.positions, z * METERS)
table.insert(hull.positions, -y * METERS)
v = #hull.positions // 3 - 1
map[id] = v
end
table.insert(hull.indices, v)
end
end
table.insert(out.hulls, hull)
return nil
end
local function node(no: number, depth: number): string?
seen += 1
if depth > 64 or seen > 65536 or no + 28 > limit or no < at then
return "bad ledge tree"
end
local right, led = readi32(b, no), readi32(b, no + 4)
if right == 0 then
if led == 0 then
return nil
end
return ledge(no + led)
end
local e = node(no + 28, depth + 1)
if e then
return e
end
return node(no + right, depth + 1)
end
if root <= 0 then
return "bad ledge tree root"
end
return node(at + root, 0)
end
function Phy.parse(b: buffer, maxTriangles: number?): (Physics?, string?)
local size = buffer.len(b)
if size < 16 then
return nil, "truncated phy header"
end
local hsize, nSolids = readi32(b, 0), readi32(b, 8)
if hsize < 16 or hsize > size or nSolids < 0 or nSolids > 1024 then
return nil, "bad phy header"
end
local out: Physics = { checksum = readu32(b, 12), solids = {}, text = "" }
local budget = { maxTriangles or 2 ^ 22 }
local p = hsize
for _ = 1, nSolids do
if p + 4 > size then
return nil, "truncated phy solid"
end
local n = readi32(b, p)
if n < 0 or p + 4 + n > size then
return nil, "truncated phy solid"
end
local s: Solid = { hulls = {} }
local at = p + 4
if n >= 28 and buffer.readstring(b, at, 4) == "VPHY" then
s.version, s.kind = readu16(b, at + 4), readu16(b, at + 6)
at += 28
end
local e = surface(b, at, p + 4 + n, s, budget)
if e then
return nil, e
end
table.insert(out.solids, s)
p += 4 + n
end
if p < size then
out.text = (string.match(buffer.readstring(b, p, size - p), "^[^%z]*")) :: string
end
return out, nil
end
return Phy
+180
View File
@@ -0,0 +1,180 @@
--!strict
-- model/sourcemdl/Vtx: ".vtx" optimized strips (version 7: body part / model / LOD / mesh / strip group / strip
-- headers, 9-byte vertices, u16 indices; the 33 / 35-byte strip group / strip headers of later branches too), from
-- Source SDK 2013 public/optimize.h.
local Vtx = {}
local readi32, readu16, readu8, readi16, readf32 = buffer.readi32, buffer.readu16, buffer.readu8, buffer.readi16, buffer.readf32
export type Mesh = { flags: number, indices: { number } } -- triangles of mesh-relative vertex ids, file winding
export type Lod = { switchPoint: number, meshes: { Mesh } }
export type Strips = {
checksum: number,
lods: number,
parts: { { { Lod } } }, -- parts[p][m][lod]
replacements: { { { material: number, name: string } } }, -- per LOD
maxBonesPerStrip: number,
extended: boolean,
}
local function walk(b: buffer, ext: boolean, maxIndices: number): (Strips?, string?)
local size = buffer.len(b)
local sgStride, stStride = if ext then 33 else 25, if ext then 35 else 27
local function inside(o: number, n: number): boolean
return o >= 0 and n >= 0 and o + n <= size
end
local nParts, oParts = readi32(b, 28), readi32(b, 32)
if nParts < 0 or nParts > 4096 or not inside(oParts, nParts * 8) then
return nil, "bad vtx body part table"
end
local total = 0
local parts = {}
for p = 0, nParts - 1 do
local po = oParts + p * 8
local nModels, oModels = readi32(b, po), readi32(b, po + 4)
if nModels < 0 or nModels > 4096 or not inside(po + oModels, nModels * 8) then
return nil, "bad vtx model table"
end
local models = {}
for m = 0, nModels - 1 do
local mo = po + oModels + m * 8
local nLods, oLods = readi32(b, mo), readi32(b, mo + 4)
if nLods < 0 or nLods > 8 or not inside(mo + oLods, nLods * 12) then
return nil, "bad vtx lod table"
end
local lods = {}
for l = 0, nLods - 1 do
local lo = mo + oLods + l * 12
local nMesh, oMesh = readi32(b, lo), readi32(b, lo + 4)
if nMesh < 0 or nMesh > 4096 or not inside(lo + oMesh, nMesh * 9) then
return nil, "bad vtx mesh table"
end
local meshes = {}
for k = 0, nMesh - 1 do
local me = lo + oMesh + k * 9
local nGroups, oGroups = readi32(b, me), readi32(b, me + 4)
if nGroups < 0 or nGroups > 4096 or not inside(me + oGroups, nGroups * sgStride) then
return nil, "bad vtx strip group table"
end
local tris: { number } = {}
for g = 0, nGroups - 1 do
local go = me + oGroups + g * sgStride
local nv, ov, ni, oi = readi32(b, go), readi32(b, go + 4), readi32(b, go + 8), readi32(b, go + 12)
local ns, os = readi32(b, go + 16), readi32(b, go + 20)
if not inside(go + ov, nv * 9) or not inside(go + oi, ni * 2) or ns < 0 or ns > 65536 or not inside(go + os, ns * stStride) then
return nil, "bad vtx strip group"
end
total += ni
if total > maxIndices then
return nil, "limit: too many indices"
end
local vbase, ibase = go + ov, go + oi
local function vid(i: number): number?
if i < 0 or i >= ni then
return nil
end
local v = readu16(b, ibase + i * 2)
if v >= nv then
return nil
end
return readu16(b, vbase + v * 9 + 4)
end
local function strip(first: number, count: number, list: boolean): boolean
if list then
for i = first, first + count - 3, 3 do
local a, c, d = vid(i), vid(i + 1), vid(i + 2)
if not a or not c or not d then
return false
end
table.insert(tris, a)
table.insert(tris, c)
table.insert(tris, d)
end
else
for i = first, first + count - 3 do
local a, c, d = vid(i), vid(i + 1), vid(i + 2)
if not a or not c or not d then
return false
end
if a ~= c and c ~= d and a ~= d then
if (i - first) % 2 == 0 then
table.insert(tris, a)
table.insert(tris, c)
table.insert(tris, d)
else
table.insert(tris, c)
table.insert(tris, a)
table.insert(tris, d)
end
end
end
end
return true
end
if ns == 0 then
if not strip(0, ni, true) then
return nil, "bad vtx index"
end
end
for s = 0, ns - 1 do
local so = go + os + s * stStride
local sni, sio = readi32(b, so), readi32(b, so + 4)
local flags = readu8(b, so + 18)
if sni < 0 or sio < 0 or sio + sni > ni then
return nil, "bad vtx strip"
end
if not strip(sio, sni, bit32.band(flags, 2) == 0) then
return nil, "bad vtx index"
end
end
end
meshes[k + 1] = { flags = readu8(b, me + 8), indices = tris }
end
lods[l + 1] = { switchPoint = readf32(b, lo + 8), meshes = meshes }
end
models[m + 1] = lods
end
parts[p + 1] = models
end
local nLods = readi32(b, 20)
local reps = {}
local oRep = readi32(b, 24)
if nLods > 0 and nLods <= 8 and inside(oRep, nLods * 8) then
for l = 0, nLods - 1 do
local ro = oRep + l * 8
local n, at = readi32(b, ro), readi32(b, ro + 4)
local list = {}
if n > 0 and n <= 4096 and inside(ro + at, n * 6) then
for k = 0, n - 1 do
local eo = ro + at + k * 6
local no = eo + readi32(b, eo + 2)
local name = if no >= 0 and no < size then (string.match(buffer.readstring(b, no, math.min(size - no, 1024)), "^[^%z]*")) :: string else ""
list[k + 1] = { material = readi16(b, eo), name = name }
end
end
reps[l + 1] = list
end
end
return { checksum = readi32(b, 16), lods = nLods, parts = parts, replacements = reps, maxBonesPerStrip = readu16(b, 8), extended = ext }, nil
end
function Vtx.parse(b: buffer, maxIndices: number?): (Strips?, string?)
if buffer.len(b) < 36 then
return nil, "truncated vtx header"
end
local version = readi32(b, 0)
if version ~= 7 then
return nil, "unsupported: vtx version " .. version
end
local s, err = walk(b, false, maxIndices or 2 ^ 26)
if s then
return s, nil
end
local s2 = walk(b, true, maxIndices or 2 ^ 26)
if s2 then
return s2, nil
end
return nil, err
end
return Vtx
+92
View File
@@ -0,0 +1,92 @@
--!strict
-- model/sourcemdl/Vvd: ".vvd" vertex data ("IDSV" v4: 48-byte mstudiovertex_t records, 16-byte tangents, the LOD
-- fixup table), from Source SDK 2013 public/studio.h (vertexFileHeader_t) and Studio_LoadVertexes.
local Vvd = {}
local readi32, readu32 = buffer.readi32, buffer.readu32
export type Vertices = {
checksum: number,
lods: number,
lodCounts: { number },
count: number,
data: buffer, -- count * 48: weight f32[3], bone u8[3], numbones u8, position f32[3], normal f32[3], uv f32[2]
tangents: buffer?, -- count * 16: x, y, z, w
fixups: number,
}
-- the vertices of LOD `lod` and above, in fixup order (lod 0: every vertex, the layout the MDL meshes index)
function Vvd.parse(b: buffer, lod: number?, maxVertices: number?): (Vertices?, string?)
local size = buffer.len(b)
if size < 64 then
return nil, "truncated vvd header"
end
if buffer.readstring(b, 0, 4) ~= "IDSV" then
return nil, "not a vvd file"
end
local version = readi32(b, 4)
if version ~= 4 then
return nil, "unsupported: vvd version " .. version
end
local nLods = readi32(b, 12)
local counts = {}
for i = 0, 7 do
counts[i + 1] = readi32(b, 16 + i * 4)
end
local nFix, oFix, oVert, oTan = readi32(b, 48), readi32(b, 52), readi32(b, 56), readi32(b, 60)
local total = counts[1]
if nLods < 1 or nLods > 8 or total < 0 or total > (maxVertices or 2 ^ 24) then
return nil, "bad vvd vertex counts"
end
if oVert < 64 or oVert + total * 48 > size then
return nil, "truncated vvd vertex data"
end
local hasTan = oTan > 0 and oTan + total * 16 <= size
local want = math.clamp(lod or 0, 0, nLods - 1)
local out: Vertices = { checksum = readu32(b, 8), lods = nLods, lodCounts = counts, count = 0, data = buffer.create(0), fixups = nFix }
if nFix <= 0 then
out.count = total
out.data = buffer.create(total * 48)
buffer.copy(out.data, 0, b, oVert, total * 48)
if hasTan then
local t = buffer.create(total * 16)
buffer.copy(t, 0, b, oTan, total * 16)
out.tangents = t
end
return out, nil
end
if nFix > 65536 or oFix < 0 or oFix + nFix * 12 > size then
return nil, "bad vvd fixup table"
end
local n = 0
for i = 0, nFix - 1 do
local fl, first, cnt = readi32(b, oFix + i * 12), readi32(b, oFix + i * 12 + 4), readi32(b, oFix + i * 12 + 8)
if first < 0 or cnt < 0 or first + cnt > total then
return nil, "vvd fixup " .. i .. " out of range"
end
if fl >= want then
n += cnt
end
end
if n > total * 8 then
return nil, "bad vvd fixup table"
end
out.count = n
out.data = buffer.create(n * 48)
local tan = if hasTan then buffer.create(n * 16) else nil
local at = 0
for i = 0, nFix - 1 do
local fl, first, cnt = readi32(b, oFix + i * 12), readi32(b, oFix + i * 12 + 4), readi32(b, oFix + i * 12 + 8)
if fl >= want then
buffer.copy(out.data, at * 48, b, oVert + first * 48, cnt * 48)
if tan then
buffer.copy(tan, at * 16, b, oTan + first * 16, cnt * 16)
end
at += cnt
end
end
out.tangents = tan
return out, nil
end
return Vvd
+169
View File
@@ -0,0 +1,169 @@
--!strict
-- model/sourcemdl: Source engine studio models ("IDST" v44-49) with .vvd / .vtx (.dx90 / .dx80 / .sw) and optional .phy /
-- .ani / .vmt through opts.resolve / opts.files; Source SDK 2013 studio.h / optimize.h layouts, checked with srctools.
-- Not supported: v52+ frame animations, IK rules, movement, eyeball shading, $includemodel animations.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Input = require("@rosetta/core/Input")
local Types = require("@rosetta/Types")
local Mdl = require("@rosetta/model/sourcemdl/Mdl")
local Vvd = require("@rosetta/model/sourcemdl/Vvd")
local Vtx = require("@rosetta/model/sourcemdl/Vtx")
local Phy = require("@rosetta/model/sourcemdl/Phy")
local Build = require("@rosetta/model/sourcemdl/Build")
local Material = require("@rosetta/model/sourcemdl/Material")
-- ------------------------------------------------------------------------------------------------ contract
local SourceMdl = {
name = "sourcemdl",
category = "model",
extensions = { "mdl" },
mime = { "model/x-source-mdl" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Half", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/SourceAnim", "codecs/text/KeyValues" },
caps = { decode = true, encode = false, skins = true, morph = true, animation = true, lods = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
name: string?, -- the .mdl file name: its stem names the sibling files (default: the stem of the header name)
vvd: (buffer | string)?,
vtx: (buffer | string)?,
phy: (buffer | string)?,
ani: (buffer | string)?,
bodies: { number }?, -- 1-based model per body part, default 1
lod: number?, -- 1-based LOD for the primitive indices, default 1
animations: boolean?, -- default true
physics: boolean?, -- default true: read the .phy
materials: boolean?, -- default true: resolve materials/<cdmaterials><texture>.vmt
maxVertices: number?, -- default 2^24
maxFrames: number?, -- per animation, default 65536
}
-- ------------------------------------------------------------------------------------------------ constants
local VTX = { "dx90.vtx", "dx80.vtx", "sw.vtx", "vtx" }
-- ------------------------------------------------------------------------------------------------ sniff
function SourceMdl.sniff(r: Bytes.Reader): number
if r.limit - r.base < 8 or r:peek(4) ~= "IDST" then
return 0
end
local v = buffer.readi32(r.buf, r.base + 4)
return if v >= 44 and v <= 49 then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function stems(opts: DecodeOptions?, header: string): { string }
local out: { string } = {}
local function add(s: string?)
if s and s ~= "" and not table.find(out, s) then
table.insert(out, s)
end
end
local n = opts and opts.name
if type(n) == "string" then
add((string.gsub(string.match(n, "([^/\\]+)$") or n, "%.[mM][dD][lL]$", "")))
end
local h = string.gsub(header, "\\", "/")
add((string.gsub(string.match(h, "([^/]+)$") or h, "%.[mM][dD][lL]$", "")))
add("models/" .. (string.gsub(h, "%.[mM][dD][lL]$", "")))
return out
end
local function sibling(opts: DecodeOptions?, direct: (buffer | string)?, names: { string }, exts: { string }): (buffer?, string?)
if direct then
return Bytes.toBuffer(direct), nil
end
for _, s in names do
for _, e in exts do
local uri = s .. "." .. e
local b = Input.sibling(opts, uri)
if b then
return b, uri
end
end
end
return nil, nil
end
function SourceMdl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local size = r.limit - r.base
if size < 8 then
return nil, Err.new(Err.TRUNCATED, "header", 0)
end
if r:peek(4) ~= "IDST" then
return nil, Err.new(Err.CORRUPT, "bad magic", 0)
end
local version = buffer.readi32(r.buf, r.base + 4)
if version < 44 or version > 49 then
return nil, Err.new(Err.UNSUPPORTED, "studio model version " .. version, 4)
end
local h, perr = Mdl.parse(r.buf, r.base, size, opts)
if not h then
return nil, Err.from(perr)
end
local warnings: { string } = {}
local names = stems(opts, h.name)
local inp: Build.Inputs = { warnings = warnings }
local maxV = opts and opts.maxVertices or 2 ^ 24
local vvdBuf = sibling(opts, opts and opts.vvd, names, { "vvd" })
if vvdBuf then
local v, e = Vvd.parse(vvdBuf, 0, maxV)
if not v then
return nil, Err.from("vvd: " .. tostring(e))
end
if v.checksum ~= h.checksum then
table.insert(warnings, "vvd checksum differs from the mdl")
end
inp.vvd = v
else
table.insert(warnings, "no .vvd: no geometry")
end
local vtxBuf, vtxName = sibling(opts, opts and opts.vtx, names, VTX)
if vtxBuf then
local s, e = Vtx.parse(vtxBuf, maxV * 8)
if not s then
return nil, Err.from("vtx: " .. tostring(e))
end
if bit32.band(s.checksum, 0xFFFFFFFF) ~= h.checksum then
table.insert(warnings, "vtx checksum differs from the mdl")
end
inp.vtx = s
else
table.insert(warnings, "no .vtx: no geometry")
end
if not (opts and opts.physics == false) then
local phyBuf = sibling(opts, opts and opts.phy, names, { "phy" })
if phyBuf then
local p, e = Phy.parse(phyBuf)
if p then
inp.phy = p
else
table.insert(warnings, "phy: " .. tostring(e))
end
end
end
if #h.animBlocks > 1 and not (opts and opts.animations == false) then
local ani: buffer? = if opts and opts.ani then Bytes.toBuffer(opts.ani) else nil
local an = string.gsub(h.animBlockName, "\\", "/")
if not ani and an ~= "" then
ani = Input.sibling(opts, an) or Input.sibling(opts, string.match(an, "([^/]+)$") or an)
end
inp.ani = ani
end
local scene, berr = Build.scene(h, r.buf, r.base, size, inp, opts)
if not scene then
return nil, Err.from(berr)
end
if not (opts and opts.materials == false) then
Material.apply(scene, h.textures, h.cdmaterials, opts, warnings)
end
local src = scene.meta.source :: { [string]: any }
src.vtx = vtxName
return scene, nil
end
return SourceMdl
+166
View File
@@ -0,0 +1,166 @@
-- codecs/text/KeyValues tests: text against srctools' Keyvalues.parse, trees written by the python vdf module, binary
-- KeyValues by vdf.binary_dumps; write round trips, conditions, #include / #base, the entity lump, errors, fuzz.
-- Fixtures: tools/fixtures/keyvalues.py.
local T = require("@tests/T")
local KeyValues = require("@rosetta/codecs/text/KeyValues")
local Err = require("@rosetta/core/Err")
local Fx = require("@tests/gen/keyvalues")
local t = T.suite("keyvalues")
local function canon(b: KeyValues.Block, typed: boolean?): string
local out = { "{" }
for _, p in b do
table.insert(out, #p.key .. ":" .. p.key .. "=")
local v = p.value
if type(v) == "table" then
table.insert(out, canon(v, typed))
elseif typed and p.type then
local tag = ({ int32 = "i32", float32 = "f32", pointer = "ptr", color = "col", uint64 = "u64", int64 = "i64", wstring = "wstr" } :: any)[p.type]
if p.type == "float32" then
table.insert(out, tag .. "f" .. string.format("%.17g", v))
elseif type(v) == "string" and p.type ~= "wstring" then
table.insert(out, tag .. "i" .. v)
else
table.insert(out, tag .. "i" .. string.format("%d", v))
end
else
table.insert(out, "s" .. #v .. ":" .. v)
end
end
table.insert(out, "}")
return table.concat(out)
end
for i, c in Fx.text do
local b, err = KeyValues.parse(c.data)
t:check(b ~= nil, "text " .. i .. ": " .. tostring(err))
if b then
t:eq(canon(b), c.canon, "text " .. i .. ": same pairs as srctools")
local s = KeyValues.write(b) :: string
local b2 = KeyValues.parse(s)
t:eq(b2 and canon(b2), c.canon, "text " .. i .. ": write round trip")
end
end
for i, c in Fx.written do
local b, err = KeyValues.parse(c.data)
t:check(b ~= nil, "vdf.dumps " .. i .. ": " .. tostring(err))
t:eq(b and canon(b), c.canon, "vdf.dumps " .. i .. ": pairs")
if b then
local b2 = KeyValues.parse(KeyValues.write(b) :: string)
t:eq(b2 and canon(b2), c.canon, "vdf.dumps " .. i .. ": round trip")
end
end
for i, c in Fx.binary do
local b, err = KeyValues.readBinary(c.data)
t:check(b ~= nil, "binary " .. i .. ": " .. tostring(err))
if b then
t:eq(canon(b, true), c.canon, "binary " .. i .. ": values as vdf.binary_loads")
local w = KeyValues.writeBinary(b) :: buffer
t:eq(buffer.tostring(w), c.data, "binary " .. i .. ": identical bytes")
end
t:check(KeyValues.isBinary(buffer.fromstring(c.data), 0, #c.data), "binary " .. i .. ": sniffed")
end
do
-- conditions
t:check(KeyValues.condition("$WIN32"), "WIN32 by default")
t:check(not KeyValues.condition("$X360"), "X360 off")
t:check(KeyValues.condition("!$X360"), "negation")
t:check(KeyValues.condition("$X360 || $WIN32"), "or")
t:check(not KeyValues.condition("$WIN32 && $OSX"), "and")
t:check(KeyValues.condition("$OSX", { OSX = true }), "defines")
local b = KeyValues.parse('"r" { "a" "1" [$X360] "a" "2" [$X360||$WIN32] }') :: KeyValues.Block
t:eq(KeyValues.get(b, "r/a"), "2", "|| in a condition")
local keep = KeyValues.parse('"r" { "a" "1" [$X360] "a" "2" [$WIN32] }', { defines = false }) :: KeyValues.Block
local r = KeyValues.find(keep, "r") :: KeyValues.Pair
t:eq(#r.value, 2, "defines = false keeps both")
t:eq(r.value[1].cond, "$X360", "cond kept")
t:check(string.find(KeyValues.write(keep) :: string, '"a"\t"1" [$X360]', 1, true) ~= nil, "cond written")
-- #include / #base
local files = {
["base.res"] = '"r" { "a" "base" "b" "base" "sub" { "x" "1" "y" "1" } }',
["inc.res"] = '"extra" { "k" "v" }',
}
local main = '#base "base.res"\n#include "inc.res"\n"r" { "a" "main" "sub" { "x" "2" } }'
local m = KeyValues.parse(main, { resolve = function(n: string): string?
return files[n]
end }) :: KeyValues.Block
t:eq(KeyValues.get(m, "r/a"), "main", "#base: main wins")
t:eq(KeyValues.get(m, "r/b"), "base", "#base: missing key added")
t:eq(KeyValues.get(m, "r/sub/x"), "2", "#base: nested merge keeps main")
t:eq(KeyValues.get(m, "r/sub/y"), "1", "#base: nested merge adds")
t:eq(KeyValues.get(m, "extra/k"), "v", "#include appended")
t:eq(m[#m].key, "extra", "#include after the file's keys")
local raw = KeyValues.parse(main) :: KeyValues.Block
t:eq(raw[1].key, "#base", "no resolve: directive kept as a pair")
local _, e1 = KeyValues.parse(main, { resolve = function()
return nil
end })
t:eq(e1 and e1.code, Err.IO, "missing include")
local _, e2 = KeyValues.parse('#include "self"', { resolve = function()
return '#include "self"'
end })
t:eq(e2 and e2.code, Err.LIMIT, "include loop")
-- objects
local o = KeyValues.toObject(KeyValues.parse('"r" { "d" "1" "d" "2" "x" "y" }') :: KeyValues.Block)
t:eq(#o.r.d, 2, "duplicates -> array")
local last = KeyValues.toObject(KeyValues.parse('"r" { "d" "1" "d" "2" }') :: KeyValues.Block, { duplicates = "last" })
t:eq(last.r.d, "2", "duplicates last")
local back = KeyValues.fromObject(o) :: KeyValues.Block
t:eq(canon(back), "{1:r={1:d=s1:11:d=s1:21:x=s1:y}}", "fromObject repeats array keys in order")
-- escapes off
local ne = KeyValues.parse('"p" "C:\\maps\\x"', { escapes = false }) :: KeyValues.Block
t:eq(ne[1].value, "C:\\maps\\x", "escapes off")
-- entity lump
local ents = KeyValues.entities('{\n"classname" "worldspawn"\n"mapversion" "1"\n}\n{\n"classname" "logic_relay"\n"OnTrigger" "a,b,,0,-1"\n"OnTrigger" "c,d,,0,-1"\n}\n\0') :: { KeyValues.Block }
t:eq(#ents, 2, "entities")
t:eq(#KeyValues.all(ents[2], "ontrigger"), 2, "repeated outputs kept")
local again = KeyValues.entities(KeyValues.writeEntities(ents) :: string) :: { KeyValues.Block }
t:eq(canon(again[2]), canon(ents[2]), "entity round trip")
-- 64-bit binary values
local big = KeyValues.writeBinary({ { key = "id", value = "76561197960287930", type = "uint64" }, { key = "n", value = -5, type = "int64" }, { key = "w", value = "\u{e9}\u{1F600}", type = "wstring" } }) :: buffer
local rb = KeyValues.readBinary(big) :: KeyValues.Block
t:eq(rb[1].value, "76561197960287930", "uint64 above 2^53 as digits")
t:eq(rb[2].value, -5, "negative int64")
t:eq(rb[3].value, "\u{e9}\u{1F600}", "wide string")
-- errors
local function code(s: string): string?
local _, e = KeyValues.parse(s)
return e and e.code
end
t:eq(code('"r" { "a" "1"'), Err.TRUNCATED, "unclosed block")
t:eq(code('"r" "unterminated'), Err.TRUNCATED, "unterminated string")
t:eq(code('"r" { } }'), Err.CORRUPT, "extra brace")
t:eq(code("{ }"), Err.CORRUPT, "block without a key")
t:eq(code(string.rep('"a" {', 300) .. string.rep("}", 300)), Err.LIMIT, "depth limit")
local _, be = KeyValues.readBinary(buffer.fromstring("\1key\0no end"))
t:eq(be and be.code, Err.TRUNCATED, "binary truncated")
local _, we = KeyValues.write({ { key = "k", value = function() end } } :: any)
t:eq(we and we.code, Err.ARG, "unwritable value")
end
local samples = {}
for _, c in Fx.text do
table.insert(samples, c.data)
end
t:fuzz("parse", function(b: buffer)
return KeyValues.parse(b)
end, samples)
local bsamples = {}
for _, c in Fx.binary do
table.insert(bsamples, c.data)
end
t:fuzz("readBinary", function(b: buffer)
return KeyValues.readBinary(b)
end, bsamples)
t:fuzz("entities", function(b: buffer)
return KeyValues.entities(buffer.tostring(b))
end, { '{\n"classname" "worldspawn"\n}\n{ "a" "b" }' })
t:done()
+104
View File
@@ -0,0 +1,104 @@
-- codecs/model/SourceAnim tests: run-length anim values (repeat of value[valid], valid = 0), Quaternion48 / 64,
-- Vector48 and a bone record chain, against values built here from the studio.h bit layouts.
local T = require("@tests/T")
local SourceAnim = require("@rosetta/codecs/model/SourceAnim")
local Half = require("@rosetta/codecs/image/Half")
local t = T.suite("sourceanim")
local function shorts(list: { number }): buffer
local b = buffer.create(#list * 2)
for i, v in list do
buffer.writei16(b, (i - 1) * 2, v)
end
return b
end
-- runs: { valid 2, total 4 } 10 20 (then 20 20); { valid 1, total 2 } -5 (then -5)
local runs = buffer.create(12)
buffer.writeu8(runs, 0, 2)
buffer.writeu8(runs, 1, 4)
buffer.writei16(runs, 2, 10)
buffer.writei16(runs, 4, 20)
buffer.writeu8(runs, 6, 1)
buffer.writeu8(runs, 7, 2)
buffer.writei16(runs, 8, -5)
local v = SourceAnim.values(runs, 0, 10, 6)
t:eq(table.concat(v :: { number }, ","), "10,20,20,20,-5,-5", "values: runs and repeats")
for k = 0, 5 do
t:eq(SourceAnim.value(runs, 0, 10, k), (v :: { number })[k + 1], "value " .. k)
end
t:eq(SourceAnim.values(runs, 0, 10, 7), nil, "values past the data")
t:eq(SourceAnim.value(runs, 0, 10, 6), nil, "value past the data")
local zero = shorts({ 0x0300 })
t:eq(table.concat(SourceAnim.values(zero, 0, 2, 3) :: { number }, ","), "768,768,768", "valid = 0 repeats the run header (as the engine)")
-- Quaternion48: x = 0.5, y = -0.25, z = 0.125, w < 0
local q48 = buffer.create(6)
buffer.writeu16(q48, 0, 32768 + 16384)
buffer.writeu16(q48, 2, 32768 - 8192)
buffer.writeu16(q48, 4, (16384 + 2048) + 32768)
local x, y, z, w = SourceAnim.quat48(q48, 0)
t:check(x == 0.5 and y == -0.25 and z == 0.125 and math.abs(w + math.sqrt(1 - 0.25 - 0.0625 - 0.015625)) < 1e-12, "quat48")
-- Quaternion64: 21-bit fields
local xs, ys, zs = 1048576 + 524288, 1048576 - 262144, 1048576 + 1
local lo = xs + (ys % 2048) * 2097152
local hi = ys // 2048 + zs * 1024
local q64 = buffer.create(8)
buffer.writeu32(q64, 0, lo)
buffer.writeu32(q64, 4, hi)
x, y, z, w = SourceAnim.quat64(q64, 0)
t:check(math.abs(x - 524288 / 1048576.5) < 1e-12 and math.abs(y + 262144 / 1048576.5) < 1e-12 and math.abs(z - 1 / 1048576.5) < 1e-12 and w > 0, "quat64")
buffer.writeu32(q64, 4, hi + 0x80000000)
local _, _, _, w2 = SourceAnim.quat64(q64, 0)
t:check(w2 < 0 and math.abs(w2 + w) < 1e-12, "quat64 w sign")
local v48 = buffer.create(6)
buffer.writeu16(v48, 0, Half.fromFloat(1.5))
buffer.writeu16(v48, 2, Half.fromFloat(-2))
buffer.writeu16(v48, 4, Half.fromFloat(0.25))
local a, b, c = SourceAnim.vec48(v48, 0)
t:check(a == 1.5 and b == -2 and c == 0.25, "vec48")
-- a chain: bone 1 animated rotation x + raw position; bone 0 raw rotation (delta flag off)
local bones = {
{ pos = { 1, 2, 3 }, quat = { 0, 0, 0, 1 }, rot = { 0, 0, 0 }, posScale = { 1, 1, 1 }, rotScale = { 1, 1, 1 } },
{ pos = { 4, 5, 6 }, quat = { 0, 0, 0, 1 }, rot = { 0.1, 0.2, 0.3 }, posScale = { 0.5, 0.5, 0.5 }, rotScale = { 0.01, 0.01, 0.01 } },
}
local chain = buffer.create(64)
-- record 0: bone 1, ANIMROT | RAWPOS, next = 4 + 6 + 6 + 6
buffer.writeu8(chain, 0, 1)
buffer.writeu8(chain, 1, 0x08 + 0x01)
buffer.writei16(chain, 2, 22)
buffer.writei16(chain, 4, 12) -- x values at 4 + 12 (after the valueptr and Vector48)
buffer.writeu16(chain, 10, Half.fromFloat(7))
buffer.writeu16(chain, 12, Half.fromFloat(8))
buffer.writeu16(chain, 14, Half.fromFloat(9))
buffer.writeu8(chain, 16, 2)
buffer.writeu8(chain, 17, 2)
buffer.writei16(chain, 18, 10)
buffer.writei16(chain, 20, -10)
-- record 1 at 22: bone 0, RAWROT, last
buffer.writeu8(chain, 22, 0)
buffer.writeu8(chain, 23, 0x02)
buffer.writei16(chain, 24, 0)
buffer.writeu16(chain, 26, 32768)
buffer.writeu16(chain, 28, 32768)
buffer.writeu16(chain, 30, 16384)
local tracks, err = SourceAnim.decode(chain, 0, 32, bones, 2)
t:check(tracks, "decode: " .. tostring(err))
if tracks then
local t1, t0 = tracks[2], tracks[1]
t:eq(table.concat(t1.pos, ","), "7,8,9,7,8,9", "raw position")
local qx, qy, qz, qw = SourceAnim.angles(0.1 - 0.1, 0.2, 0.3)
t:check(math.abs(t1.rot[5] - qx) < 1e-12 and math.abs(t1.rot[6] - qy) < 1e-12 and math.abs(t1.rot[7] - qz) < 1e-12 and math.abs(t1.rot[8] - qw) < 1e-12, "animated rotation, frame 1")
t:eq(table.concat(t0.rot, ","), "0,0,0,1,0,0,0,1", "raw rotation")
t:eq(table.concat(t0.pos, ","), "1,2,3,1,2,3", "rest position without position data")
end
t:eq(SourceAnim.decode(chain, 0, 20, bones, 2), nil, "truncated chain")
local junk = { buffer.tostring(chain), buffer.tostring(runs) }
t:fuzz("decode", function(bb: buffer)
return SourceAnim.decode(bb, 0, buffer.len(bb), bones, 4)
end, junk)
t:done()
+62
View File
@@ -0,0 +1,62 @@
-- data/vdf tests: KeyValues text written by the python vdf module decodes to what vdf.loads gives, encodes back;
-- binary KeyValues by sniffing; pair lists; sniff; fuzz. Fixtures: tools/fixtures/keyvalues.py.
local T = require("@tests/T")
local Vdf = require("@rosetta/data/vdf")
local Bytes = require("@rosetta/core/Bytes")
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Canon = require("@tests/data/Canon")
local Fx = require("@tests/gen/keyvalues")
local t = T.suite("data/vdf")
t:eq(Vdf.name, "vdf", "name")
t:check(Vdf.caps.decode and Vdf.caps.encode, "caps")
local function dec(s: string, opts: any?): (any, any)
return Vdf.decode(Bytes.reader(buffer.fromstring(s)), opts)
end
for i, c in Fx.objects do
local v, err = dec(c.data)
t:check(v ~= nil, "vdf.dumps " .. i .. ": " .. tostring(err))
t:eq(Canon.of(v), c.canon, "vdf.dumps " .. i .. ": as vdf.loads")
local back = dec(buffer.tostring(Vdf.encode(v) :: buffer))
t:eq(Canon.of(back), c.canon, "vdf.dumps " .. i .. ": encode round trip")
t:check(Vdf.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, "vdf.dumps " .. i .. ": sniff")
end
for i, c in Fx.binary do
local v, err = dec(c.data)
t:check(type(v) == "table" and v.shortcuts ~= nil, "binary " .. i .. ": " .. tostring(err))
local p = dec(c.data, { pairs = true })
t:eq(buffer.tostring(Vdf.encode(p, { binary = true }) :: buffer), c.data, "binary " .. i .. ": pairs round trip")
end
do
local v = dec('"AppState"\n{\n\t"appid"\t"440"\n\t"InstalledDepots"\n\t{\n\t\t"441" { "manifest" "1" }\n\t}\n\t"x" "1"\n\t"x" "2"\n}\n')
t:eq(v.AppState.appid, "440", "acf value")
t:eq(v.AppState.InstalledDepots["441"].manifest, "1", "nested")
t:eq(#v.AppState.x, 2, "duplicates as array")
t:eq(table.concat(Types.keys(v.AppState), ","), "appid,InstalledDepots,x", "key order")
local s = buffer.tostring(Vdf.encode(v) :: buffer)
t:check(string.find(s, '\t"x"\t"1"\n\t"x"\t"2"\n', 1, true) ~= nil, "array written as repeated keys")
local o = Types.object()
Types.set(o, "b", true)
Types.set(o, "n", 3)
t:eq(buffer.tostring(Vdf.encode({ r = o }) :: buffer), '"r"\n{\n\t"b"\t"1"\n\t"n"\t"3"\n}\n', "encode typed values")
local _, e = dec('"r" {')
t:eq(e and e.code, Err.TRUNCATED, "truncated")
local _, ee = Vdf.encode({ r = { function() end } })
t:eq(ee and ee.code, Err.ARG, "unwritable")
t:eq(Vdf.sniff(Bytes.reader(buffer.fromstring("{}"))), 0, "json is not vdf")
end
local samples = {}
for i = 1, 10 do
table.insert(samples, Fx.objects[i].data)
table.insert(samples, Fx.binary[i].data)
end
t:fuzz("decode", function(b: buffer)
return Vdf.decode(Bytes.reader(b))
end, samples)
t:done()
+319
View File
@@ -0,0 +1,319 @@
-- model/sourcemdl tests: generated MDL v44 / v48 / v49 + VVD / VTX / PHY / ANI against the writer's exact values and
-- srctools' reading of the same files. Fixtures: tools/fixtures/sourcemdl.py.
local T = require("@tests/T")
local F = require("@rosetta")
local SourceMdl = require("@rosetta/model/sourcemdl")
local Bytes = require("@rosetta/core/Bytes")
local Err = require("@rosetta/core/Err")
local Mat4 = require("@rosetta/codecs/model/Mat4")
local Types = require("@rosetta/Types")
local Fx = require("@tests/gen/sourcemdl")
local t = T.suite("sourcemdl")
t:eq(SourceMdl.name, "sourcemdl", "name")
t:eq(SourceMdl.category, "model", "category")
local function floats(acc: any): { number }
local rd = Types.Scene.reader(acc) :: any
local out = {}
for i = 0, acc.count - 1 do
for c = 0, acc.components - 1 do
table.insert(out, rd(i, c))
end
end
return out
end
local function near(a: { number }, b: { number }, tol: number): boolean
if #a ~= #b then
return false
end
for i = 1, #b do
if math.abs(a[i] - b[i]) > tol then
return false
end
end
return true
end
local function decode(c: any, extra: { [string]: any }?): (any, any)
local o: { [string]: any } = { files = c.files }
for k, v in extra or {} do
o[k] = v
end
return SourceMdl.decode(Bytes.reader(buffer.fromstring(c.mdl)), o :: any)
end
local function normDir(s: string): string
local d = string.gsub(s, "\\", "/")
d = string.gsub(d, "^/+", "")
if d ~= "" and string.sub(d, -1) ~= "/" then
d ..= "/"
end
return d
end
for _, c in Fx.cases do
local tag = "v" .. c.version .. ": "
local e = c.expect
local st = c.srctools
local s, err = decode(c)
t:check(s, tag .. tostring(err))
if not s then
continue
end
local src = s.meta.source
t:eq(F.detect(c.mdl), "sourcemdl", tag .. "F.detect")
t:eq(#src.warnings, 0, tag .. "no warnings (" .. table.concat(src.warnings, "; ") .. ")")
t:eq(src.vtx, "model.dx90.vtx", tag .. "the dx90 strips")
-- header against srctools
t:eq(src.name, st.name, tag .. "name (srctools)")
t:eq(src.version, st.version, tag .. "version (srctools)")
t:eq(src.surfaceProp, st.surfaceprop, tag .. "surfaceprop (srctools)")
t:eq(src.keyValues, st.keyvalues, tag .. "keyvalues (srctools)")
t:check(math.abs(src.mass - st.mass) < 1e-6, tag .. "mass (srctools)")
t:check(near(src.eye, st.eye, 1e-6) and near(src.hull[1], st.hull[1], 1e-6) and near(src.hull[2], st.hull[2], 1e-6), tag .. "eye / hull (srctools)")
for i, d in src.cdmaterials do
t:eq(normDir(d), st.cdmaterials[i], tag .. "cdmaterials " .. i .. " (srctools)")
end
t:eq(#src.includeModels, #st.included, tag .. "include models (srctools)")
t:eq(src.includeModels[1].file, st.included[1][2], tag .. "include model file (srctools)")
t:eq(#src.skins, #st.skins, tag .. "skin families (srctools)")
for f, fam in src.skins do
local names = {}
for r, mi in fam do
names[r] = s.materials[mi].name
end
t:eq(table.concat(names, ","), table.concat(st.skins[f], ","), tag .. "skin family " .. f .. " (srctools)")
end
t:eq(#src.sequences, #st.sequences, tag .. "sequences (srctools)")
for i, q in st.sequences do
local ours = src.sequences[i]
t:eq(ours.name, q.label, tag .. "sequence " .. i .. " label (srctools)")
t:eq(ours.activity, q.act, tag .. "sequence " .. i .. " activity (srctools)")
t:eq(ours.flags, q.flags, tag .. "sequence " .. i .. " flags (srctools)")
t:eq(ours.weight, q.weight, tag .. "sequence " .. i .. " weight (srctools)")
t:eq(ours.keyValues, q.keyvalues, tag .. "sequence " .. i .. " keyvalues (srctools)")
t:check(near(ours.bboxMin, q.bbox[1], 1e-6) and near(ours.bboxMax, q.bbox[2], 1e-6), tag .. "sequence " .. i .. " bbox (srctools)")
t:eq(#ours.events, #q.events, tag .. "sequence " .. i .. " events (srctools)")
for k, ev in q.events do
t:check(math.abs(ours.events[k].cycle - ev[1]) < 1e-6 and ours.events[k].options == ev[2], tag .. "sequence " .. i .. " event " .. k .. " (srctools)")
end
end
local total = 0
for _, p in src.bodyParts do
for _, m in p.models do
total += m.vertices
end
end
t:eq(total, st.total_verts, tag .. "total vertices (srctools)")
t:check(string.find(src.physics.text, '"mass" "12.5', 1, true) ~= nil and st.phys_mass == 12.5, tag .. "phy keyvalues (srctools)")
-- materials: the .vmt srctools finds through cdmaterials, its $basetexture / $bumpmap
local seen = 0
for _, vmt in st.textures do
local mat
for _, m in s.materials do
if m.extras and m.extras.vmt and m.extras.vmt.path == vmt then
mat = m
end
end
t:check(mat, tag .. vmt .. ": resolved as srctools")
if mat then
seen += 1
local want = st.materials[vmt]
t:eq(mat.extras.vmt.shader, want.shader, tag .. vmt .. ": shader (srctools)")
local base = string.gsub(want.basetexture, "\\", "/")
t:eq(s.textures[mat.baseColorTexture.texture].uri, "materials/" .. base .. ".vtf", tag .. vmt .. ": $basetexture (srctools)")
if want.bumpmap ~= "" then
t:eq(s.textures[mat.normalTexture.texture].uri, "materials/" .. want.bumpmap .. ".vtf", tag .. vmt .. ": $bumpmap (srctools)")
else
t:check(mat.normalTexture == nil, tag .. vmt .. ": no bumpmap")
end
t:eq(mat.alphaMode, if want.translucent == "1" then "blend" elseif string.find(vmt, "metal") then "mask" else "opaque", tag .. vmt .. ": alpha mode")
t:eq(mat.doubleSided, string.find(vmt, "metal") ~= nil, tag .. vmt .. ": $nocull")
end
end
t:eq(seen, #s.materials, tag .. "every texture has its .vmt")
if c.version == 49 then
local Vtf = require("@tests/gen/vtf")
local loaded, errs = F.model.loadTextures(s, { resolve = function(uri: string): string?
return if string.sub(uri, -4) == ".vtf" then Vtf[1].data else nil
end })
t:check(next(errs) == nil and loaded.textures[1].image and loaded.textures[1].image.width > 0, tag .. "F.model.loadTextures decodes the .vtf references")
end
-- skeleton
local skin = s.skins[1]
t:eq(#skin.joints, #e.bones, tag .. "joints")
local ibm = floats(skin.inverseBindMatrices)
for i, b in e.bones do
local node = s.nodes[skin.joints[i]]
t:eq(node.name, b.name, tag .. "bone " .. i .. " name")
t:check(near(node.translation, b.pos, 0) and near(node.rotation, b.quat, 0), tag .. "bone " .. i .. " rest pose")
if b.parent >= 0 then
t:check(table.find(s.nodes[skin.joints[b.parent + 1]].children, skin.joints[i]) ~= nil, tag .. "bone " .. i .. " parent")
end
local m = Mat4.fromRows(b.poseToBone)
local got = table.move(ibm, (i - 1) * 16 + 1, i * 16, 1, {})
t:check(near(got, m, 1e-6), tag .. "bone " .. i .. " poseToBone as the inverse bind matrix")
end
t:eq(s.nodes[skin.joints[5]].extras.procedural.type, "jiggle", tag .. "jiggle bone")
t:eq(s.nodes[skin.joints[6]].extras.procedural.type, "aimatbone", tag .. "aim-at bone")
t:check(near(src.lodVertices, e.lodCounts, 0) or (src.lodVertices[1] == e.lodCounts[1] and src.lodVertices[2] == e.lodCounts[2]), tag .. "vvd LOD vertex counts")
-- meshes
for p, part in e.parts do
for m, model in part.models do
local info = src.bodyParts[p].models[m]
t:eq(info.name, model.name, tag .. "model " .. model.name)
if #model.meshes == 0 then
t:check(info.mesh == nil, tag .. model.name .. ": no mesh")
continue
end
local mesh = s.meshes[info.mesh]
t:eq(#mesh.primitives, #model.meshes, tag .. model.name .. ": primitives")
for k, x in model.meshes do
local prim = mesh.primitives[k]
local lab = tag .. model.name .. " mesh " .. k .. ": "
t:check(near(floats(prim.attributes.POSITION), x.positions, 0), lab .. "positions")
t:check(near(floats(prim.attributes.NORMAL), x.normals, 0), lab .. "normals")
t:check(near(floats(prim.attributes.TEXCOORD_0), x.uvs, 0), lab .. "uvs")
t:check(near(floats(prim.attributes.TANGENT), x.tangents, 0), lab .. "tangents")
t:check(near(floats(prim.attributes.WEIGHTS_0), x.weights, 0), lab .. "weights")
t:check(near(floats(prim.attributes.JOINTS_0), x.joints, 0), lab .. "joints")
t:check(near(floats(prim.indices), x.lods[1], 0), lab .. "LOD 0 triangles (strips, groups, winding)")
t:check(near(floats(prim.extras.lods[2].indices), x.lods[2], 0), lab .. "LOD 1 triangles")
t:eq(prim.extras.lods[2].switchPoint, 40, lab .. "LOD 1 switch point")
t:eq(prim.material, x.material, lab .. "material through skin family 1")
t:eq(prim.extras.skinRef, x.skinRef, lab .. "skin reference")
local names = mesh.extras.targetNames
local want = 0
for d, verts in x.targets do
local slot = table.find(names, e.flexdescs[tonumber(d) :: number + 1])
t:check(slot ~= nil, lab .. "flex target " .. d)
if slot then
local pos, nrm = floats(prim.targets[slot].POSITION), floats(prim.targets[slot].NORMAL)
local ok = true
for v, dd in verts do
local vi = tonumber(v) :: number
for cc = 1, 3 do
ok = ok and math.abs(pos[vi * 3 + cc] - dd[cc]) < 1e-6 and math.abs(nrm[vi * 3 + cc] - dd[cc + 3]) < 1e-6
end
want += 1
end
t:check(ok, lab .. "flex " .. names[slot] .. " deltas")
end
end
if names then
t:eq(#prim.targets, #names, lab .. "a target per flex")
end
end
end
end
t:eq(s.nodes[s.roots[1]].name, src.name, tag .. "root node")
-- attachments
for i, a in e.attachments do
local at = src.attachments[i]
local node = s.nodes[at.node]
t:eq(node.name, a.name, tag .. "attachment " .. i .. " name")
t:check(table.find(s.nodes[skin.joints[a.bone + 1]].children, at.node) ~= nil, tag .. "attachment " .. i .. " parent bone")
local m = Mat4.compose(node.translation, node.rotation, node.scale)
t:check(near(m, Mat4.fromRows(a.matrix), 1e-5), tag .. "attachment " .. i .. " matrix")
end
t:eq(#src.hitboxSets[1].boxes, 2, tag .. "hitboxes")
t:eq(src.hitboxSets[1].boxes[2].name, "head_box", tag .. "hitbox name")
-- animations
for _, a in e.anims do
local anim
for _, x in s.animations do
if x.name == a.name then
anim = x
end
end
t:check(anim, tag .. "animation " .. a.name)
if not anim then
continue
end
for bone, want in a.bones do
local node = skin.joints[tonumber(bone) :: number]
local tr, rot
for _, ch in anim.channels do
if ch.node == node then
if ch.path == "translation" then
tr = ch
elseif ch.path == "rotation" then
rot = ch
end
end
end
t:check(tr and rot, tag .. a.name .. " bone " .. bone .. ": channels")
if tr and rot then
t:eq(tr.input.count, a.frames, tag .. a.name .. ": frames")
t:check(math.abs(floats(tr.input)[2] - 1 / a.fps) < 1e-6, tag .. a.name .. ": fps")
t:check(near(floats(tr.output), want.pos, 1e-4), tag .. a.name .. " bone " .. bone .. ": positions per frame")
t:check(near(floats(rot.output), want.rot, 1e-5), tag .. a.name .. " bone " .. bone .. ": rotations per frame")
end
end
end
if c.version == 49 then
t:check(c.files["model.ani"] ~= nil, tag .. "an .ani block")
end
-- physics
local soup = {}
for _, sol in src.physics.solids do
for _, h in sol.hulls do
for _, v in h.indices do
for cc = 1, 3 do
table.insert(soup, h.positions[v * 3 + cc])
end
end
end
end
t:check(near(soup, e.physics, 1e-3), tag .. "phy convex hulls")
-- options
local s2 = decode(c, { bodies = { 2, 2 }, lod = 2 }) :: any
local names = {}
for _, ni in s2.nodes[s2.roots[1]].children do
if s2.nodes[ni].mesh then
table.insert(names, s2.meshes[s2.nodes[ni].mesh].name)
end
end
t:eq(table.concat(names, ","), "body_lo,hat", tag .. "opts.bodies")
t:check(near(floats(s2.meshes[1].primitives[1].indices), e.parts[1].models[1].meshes[1].lods[2], 0), tag .. "opts.lod")
local s3 = SourceMdl.decode(Bytes.reader(buffer.fromstring(c.mdl))) :: any
t:check(s3 and #s3.meshes == 0 and #s3.meta.source.warnings > 0 and #s3.skins == 1, tag .. "no siblings: skeleton only, with warnings")
local s4 = decode(c, { name = "renamed.mdl", files = { ["renamed.vvd"] = c.files["model.vvd"], ["renamed.sw.vtx"] = c.files["model.dx90.vtx"] } }) :: any
t:check(s4 and #s4.meshes == 3 and s4.meta.source.vtx == "renamed.sw.vtx", tag .. "siblings named after opts.name")
-- fuzz: the mdl, and each sibling file
local samples = { c.mdl }
t:fuzz(tag .. "mdl", function(b: buffer)
return SourceMdl.decode(Bytes.reader(b), { files = c.files })
end, samples, { mutations = 40 })
for _, name in { "model.vvd", "model.dx90.vtx", "model.phy", "materials/models/test/skin_c.vmt" } do
t:fuzz(tag .. name, function(b: buffer)
local files = table.clone(c.files)
files[name] = buffer.tostring(b)
return SourceMdl.decode(Bytes.reader(buffer.fromstring(c.mdl)), { files = files })
end, { c.files[name] }, { mutations = 30, garbage = 20 })
end
end
-- errors
local bad = buffer.fromstring(Fx.cases[1].mdl)
buffer.writei32(bad, 4, 52)
local _, e1 = SourceMdl.decode(Bytes.reader(bad))
t:check(e1 and e1.code == Err.UNSUPPORTED, "version 52: UNSUPPORTED")
local _, e2 = SourceMdl.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.cases[1].mdl, 1, 100))))
t:check(e2 and (e2.code == Err.TRUNCATED or e2.code == Err.CORRUPT), "truncated header")
local s5 = SourceMdl.decode(Bytes.reader(buffer.fromstring(Fx.cases[1].mdl)), { files = { ["model.vvd"] = "IDSV" } })
t:check(s5 == nil, "a broken .vvd is an error")
t:eq(SourceMdl.sniff(Bytes.reader(buffer.fromstring(Fx.cases[1].mdl))), 1, "sniff")
t:eq(SourceMdl.sniff(Bytes.reader(buffer.fromstring("IDST\10\0\0\0"))), 0, "sniff: GoldSrc is model/mdl")
t:done()
+29
View File
@@ -0,0 +1,29 @@
# Docs inputs for the Source models section of docs/guide/scene.md (tools/fixtures.py; tools/docs_check.py explains
# the inputs): a v49 model with its .vvd / .dx90.vtx / .phy and a .vmt, from tools/fixtures/sourcemdl.py's writer.
# tests/gen/docs_sourcemdl.luau { files = { [name] = bytes }, vars = { sourceMdlBytes = "model.mdl", ... } }
import importlib.util, os
INPUTS = ["tools/docs_check.py", "tools/fixtures/sourcemdl.py"]
def load(ctx, rel, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, rel))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def generate(ctx):
check = load(ctx, "tools/docs_check.py", "docs_check")
smdl = load(ctx, "tools/fixtures/sourcemdl.py", "fx_sourcemdl")
rng = ctx.rng(49)
m = smdl.make(rng, 49)
checksum = rng.randrange(1 << 31)
mdl, _, _, _ = smdl.write_mdl(m, rng, checksum)
vvd, _ = smdl.write_vvd(m, rng, checksum)
vtx, _ = smdl.write_vtx(m, rng, checksum, True)
phy, _, _ = smdl.write_phy(rng, checksum)
vmt = "materials/models/test/skin_a.vmt"
files = {"model.mdl": mdl, "model.vvd": vvd, "model.dx90.vtx": vtx, "model.phy": phy, vmt: smdl.VMTS[vmt].encode()}
check.emit_inputs(ctx, files, {"sourceMdlBytes": "model.mdl", "sourceVvdBytes": "model.vvd", "sourceVtxBytes": "model.dx90.vtx",
"sourcePhyBytes": "model.phy", "skinVmtText": vmt})
+139
View File
@@ -0,0 +1,139 @@
# codecs/text/KeyValues + data/vdf fixtures: KeyValues text parsed by srctools (Keyvalues.parse, flags $WIN32 on),
# random trees written by the python vdf module (vdf.dumps) and binary KeyValues written / read by vdf.binary_dumps.
# tests/gen/keyvalues.luau { text = { { data, canon } }, objects = { { data, canon } }, written = { { data, canon } }, binary = { { data, canon } } }
# canon: a pair list as "{" .. <len>:<key>=<value> ... "}", a value s<len>:<bytes> | i<int> | f<%.17g> | a block;
# binary types prefix their letter (i32 / f32 / ptr / wstr / col / u64 / i64). objects: vdf.loads of the written
# trees, in tests/data/Canon form.
import importlib.util, json, os
_spec = importlib.util.spec_from_file_location("_data_common", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_data_common.py"))
C = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(C)
TEXT = [
'"root"\n{\n\t"a"\t"1"\n\t"b"\t"two words"\n}\n',
'// comment\n"root" { "k" "v" "sub" { "x" "y" } }\n',
'root\n{\n\tkey value\n\tother\t"quoted value"\n\tnested\n\t{\n\t\tdeep 1\n\t}\n}\n',
'"r"\n{\n\t"dup"\t"1"\n\t"dup"\t"2"\n\t"blk" { "a" "1" }\n\t"blk" { "a" "2" }\n}\n',
'"r"\n{\n\t"x"\t"1"\n\t"x"\t"2"\t[$X360]\n\t"y"\t"pc"\t[$WIN32]\n\t"z"\t"not console"\t[!$X360]\n}\n',
'"r"\n{\n\t"esc"\t"a\\tb\\nc\\\\d\\"e"\n}\n',
'"r"\n{\n\t"first" "0"\n\t"blk" [$X360]\n\t{\n\t\t"a" "1"\n\t}\n\t"blk2" [$WIN32]\n\t{\n\t\t"b" "2"\n\t}\n}\n',
'"r" { "empty" "" "emptyblock" { } }\n',
'"a" { "k" "1" }\n"b" { "k" "2" }\n',
'"r"\r\n{\r\n\t"crlf"\t"yes"\r\n}\r\n',
'"r"\n{\n\t"unicode"\t"é中"\n\t"slash"\t"models/props/x.mdl"\n}\n',
'"r"\n{\n\t"c" "1" // trailing comment\n\t// "hidden" "1"\n}\n',
'"r"{"tight""1""t2"{"a""b"}}',
]
CODE = r'''
import json, sys, random
from srctools.keyvalues import Keyvalues
import vdf
FLAGS = {"$win32": True, "win32": True, "$x360": False}
inp = json.loads(sys.stdin.read())
def esc(b):
return b"%d:" % len(b) + b
def canon(kvs):
out = bytearray(b"{")
for q in kvs:
out += esc(q.real_name.encode())
out += b"="
if q.has_children() or isinstance(q.value, list):
out += canon(q)
else:
out += b"s" + esc(q.value.encode())
return bytes(out + b"}")
def vcanon(d):
out = bytearray(b"{")
for k, v in d.items():
out += esc(k.encode()) + b"="
if isinstance(v, dict):
out += vcanon(v)
elif isinstance(v, vdf.UINT_64):
out += b"u64i%d" % int(v)
elif isinstance(v, vdf.INT_64):
out += b"i64i%d" % int(v)
elif isinstance(v, vdf.POINTER):
out += b"ptri%d" % int(v)
elif isinstance(v, vdf.COLOR):
out += b"coli%d" % int(v)
elif isinstance(v, int):
out += b"i32i%d" % int(v)
elif isinstance(v, float):
out += b"f32f" + ("%.17g" % v).encode()
else:
out += b"s" + esc(v.encode())
return bytes(out + b"}")
res = {"text": [], "written": [], "binary": []}
for t in inp["text"]:
kv = Keyvalues.parse(t, flags=FLAGS, single_line=True)
res["text"].append({"data": t, "canon": canon(kv).decode("latin1")})
rng = random.Random(5)
ALPH = "abcXYZ019_ .-/\\\"\té"
def word(n=8):
return "".join(rng.choice(ALPH) for _ in range(rng.randrange(1, n)))
def tree(d):
out = vdf.VDFDict() if False else {}
for i in range(rng.randrange(0, 5)):
k = word() + str(i)
if d < 3 and rng.random() < 0.3:
out[k] = tree(d + 1)
else:
out[k] = word(14)
return out
for i in range(40):
t = {"root%d" % i: tree(0)}
s = vdf.dumps(t, pretty=bool(i % 2))
kv = Keyvalues.parse(s, single_line=True)
res["written"].append({"data": s, "canon": canon(kv).decode("latin1"), "obj": vdf.loads(s)})
import struct
def btree(d):
out = {}
for i in range(rng.randrange(0, 6)):
k = "k%d_%s" % (i, rng.choice(["", "x", "é"]))
r = rng.random()
if d < 3 and r < 0.2:
out[k] = btree(d + 1)
elif r < 0.35:
out[k] = rng.randrange(-2**31, 2**31)
elif r < 0.45:
out[k] = struct.unpack("<f", struct.pack("<f", rng.uniform(-1e6, 1e6)))[0]
elif r < 0.55:
out[k] = vdf.UINT_64(rng.choice([rng.randrange(0, 2**64), 76561197960265728 + rng.randrange(1000), 5]))
elif r < 0.6:
out[k] = vdf.INT_64(rng.randrange(-2**63, 2**63))
elif r < 0.65:
out[k] = vdf.POINTER(rng.randrange(0, 2**31))
elif r < 0.7:
out[k] = vdf.COLOR(rng.randrange(0, 2**31))
else:
out[k] = word(10)
return out
for i in range(30):
t = {"shortcuts": btree(0)}
b = vdf.binary_dumps(t)
back = vdf.binary_loads(b)
res["binary"].append({"data": b.decode("latin1"), "canon": vcanon(back).decode("latin1")})
print(json.dumps(res))
'''
def generate(ctx):
out = ctx.python(["srctools", "vdf"], CODE, input=json.dumps({"text": TEXT}).encode())
res = json.loads(out)
def enc(lst):
return [{"data": c["data"].encode("utf-8") if not isinstance(c["data"], bytes) else c["data"], "canon": c["canon"].encode("latin1")} for c in lst]
objs = [{"data": c["data"].encode("utf-8"), "canon": C.canon(c["obj"])} for c in res["written"]]
ctx.emit("keyvalues", {
"objects": objs,
"text": enc(res["text"]),
"written": enc(res["written"]),
"binary": [{"data": c["data"].encode("latin1"), "canon": c["canon"].encode("latin1")} for c in res["binary"]],
})
+816
View File
@@ -0,0 +1,816 @@
# Source MDL fixtures (tools/fixtures.py). Models written here from the Source SDK 2013 studio.h / optimize.h /
# phyfile.h layouts with random data (no Valve assets): MDL v44 / v48 / v49 with .vvd (LOD fixups, file order
# shuffled), .dx90.vtx (trilists, a tristrip, two LODs, a material replacement; v49 uses the 33 / 35-byte strip
# headers), .phy (VPHY, two convex leaves, KeyValues text), .ani (an external animation block) and .vmt materials.
# References: the writer's exact values (vertices, triangles, bones, poseToBone, flex deltas, per-frame bone poses from
# RLE values / Quaternion48 / Quaternion64 / Vector48, sections, delta animation) and srctools (nixpkgs python
# srctools.mdl.Model: header, cdmaterials, skins, sequences, events, included models, phy keyvalues, iter_textures;
# srctools.vmt.Material: $basetexture / $bumpmap).
# tests/gen/sourcemdl.luau { cases = { { version, mdl, vvd, vtx, phy, ani, files, expect, srctools }, ... } }
import json, math, os, shutil, struct, tempfile
INPUTS = []
def f32(x):
return struct.unpack("<f", struct.pack("<f", x))[0]
def f16(x):
return struct.unpack("<e", struct.pack("<e", x))[0]
def angles(x, y, z):
sy, cy = math.sin(z / 2), math.cos(z / 2)
sp, cp = math.sin(y / 2), math.cos(y / 2)
sr, cr = math.sin(x / 2), math.cos(x / 2)
return [sr * cp * cy - cr * sp * sy, cr * sp * cy + sr * cp * sy, cr * cp * sy - sr * sp * cy, cr * cp * cy + sr * sp * sy]
def qmul(a, b):
ax, ay, az, aw = a
bx, by, bz, bw = b
return [aw * bx + ax * bw + ay * bz - az * by, aw * by - ax * bz + ay * bw + az * bx, aw * bz + ax * by - ay * bx + az * bw, aw * bw - ax * bx - ay * by - az * bz]
def qmat(q):
x, y, z, w = q
return [[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]
def compose(r, t):
return [r[0] + [t[0]], r[1] + [t[1]], r[2] + [t[2]]]
def mul34(a, b):
out = []
for i in range(3):
row = [sum(a[i][k] * b[k][j] for k in range(3)) for j in range(3)]
row.append(sum(a[i][k] * b[k][3] for k in range(3)) + a[i][3])
out.append(row)
return out
def inv34(m):
r = [[m[j][i] for j in range(3)] for i in range(3)]
t = [-sum(r[i][k] * m[k][3] for k in range(3)) for i in range(3)]
return [r[i] + [t[i]] for i in range(3)]
class Buf:
def __init__(self):
self.b = bytearray()
self.strings = []
def tell(self):
return len(self.b)
def put(self, fmt, *v):
at = len(self.b)
self.b += struct.pack("<" + fmt, *v)
return at
def raw(self, data):
at = len(self.b)
self.b += data
return at
def patch(self, at, fmt, *v):
struct.pack_into("<" + fmt, self.b, at, *v)
def align(self, n=4):
while len(self.b) % n:
self.b.append(0)
def string(self, field, base, text):
self.strings.append((field, base, text))
def flush_strings(self):
seen = {}
for field, base, text in self.strings:
if text not in seen:
seen[text] = self.raw(text.encode() + b"\0")
self.patch(field, "i", seen[text] - base)
self.strings = []
def rle(values):
out, i, n = b"", 0, len(values)
while i < n:
vals = [values[i]]
total = 1
j = i + 1
while j < n and len(vals) < 255 and total < 255:
if values[j] == values[j - 1]:
while j < n and values[j] == values[j - 1] and total < 255:
total += 1
j += 1
break
vals.append(values[j])
total += 1
j += 1
out += struct.pack("<BB", len(vals), total) + struct.pack("<%dh" % len(vals), *vals)
i = j
return out
def quat48(q):
x, y, z, w = q
xs = max(0, min(65535, int(round(x * 32768 + 32768))))
ys = max(0, min(65535, int(round(y * 32768 + 32768))))
zs = max(0, min(32767, int(round(z * 16384 + 16384))))
data = struct.pack("<3H", xs, ys, zs | (0x8000 if w < 0 else 0))
dx, dy, dz = (xs - 32768) / 32768, (ys - 32768) / 32768, (zs - 16384) / 16384
dw = math.sqrt(max(0, 1 - dx * dx - dy * dy - dz * dz))
return data, [dx, dy, dz, -dw if w < 0 else dw]
def quat64(q):
x, y, z, w = q
s = [max(0, min(2097151, int(round(c * 1048576.5 + 1048576)))) for c in (x, y, z)]
v = s[0] | (s[1] << 21) | (s[2] << 42) | ((1 << 63) if w < 0 else 0)
d = [(c - 1048576) / 1048576.5 for c in s]
dw = math.sqrt(max(0, 1 - sum(c * c for c in d)))
return struct.pack("<Q", v), d + [-dw if w < 0 else dw]
# ------------------------------------------------------------------------------------------------ the model
def make(rng, version):
ext = version == 49
nb = 6
bones = []
world = []
for i in range(nb):
parent = -1 if i == 0 else rng.randrange(i)
rot = [f32(rng.uniform(-1.5, 1.5)) for _ in range(3)]
quat = [f32(c) for c in angles(*rot)]
pos = [f32(rng.uniform(-8, 8)) for _ in range(3)]
b = {"name": "bone%d" % i if i else "root", "parent": parent, "pos": pos, "quat": quat, "rot": rot,
"posscale": [f32(rng.uniform(0.001, 0.01)) for _ in range(3)], "rotscale": [f32(rng.uniform(0.0001, 0.001)) for _ in range(3)]}
local = compose(qmat(quat), pos)
w = local if parent < 0 else mul34(world[parent], local)
world.append(w)
b["poseToBone"] = [f32(c) for row in inv34(w) for c in row]
bones.append(b)
bones[4]["proc"] = ("jiggle", [f32(rng.uniform(0, 10)) for _ in range(29)])
bones[5]["proc"] = ("aimatbone", [f32(rng.uniform(-1, 1)) for _ in range(9)])
textures = ["skin_a", "skin_b", "models/shared/metal", "skin_c"]
cdmats = ["models\\test\\", "models/alt"]
nref = 3
families = [[0, 1, 2], [3, 1, 2]]
# body parts: models of meshes of (vertex count, triangle count)
layout = [("body", [("body_hi", [(30, 40), (20, 24)]), ("body_lo", [(12, 10)])]), ("head", [("blank", []), ("hat", [(10, 8)])])]
vertices = []
parts = []
counter = [0]
for pname, models in layout:
mlist = []
for mname, meshes in models:
start = len(vertices)
mm = []
off = 0
for k, (nv, nt) in enumerate(meshes):
for _ in range(nv):
nbw = rng.randrange(1, 4)
ws = [rng.random() for _ in range(nbw)]
s = sum(ws)
ws = [f32(w / s) for w in ws] + [0.0] * (3 - nbw)
ids = [rng.randrange(nb) for _ in range(nbw)] + [0] * (3 - nbw)
n = [rng.uniform(-1, 1) for _ in range(3)]
l = math.sqrt(sum(c * c for c in n)) or 1
vertices.append({"w": ws, "b": ids, "n": nbw, "pos": [f32(rng.uniform(-20, 20)) for _ in range(3)],
"nrm": [f32(c / l) for c in n], "uv": [f32(rng.random()), f32(rng.random())],
"tan": [f32(rng.uniform(-1, 1)) for _ in range(3)] + [f32(rng.choice((-1.0, 1.0)))]})
tris = []
while len(tris) < nt:
t = rng.sample(range(nv), 3)
tris.append(t)
counter[0] += 1
mm.append({"nv": nv, "off": off, "tris": tris, "material": (counter[0] - 1) % nref, "center": [f32(rng.uniform(-1, 1)) for _ in range(3)], "flexes": []})
off += nv
mlist.append({"name": mname, "start": start, "nv": off, "meshes": mm})
parts.append({"name": pname, "models": mlist})
flexdescs = ["AU1L", "AU1R", "smile", "unused"]
hi = parts[0]["models"][0]
m0 = hi["meshes"][0]
fixed = version >= 48
scale = f32(1 / 4096.0)
def deltas(nv, count, wrinkle=False):
out = []
for idx in sorted(rng.sample(range(nv), count)):
d = [rng.uniform(-2, 2) for _ in range(6)]
out.append({"index": idx, "speed": rng.randrange(256), "side": rng.randrange(256), "d": d, "wrinkle": rng.randrange(-32767, 32768) if wrinkle else 0})
return out
m0["flexes"].append({"desc": 2, "partner": 0, "kind": 0, "targets": [0.0, 0.25, 0.75, 1.0], "verts": deltas(m0["nv"], 8)})
m0["flexes"].append({"desc": 0, "partner": 1, "kind": 1, "targets": [0.0, 0.5, 0.5, 1.0], "verts": deltas(m0["nv"], 6, True)})
hi["meshes"][1]["flexes"].append({"desc": 2, "partner": 0, "kind": 0, "targets": [0.0, 1.0, 1.0, 1.0], "verts": deltas(hi["meshes"][1]["nv"], 5)})
for m in (m0, hi["meshes"][1]):
for f in m["flexes"]:
for v in f["verts"]:
if fixed:
v["raw"] = [max(-32768, min(32767, int(round(c / scale)))) for c in v["d"]]
v["val"] = [r * scale for r in v["raw"]]
else:
v["val"] = [f16(c) for c in v["d"]]
# animations
nf = {"idle": 6, "walk": 12, "gesture": 4, "fromani": 3}
anims = []
# per-anim per-bone specs (full length), split into sections by the writer
def make_specs(n, delta):
specs = []
r = [rng.randrange(-2000, 2000) for _ in range(3)]
specs.append((0, {"rot": "anim", "rv": [[rng.randrange(-3000, 3000) for _ in range(n)], [r[1]] * n, [rng.choice((5, 5, 9)) for _ in range(n)]],
"pos": "anim", "pv": [[rng.randrange(-500, 500) for _ in range(n)], None, [7] * n]}))
specs.append((1, {"rot": "raw48", "q": [f32(c) for c in normalize([rng.uniform(-1, 1) for _ in range(4)])], "pos": "raw48", "p": [f16(rng.uniform(-10, 10)) for _ in range(3)]}))
specs.append((3, {"rot": "raw64", "q": normalize([rng.uniform(-1, 1) for _ in range(4)]), "pos": None}))
specs.append((4, {"rot": None, "pos": "anim", "pv": [None, [rng.randrange(-100, 100) for _ in range(n)], None]}))
return specs
for name, delta in (("idle", False), ("walk", False), ("gesture", True), ("fromani", False)):
anims.append({"name": "@" + name, "seq": name, "frames": nf[name], "delta": delta, "specs": make_specs(nf[name], delta),
"fps": f32(rng.choice((24.0, 30.0))), "sections": 5 if name == "walk" else 0, "ani": name == "fromani"})
if version < 49:
anims.pop()
# expected poses per anim: { bone -> { pos = [...], rot = [...] } }
for a in anims:
n = a["frames"]
exp = {}
for bi, sp in a["specs"]:
b = bones[bi]
pos, rot = [], []
for fr in range(n):
if sp["rot"] == "anim":
ang = [(0 if a["delta"] else b["rot"][k]) + (sp["rv"][k][fr] * b["rotscale"][k] if sp["rv"][k] else 0) for k in range(3)]
q = angles(*ang)
elif sp["rot"] == "raw48":
q = quat48(sp["q"])[1]
elif sp["rot"] == "raw64":
q = quat64(sp["q"])[1]
else:
q = [0, 0, 0, 1] if a["delta"] else b["quat"]
if sp["pos"] == "anim":
p = [(0 if a["delta"] else b["pos"][k]) + (sp["pv"][k][fr] * b["posscale"][k] if sp["pv"][k] else 0) for k in range(3)]
elif sp["pos"] == "raw48":
p = list(sp["p"])
else:
p = [0, 0, 0] if a["delta"] else list(b["pos"])
if a["delta"]:
p = [b["pos"][k] + p[k] for k in range(3)]
q = qmul(b["quat"], q)
pos += p
rot += q
exp[bi] = {"pos": pos, "rot": rot}
a["expect"] = exp
return {"version": version, "ext": ext, "bones": bones, "textures": textures, "cdmats": cdmats, "families": families, "nref": nref,
"parts": parts, "vertices": vertices, "flexdescs": flexdescs, "fixed": fixed, "scale": scale, "anims": anims}
def normalize(q):
l = math.sqrt(sum(c * c for c in q))
return [c / l for c in q]
def anim_chain(b, a, bones, first, count):
# mstudioanim_t records for frames [first, first + count) of every spec
out = bytearray()
recs = []
for i, (bi, sp) in enumerate(a["specs"]):
flags = 0
body = bytearray()
later = []
if sp["rot"] == "raw48":
flags |= 0x02
body += quat48(sp["q"])[0]
elif sp["rot"] == "raw64":
flags |= 0x20
body += quat64(sp["q"])[0]
elif sp["rot"] == "anim":
flags |= 0x08
later.append((len(body), sp["rv"]))
body += bytes(6)
if sp["pos"] == "raw48":
flags |= 0x01
body += struct.pack("<3e", *sp["p"])
elif sp["pos"] == "anim":
flags |= 0x04
later.append((len(body), sp["pv"]))
body += bytes(6)
if a["delta"]:
flags |= 0x10
for vp, chans in later:
for k in range(3):
if chans[k] is not None:
off = 4 + len(body) - (4 + vp)
struct.pack_into("<h", body, vp + k * 2, off)
body += rle(chans[k][first:first + count])
if len(body) % 2:
body.append(0)
recs.append((bi, flags, bytes(body)))
for i, (bi, flags, body) in enumerate(recs):
nxt = 0 if i == len(recs) - 1 else 4 + len(body)
out += struct.pack("<BBh", bi, flags, nxt) + body
return bytes(out)
def write_mdl(m, rng, checksum):
v = m["version"]
w = Buf()
w.raw(bytes(408))
hdr = {}
w.patch(0, "4sii64si", b"IDST", v, checksum, b"test/model.mdl", 0)
eye = [f32(rng.uniform(-5, 5)) for _ in range(18)]
w.patch(80, "18f", *eye)
w.patch(152, "I", 0x200000 if m["fixed"] else 0)
w.patch(392, "f", m["scale"] if m["fixed"] else 0.0)
# bones
bo = w.tell()
hdr[156] = (len(m["bones"]), bo)
for b in m["bones"]:
w.put("ii6i3f4f3f3f3f12f4fiiiiii8i", 0, b["parent"], *([-1] * 6), *b["pos"], *b["quat"], *b["rot"], *b["posscale"], *b["rotscale"],
*b["poseToBone"], 0, 0, 0, 1, 0x100, 0, 0, 0, 0, 1, *([0] * 8))
for i, b in enumerate(m["bones"]):
at = bo + i * 216
w.string(at, at, b["name"])
w.string(at + 176, at, "flesh")
if "proc" in b:
kind, vals = b["proc"]
w.align()
po = w.tell()
if kind == "jiggle":
w.put("i29f", 0x41, *vals)
w.patch(at + 164, "ii", 5, po - at)
else:
w.put("ii9f", 0, 2, *vals)
w.patch(at + 164, "ii", 3, po - at)
# hitbox set
hs = w.tell()
hdr[172] = (1, hs)
w.put("iii", 0, 2, 12)
w.string(hs, hs, "default")
for k in range(2):
bb = w.tell()
w.put("ii3f3fi8i", k + 1, k, -1.0, -2.0, -3.0, 1.0, 2.0, 3.0, 0, *([0] * 8))
if k == 1:
w.string(bb + 32, bb, "head_box")
# animdescs
ad = w.tell()
hdr[184 - 4] = (len(m["anims"]), ad)
for a in m["anims"]:
w.put("iifiiii6i9ihhif", -w.tell(), 0, a["fps"], 0x4 if a["delta"] else 0, a["frames"], 0, 0, *([0] * 6), *([0] * 9), 0, 0, 0, 0.0)
anidata = bytearray(b"IDAG" + bytes(60))
for i, a in enumerate(m["anims"]):
at = ad + i * 100
w.string(at + 4, at, a["name"])
w.align()
n = a["frames"]
if a["sections"]:
sf = a["sections"]
ns = n // sf + 2
st = w.tell()
w.raw(bytes(ns * 8))
w.patch(at + 80, "ii", st - at, sf)
datas = []
for s in range(ns):
if s == ns - 1:
first, cnt = n - 1, 1
else:
first = s * sf
cnt = min(sf + 1, n - first)
if cnt <= 0:
first, cnt = n - 1, 1
w.align()
d = w.raw(anim_chain(w, a, m["bones"], first, cnt))
w.patch(st + s * 8, "ii", 0, d - at)
datas.append(d)
w.patch(at + 52, "ii", 0, datas[0] - at)
elif a["ani"]:
off = len(anidata) - 64
anidata += anim_chain(w, a, m["bones"], 0, n)
w.patch(at + 52, "ii", 1, off)
else:
d = w.raw(anim_chain(w, a, m["bones"], 0, n))
w.patch(at + 52, "ii", 0, d - at)
# sequences
w.align()
sq = w.tell()
hdr[188] = (len(m["anims"]), sq)
seqs = []
for i, a in enumerate(m["anims"]):
bmin = [f32(rng.uniform(-10, 0)) for _ in range(3)]
bmax = [f32(rng.uniform(0, 10)) for _ in range(3)]
flags = 1 if a["seq"] in ("idle", "walk") else (4 if a["delta"] else 0)
w.put("8i3f3f5i2i2f2fiff3i3f2i10i7i", -w.tell(), 0, 0, flags, -1, 1 + i, 0, 0, *bmin, *bmax, 1, 0, 0, 1, 1, -1, -1, 0.0, 0.0, 0.0, 0.0, 0,
0.2, 0.2, 0, 0, 0, 0.0, 0.0, 0.0, 0, 0, *([0] * 10), *([0] * 7))
seqs.append({"name": a["seq"], "flags": flags, "weight": 1 + i, "bmin": bmin, "bmax": bmax, "act": "ACT_" + a["seq"].upper()})
for i, a in enumerate(m["anims"]):
at = sq + i * 212
w.string(at + 4, at, a["seq"])
w.string(at + 8, at, seqs[i]["act"])
w.align()
ai = w.put("h", i)
w.align()
w.patch(at + 60, "i", ai - at)
if i == 0:
ev = w.tell()
w.put("fii64si", 0.5, 5004, 0, b"Weapon.Fire", 0)
w.put("fii64si", 0.25, 1004, 0, b"footstep", 0)
w.patch(at + 24, "ii", 2, ev - at)
seqs[i]["events"] = [[0.5, "Weapon.Fire"], [0.25, "footstep"]]
kv = w.raw(b"speed 10\0")
w.patch(at + 172, "ii", kv - at, 9)
else:
seqs[i]["events"] = []
# textures
tx = w.tell()
hdr[204] = (len(m["textures"]), tx)
for t in m["textures"]:
w.put("iiii2i10i", 0, 0, 0, 0, 0, 0, *([0] * 10))
for i, t in enumerate(m["textures"]):
w.string(tx + i * 64, tx + i * 64, t)
cd = w.tell()
hdr[212] = (len(m["cdmats"]), cd)
for c in m["cdmats"]:
w.put("i", 0)
for i, c in enumerate(m["cdmats"]):
w.string(cd + i * 4, 0, c)
sk = w.tell()
for fam in m["families"]:
w.put("%dh" % m["nref"], *fam)
w.align()
w.patch(220, "iii", m["nref"], len(m["families"]), sk)
# body parts
bp = w.tell()
hdr[232] = (len(m["parts"]), bp)
base = 0
for p in m["parts"]:
w.put("iiii", 0, len(p["models"]), max(1, base), 0)
base = max(1, base) * len(p["models"])
for pi, p in enumerate(m["parts"]):
pat = bp + pi * 16
w.string(pat, pat, p["name"])
mo = w.tell()
w.patch(pat + 12, "i", mo - pat)
for md in p["models"]:
w.put("64sifiiiiiiiiiii8i", md["name"].encode(), 0, 10.0, len(md["meshes"]), 0, md["nv"], md["start"] * 48, md["start"] * 16, 0, 0, 0, 0, 0, 0, *([0] * 8))
for mi, md in enumerate(p["models"]):
mat = mo + mi * 148
me = w.tell()
w.patch(mat + 76, "i", me - mat if md["meshes"] else 0)
for k, sm in enumerate(md["meshes"]):
w.put("iiiiiiiii3fi8i8i", sm["material"], mat - w.tell(), sm["nv"], sm["off"], len(sm["flexes"]), 0, 0, 0, k, *sm["center"], 0,
sm["nv"], sm["nv"], *([0] * 6), *([0] * 8))
for k, sm in enumerate(md["meshes"]):
mea = me + k * 116
if not sm["flexes"]:
continue
fo = w.tell()
w.patch(mea + 20, "i", fo - mea)
for f in sm["flexes"]:
w.put("i4fiiiB3x6i", f["desc"], *f["targets"], len(f["verts"]), 0, f["partner"], f["kind"], *([0] * 6))
for fi, f in enumerate(sm["flexes"]):
fa = fo + fi * 60
va = w.tell()
w.patch(fa + 24, "i", va - fa)
for vv in f["verts"]:
if m["fixed"]:
w.put("HBB6h", vv["index"], vv["speed"], vv["side"], *vv["raw"])
else:
w.put("HBB6e", vv["index"], vv["speed"], vv["side"], *vv["d"])
if f["kind"] == 1:
w.put("h", vv["wrinkle"])
w.align()
# attachments
at0 = w.tell()
atts = []
for k in range(2):
rot = angles(*[rng.uniform(-1, 1) for _ in range(3)])
mat = compose(qmat(rot), [rng.uniform(-4, 4) for _ in range(3)])
flat = [f32(c) for row in mat for c in row]
w.put("iii12f8i", 0, 0, k * 2, *flat, *([0] * 8))
atts.append({"name": "attach%d" % k, "bone": k * 2, "matrix": flat})
for k in range(2):
w.string(at0 + k * 92, at0 + k * 92, atts[k]["name"])
hdr[240] = (2, at0)
fd = w.tell()
hdr[260] = (len(m["flexdescs"]), fd)
for d in m["flexdescs"]:
w.put("i", 0)
for i, d in enumerate(m["flexdescs"]):
w.string(fd + i * 4, fd + i * 4, d)
fc = w.tell()
hdr[268] = (2, fc)
w.put("iiiff", 0, 0, 0, 0.0, 1.0)
w.put("iiiff", 0, 0, 1, -1.0, 1.0)
for i, n in enumerate(("smile", "blink")):
w.string(fc + i * 20, fc + i * 20, "eyes" if i else "mouth")
w.string(fc + i * 20 + 4, fc + i * 20, n)
fr = w.tell()
hdr[276] = (1, fr)
w.put("iii", 2, 2, 12)
w.put("if", 1, 0.5)
w.put("ii", 2, 0)
pp = w.tell()
hdr[300] = (1, pp)
w.put("iifff", 0, 0, -45.0, 45.0, 0.0)
w.string(pp, pp, "move_yaw")
sp = w.raw(b"wood\0")
w.patch(308, "i", sp)
kvtext = b'mdlkeyvalue\n{\nprop_data\n{\n"base" "Wooden.Small"\n}\n}\n'
kv = w.raw(kvtext + b"\0")
w.patch(312, "ii", kv, len(kvtext))
w.patch(328, "fi", 12.5, 1)
inc = w.tell()
w.put("ii", 0, 0)
w.string(inc, inc, "anims")
w.string(inc + 4, inc, "models/test/anims.mdl")
hdr[336] = (1, inc)
if any(a["ani"] for a in m["anims"]):
an = w.raw(b"models/test/model.ani\0")
w.align()
blk = w.put("iiii", 0, 0, 64, len(anidata))
w.patch(348, "iii", an, 2, blk)
h2 = w.tell()
w.put("iiifii64i", 0, 0, 0, 0.0, 0, 0, *([0] * 64))
w.patch(400, "i", h2)
for off, (n, at) in hdr.items():
w.patch(off, "ii", n, at)
w.flush_strings()
w.patch(76, "i", len(w.b))
return bytes(w.b), bytes(anidata), atts, seqs
def write_vvd(m, rng, checksum):
verts = m["vertices"]
n = len(verts)
cuts = sorted(rng.sample(range(1, n), 3))
chunks = []
prev = 0
for c in cuts + [n]:
chunks.append((prev, c - prev))
prev = c
lods = [0, 1, 0, 1]
order = list(range(len(chunks)))[::-1]
filepos = {}
pos = 0
for ci in order:
filepos[ci] = pos
pos += chunks[ci][1]
counts = [sum(chunks[i][1] for i in range(len(chunks)) if lods[i] >= l) for l in range(2)] + [0] * 6
vdata, tdata = bytearray(), bytearray()
for ci in order:
s, c = chunks[ci]
for vv in verts[s:s + c]:
vdata += struct.pack("<3f3BB3f3f2f", *vv["w"], *vv["b"], vv["n"], *vv["pos"], *vv["nrm"], *vv["uv"])
tdata += struct.pack("<4f", *vv["tan"])
fix = b"".join(struct.pack("<3i", lods[i], filepos[i], chunks[i][1]) for i in range(len(chunks)))
off_fix = 64
off_v = off_fix + len(fix)
off_v += (16 - off_v % 16) % 16
off_t = off_v + len(vdata)
out = struct.pack("<4siii8iiiii", b"IDSV", 4, checksum, 2, *counts, len(chunks), off_fix, off_v, off_t)
out += fix
out += bytes(off_v - len(out))
return out + vdata + tdata, counts
def write_vtx(m, rng, checksum, ext):
w = Buf()
w.raw(bytes(36))
nlod = 2
parts = m["parts"]
bp = w.tell()
for p in parts:
w.put("ii", len(p["models"]), 0)
expect = {}
for pi, p in enumerate(parts):
pat = bp + pi * 8
mo = w.tell()
w.patch(pat + 4, "i", mo - pat)
for md in p["models"]:
w.put("ii", nlod, 0)
for mi, md in enumerate(p["models"]):
mat = mo + mi * 8
lo = w.tell()
w.patch(mat + 4, "i", lo - mat)
for l in range(nlod):
w.put("iif", len(md["meshes"]), 0, [0.0, 40.0][l])
for l in range(nlod):
la = lo + l * 12
me = w.tell()
w.patch(la + 4, "i", me - la)
for sm in md["meshes"]:
w.put("iiB", 0, 0, 0)
for k, sm in enumerate(md["meshes"]):
mea = me + k * 9
tris = sm["tris"] if l == 0 else sm["tris"][:max(1, len(sm["tris"]) // 2)]
# LOD 0 of the first mesh: two strip groups, the second one a tristrip
groups = []
if l == 0 and k == 0 and pi == 0 and mi == 0:
half = len(tris) // 2
groups.append(("list", tris[:half]))
strip = [tris[half][0], tris[half][1], tris[half][2]]
for t in tris[half + 1:half + 4]:
strip.append(t[0])
groups.append(("strip", strip))
groups.append(("list", tris[half + 4:]))
else:
groups.append(("list", tris))
decoded = []
sga = w.tell()
w.patch(mea, "ii", len(groups), sga - mea)
sgstride = 33 if ext else 25
w.raw(bytes(sgstride * len(groups)))
for gi, (kind, data) in enumerate(groups):
ids = data if kind == "strip" else [c for t in data for c in t]
uniq = []
for c in ids:
if c not in uniq:
uniq.append(c)
rng.shuffle(uniq)
local = [uniq.index(c) for c in ids]
if kind == "strip":
for i in range(len(ids) - 2):
a, b, c = ids[i], ids[i + 1], ids[i + 2]
if a != b and b != c and a != c:
decoded += [a, b, c] if i % 2 == 0 else [b, a, c]
else:
decoded += ids
ga = sga + gi * sgstride
vo = w.tell()
for c in uniq:
w.put("3BBH3b", 0, 1, 2, 1, c, 0, 0, 0)
io = w.tell()
w.put("%dH" % len(local), *local)
w.align()
so = w.tell()
stflags = 2 if kind == "strip" else 1
w.put("iiiihBii", len(local), 0, len(uniq), 0, 3, stflags, 0, 0)
if ext:
w.put("ii", 0, 0)
w.patch(ga, "iiiiiiB", len(uniq), vo - ga, len(local), io - ga, 1, so - ga, 0)
expect["%d_%d_%d_%d" % (pi, mi, l, k)] = decoded
rl = w.tell()
for l in range(nlod):
w.put("ii", 0, 0)
ra = w.tell()
w.put("hi", 1, 0)
w.patch(rl + 8, "ii", 1, ra - (rl + 8))
w.string(ra + 2, ra, "models/test/skin_b_lod1")
w.flush_strings()
w.patch(0, "iiHHiiiiii", 7, 24, 53, 9, 3, checksum, nlod, rl, len(parts), bp)
return bytes(w.b), expect
def write_phy(rng, checksum):
def ledge_bytes(points, tris):
hdr = 16
body = bytearray()
for t in tris:
body += struct.pack("<I", 0)
for c in t:
body += struct.pack("<I", c)
pts = b"".join(struct.pack("<4f", *p, 0.0) for p in points)
return struct.pack("<iiIhh", hdr + len(body), 0, 0, len(tris), 0) + bytes(body) + pts
leaves = []
soup = []
for k in range(2):
pts = [[f32(rng.uniform(-0.5, 0.5)) for _ in range(3)] for _ in range(4)]
tris = [(0, 1, 2), (0, 3, 1), (1, 3, 2), (2, 3, 0)]
leaves.append(ledge_bytes(pts, tris))
for t in tris:
for c in t:
x, y, z = pts[c]
soup += [x / 0.0254, z / 0.0254, -y / 0.0254]
surf = bytearray(bytes(48))
led_at = []
for lb in leaves:
led_at.append(len(surf))
surf += lb
root = len(surf)
surf += struct.pack("<ii3ff4B", 0, 0, 0.0, 0.0, 0.0, 1.0, 0, 0, 0, 0)
left = len(surf)
surf += struct.pack("<ii3ff4B", 0, led_at[0] - left, 0.0, 0.0, 0.0, 1.0, 0, 0, 0, 0)
right = len(surf)
surf += struct.pack("<ii3ff4B", 0, led_at[1] - right, 0.0, 0.0, 0.0, 1.0, 0, 0, 0, 0)
struct.pack_into("<ii", surf, root, right - root, 0)
struct.pack_into("<3f3ffIi3i", surf, 0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, len(surf), root, 0, 0, 0)
surf[44:48] = b"IVPS"
solid = b"VPHY" + struct.pack("<HHi3fi", 0x100, 0, len(surf), 1.0, 1.0, 1.0, 0) + bytes(surf)
text = 'solid {\n"index" "0"\n"name" "root"\n"mass" "12.500000"\n"surfaceprop" "wood"\n}\neditparams {\n"rootname" ""\n"totalmass" "12.500000"\n}\n'
out = struct.pack("<iiii", 16, 0, 1, checksum) + struct.pack("<i", len(solid)) + solid + text.encode() + b"\0"
return out, soup, text
def srctools_view(ctx, tmp):
code = r'''
import json
from srctools.filesys import RawFileSystem
from srctools.mdl import Model
from srctools.vmt import Material
fs = RawFileSystem(%r)
m = Model(fs, fs["models/test/model.mdl"])
out = {
"name": m.name, "version": m.version, "cdmaterials": m.cdmaterials, "skins": m.skins, "surfaceprop": m.surfaceprop,
"keyvalues": m.keyvalues, "mass": m.mass, "total_verts": m.total_verts,
"eye": list(m.eye_pos), "hull": [list(m.hull_min), list(m.hull_max)],
"included": [[i.label, i.filename] for i in m.included_models],
"sequences": [{"label": s.label, "act": s.act_name, "flags": s.flags, "weight": s.act_weight, "bbox": [list(s.bbox_min), list(s.bbox_max)],
"events": [[e.cycle, e.options] for e in s.events], "keyvalues": s.keyvalues} for s in m.sequences],
"phys_mass": m.phys_keyvalues.find_key("solid").float("mass"),
"textures": sorted(m.iter_textures()),
}
mats = {}
for path in out["textures"]:
with fs[path].open_str() as f:
mat = Material.parse(f, path).apply_patches(fs)
mats[path] = {"shader": mat.shader, "basetexture": mat.get("$basetexture", ""), "bumpmap": mat.get("$bumpmap", ""), "translucent": mat.get("$translucent", "")}
out["materials"] = mats
print(json.dumps(out))
''' % tmp
return json.loads(ctx.python(["srctools"], code))
VMTS = {
"materials/models/test/skin_a.vmt": '"VertexLitGeneric"\n{\n\t"$basetexture" "models/test/skin_a"\n\t"$bumpmap" "models/test/skin_a_normal"\n}\n',
"materials/models/alt/skin_b.vmt": '// comment\nVertexLitGeneric\n{\n\t$basetexture "models\\alt\\skin_b"\n\t$translucent 1\n\t"Proxies" { "Sine" { "resultVar" "$alpha" } }\n}\n',
"materials/models/shared/metal.vmt": '"LightmappedGeneric"\n{\n\t"$baseTexture" "metal/plate01"\n\t"$alphatest" "1"\n\t"$nocull" "1"\n}\n',
"materials/models/test/skin_c.vmt": '"patch"\n{\n\t"include" "materials/models/test/skin_a.vmt"\n\t"replace"\n\t{\n\t\t"$basetexture" "models/test/skin_c"\n\t}\n}\n',
}
def case(ctx, rng, version):
m = make(rng, version)
checksum = rng.randrange(1 << 31)
mdl, ani, atts, seqs = write_mdl(m, rng, checksum)
vvd, lodcounts = write_vvd(m, rng, checksum)
vtx, tris = write_vtx(m, rng, checksum, m["ext"])
phy, soup, phytext = write_phy(rng, checksum)
tmp = tempfile.mkdtemp(prefix="rosetta-sourcemdl-")
try:
os.makedirs(os.path.join(tmp, "models", "test"))
for name, data in (("model.mdl", mdl), ("model.vvd", vvd), ("model.dx90.vtx", vtx), ("model.phy", phy)):
with open(os.path.join(tmp, "models", "test", name), "wb") as f:
f.write(data)
for path, text in VMTS.items():
os.makedirs(os.path.dirname(os.path.join(tmp, path)), exist_ok=True)
with open(os.path.join(tmp, path), "w") as f:
f.write(text)
st = srctools_view(ctx, tmp)
finally:
shutil.rmtree(tmp)
expect_parts = []
for pi, p in enumerate(m["parts"]):
models = []
for mi, md in enumerate(p["models"]):
meshes = []
for k, sm in enumerate(md["meshes"]):
vs = m["vertices"][md["start"] + sm["off"]:md["start"] + sm["off"] + sm["nv"]]
lods = []
for l in range(2):
t = tris["%d_%d_%d_%d" % (pi, mi, l, k)]
rev = []
for i in range(0, len(t) - 2, 3):
rev += [t[i + 2], t[i + 1], t[i]]
lods.append(rev)
fam = m["families"][0]
targets = {}
for f in sm["flexes"]:
for vv in f["verts"]:
for side in ((0, 1) if f["partner"] else (0,)):
wgt = 1 if not f["partner"] else (vv["side"] / 255 if side == 0 else 1 - vv["side"] / 255)
d = f["desc"] if side == 0 else f["partner"]
t = targets.setdefault(str(d), {})
cur = t.setdefault(str(vv["index"]), [0.0] * 6)
for c in range(6):
cur[c] = f32(cur[c] + vv["val"][c] * wgt)
meshes.append({
"positions": [c for v in vs for c in v["pos"]], "normals": [c for v in vs for c in v["nrm"]], "uvs": [c for v in vs for c in v["uv"]],
"tangents": [c for v in vs for c in v["tan"]],
"weights": [c for v in vs for c in v["w"] + [0.0]], "joints": [c if k2 < v["n"] else 0 for v in vs for k2, c in enumerate(v["b"] + [0])],
"lods": lods, "material": fam[sm["material"]] + 1, "skinRef": sm["material"], "targets": targets,
})
models.append({"name": md["name"], "meshes": meshes})
expect_parts.append({"name": p["name"], "models": models})
anims = []
for a in m["anims"]:
anims.append({"name": a["seq"], "frames": a["frames"], "fps": a["fps"], "delta": a["delta"],
"bones": {str(bi + 1): e for bi, e in a["expect"].items()}})
bones = [{"name": b["name"], "parent": b["parent"], "pos": b["pos"], "quat": b["quat"], "poseToBone": b["poseToBone"]} for b in m["bones"]]
files = {"model.vvd": vvd, "model.dx90.vtx": vtx, "model.phy": phy}
if ani and len(ani) > 64:
files["model.ani"] = ani
for path, text in VMTS.items():
files[path] = text
return {
"version": version, "mdl": mdl, "files": files, "srctools": st,
"expect": {"parts": expect_parts, "bones": bones, "anims": anims, "attachments": atts, "sequences": seqs, "physics": soup,
"flexdescs": m["flexdescs"], "lodCounts": lodcounts[:2], "checksum": checksum, "fixed": m["fixed"]},
}
def generate(ctx):
rng = ctx.rng(4449)
ctx.emit("sourcemdl", {"cases": [case(ctx, rng, v) for v in (44, 48, 49)]})