merge ws/blend

This commit is contained in:
4DBug committed 2026-11-01 19:48:59 -06:00
commit 11d0df9418
26 files changed
+17885 -1262

No files matched your search

+3 -2
View File
@@ -46,7 +46,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list
## Formats
<!-- formats:begin -->
186 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
187 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)
adds each format's capabilities.
| Category | Format | Extensions | Read | Write |
@@ -112,6 +112,7 @@ adds each format's capabilities.
| 3D models | 3ds | .3ds | yes | yes |
| 3D models | 3mf | .3mf | yes | yes |
| 3D models | b3d | .b3d | yes | - |
| 3D models | blend | .blend | yes | - |
| 3D models | bsp | .bsp | yes | - |
| 3D models | buildmap | .map | yes | yes |
| 3D models | d3map | .map | yes | - |
@@ -255,7 +256,7 @@ Shared by the formats, not loadable on their own (`src/Rosetta/codecs/<domain>/`
| model | Brush, Displacement, DoomMap, Draco, Mat4, MeshFlatten, Minecraft, Patch, Polygon, Rbx, Rig, Sampler, SourceAnim, Vrml |
| text | Json, KeyValues, Lexer, Nbt, Text, Url, Xml |
| 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, Blend, Chunks, Cpio, Demux, Ebml, Fat, Iso9660, IsoBmff, MacFile, MpegEs, MpegPs, MpegTs, Ogg, Riff, Tar, Zip |
<!-- codecs:end -->
## Licence
+3690
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.
+8 -7
View File
@@ -1,5 +1,5 @@
{
"Core_1": [[8, "src/Rosetta/init.luau"], [852, "src/Rosetta/Registry.luau"], [3105, "src/Rosetta/Types.luau"], [4188, "src/Rosetta/codecs/audio/Adpcm/init.luau"], [4942, "src/Rosetta/codecs/image/Yuv.luau"], [5210, "src/Rosetta/codecs/model/Rbx/init.luau"], [5447, "src/Rosetta/codecs/video/Video/init.luau"], [6004, "src/Rosetta/containers/AudioWrap.luau"], [6507, "src/Rosetta/containers/Ogg/Mux.luau"], [6702, "src/Rosetta/containers/Ogg/Page.luau"], [6871, "src/Rosetta/core/Bytes.luau"], [7398, "src/Rosetta/core/Crc32.luau"], [7510, "src/Rosetta/core/Err.luau"], [7592, "src/Rosetta/core/Input.luau"], [7668, "src/Rosetta/host/init.luau"]],
"Core_1": [[8, "src/Rosetta/init.luau"], [852, "src/Rosetta/Registry.luau"], [3117, "src/Rosetta/Types.luau"], [4200, "src/Rosetta/codecs/audio/Adpcm/init.luau"], [4954, "src/Rosetta/codecs/image/Yuv.luau"], [5222, "src/Rosetta/codecs/model/Rbx/init.luau"], [5459, "src/Rosetta/codecs/video/Video/init.luau"], [6016, "src/Rosetta/containers/AudioWrap.luau"], [6519, "src/Rosetta/containers/Ogg/Mux.luau"], [6714, "src/Rosetta/containers/Ogg/Page.luau"], [6883, "src/Rosetta/core/Bytes.luau"], [7410, "src/Rosetta/core/Crc32.luau"], [7522, "src/Rosetta/core/Err.luau"], [7604, "src/Rosetta/core/Input.luau"], [7680, "src/Rosetta/host/init.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"]],
"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"]],
@@ -39,7 +39,7 @@
"codecs_model": [[8, "src/Rosetta/codecs/model/Brush.luau"], [648, "src/Rosetta/codecs/model/Displacement.luau"], [797, "src/Rosetta/codecs/model/DoomMap/init.luau"], [1242, "src/Rosetta/codecs/model/DoomMap/Udmf.luau"], [1492, "src/Rosetta/codecs/model/Mat4.luau"], [1751, "src/Rosetta/codecs/model/MeshFlatten.luau"], [2279, "src/Rosetta/codecs/model/Minecraft/init.luau"], [2831, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], [2910, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], [3017, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], [3223, "src/Rosetta/codecs/model/Patch.luau"], [3347, "src/Rosetta/codecs/model/Polygon.luau"], [3581, "src/Rosetta/codecs/model/Rbx/Binary.luau"], [4335, "src/Rosetta/codecs/model/Rig.luau"], [4578, "src/Rosetta/codecs/model/Sampler.luau"], [4738, "src/Rosetta/codecs/model/SourceAnim.luau"], [4959, "src/Rosetta/codecs/model/Vrml/init.luau"], [5107, "src/Rosetta/codecs/model/Vrml/Build.luau"], [5681, "src/Rosetta/codecs/model/Vrml/Fields.luau"], [5844, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], [6593, "src/Rosetta/codecs/model/Vrml/Parse.luau"], [7115, "src/Rosetta/codecs/model/Vrml/Write.luau"], [7842, "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/KeyValues/init.luau"], [1563, "src/Rosetta/codecs/text/KeyValues/Binary.luau"], [1869, "src/Rosetta/codecs/text/Lexer/init.luau"], [2001, "src/Rosetta/codecs/text/Nbt/init.luau"], [2354, "src/Rosetta/codecs/text/Nbt/Binary.luau"], [3046, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], [3686, "src/Rosetta/codecs/text/Nbt/Value.luau"], [3924, "src/Rosetta/codecs/text/Text/init.luau"], [4015, "src/Rosetta/codecs/text/Url/init.luau"], [4220, "src/Rosetta/codecs/text/Xml/init.luau"], [4623, "src/Rosetta/codecs/text/Xml/Parse.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/Blend.luau"], [1566, "src/Rosetta/containers/Chunks.luau"], [1701, "src/Rosetta/containers/Cpio.luau"], [2129, "src/Rosetta/containers/Demux.luau"], [2404, "src/Rosetta/containers/Ebml/init.luau"], [2717, "src/Rosetta/containers/Fat.luau"], [3405, "src/Rosetta/containers/Iso9660.luau"], [3910, "src/Rosetta/containers/IsoBmff/init.luau"], [4080, "src/Rosetta/containers/IsoBmff/Box.luau"], [4268, "src/Rosetta/containers/IsoBmff/Demux.luau"], [5113, "src/Rosetta/containers/IsoBmff/Meta.luau"], [5634, "src/Rosetta/containers/IsoBmff/Mux.luau"], [6150, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], [6267, "src/Rosetta/containers/MacFile.luau"], [6416, "src/Rosetta/containers/Ogg/init.luau"], [6841, "src/Rosetta/containers/Riff/init.luau"], [7158, "src/Rosetta/containers/Tar.luau"], [7572, "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"]],
"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"]],
@@ -47,11 +47,12 @@
"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_2": [[8, "src/Rosetta/image/tga/Codec.luau"], [160, "src/Rosetta/image/tiff/init.luau"], [987, "src/Rosetta/image/tiff/Pixels.luau"], [1377, "src/Rosetta/image/tim/init.luau"], [1619, "src/Rosetta/image/vtf/init.luau"], [1854, "src/Rosetta/image/webp/init.luau"], [2464, "src/Rosetta/image/webp/Alpha.luau"], [2540, "src/Rosetta/image/webp/Anim.luau"], [2695, "src/Rosetta/image/xbm/init.luau"], [2856, "src/Rosetta/image/xpm/init.luau"], [3124, "src/Rosetta/image/xpm/Names.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"], [4148, "src/Rosetta/model/bsp/Quake3.luau"], [4376, "src/Rosetta/model/buildmap/init.luau"], [4648, "src/Rosetta/model/buildmap/Geometry.luau"], [5051, "src/Rosetta/model/d3map/init.luau"], [5333, "src/Rosetta/model/d3map/Parse.luau"], [5531, "src/Rosetta/model/dae/init.luau"], [5720, "src/Rosetta/model/dae/Math.luau"], [5767, "src/Rosetta/model/dae/Read.luau"]],
"model_2": [[8, "src/Rosetta/model/dae/Write.luau"], [377, "src/Rosetta/model/fbx/init.luau"], [525, "src/Rosetta/model/fbx/Ascii.luau"], [795, "src/Rosetta/model/fbx/Binary.luau"], [1250, "src/Rosetta/model/fbx/Read.luau"], [2612, "src/Rosetta/model/fbx/Write.luau"], [3597, "src/Rosetta/model/fbx/Xform.luau"], [3638, "src/Rosetta/model/gltf/init.luau"], [3875, "src/Rosetta/model/gltf/Pack.luau"], [3944, "src/Rosetta/model/gltf/Read.luau"], [4675, "src/Rosetta/model/gltf/Write.luau"], [5355, "src/Rosetta/model/iqm/init.luau"], [5431, "src/Rosetta/model/iqm/Read.luau"], [5786, "src/Rosetta/model/iqm/Write.luau"], [6473, "src/Rosetta/model/ldraw/init.luau"], [6551, "src/Rosetta/model/ldraw/Colors.luau"], [6869, "src/Rosetta/model/ldraw/Read.luau"]],
"model_3": [[8, "src/Rosetta/model/lwo/init.luau"], [84, "src/Rosetta/model/lwo/Build.luau"], [546, "src/Rosetta/model/lwo/Parse.luau"], [1089, "src/Rosetta/model/map/init.luau"], [1406, "src/Rosetta/model/map/Build.luau"], [1649, "src/Rosetta/model/map/Parse.luau"], [2034, "src/Rosetta/model/map/Write.luau"], [2180, "src/Rosetta/model/mca/init.luau"], [2522, "src/Rosetta/model/mca/Chunk.luau"], [2655, "src/Rosetta/model/mca/Lz4Block.luau"], [2725, "src/Rosetta/model/md2/init.luau"], [2924, "src/Rosetta/model/md3/init.luau"], [3152, "src/Rosetta/model/md5/init.luau"], [3233, "src/Rosetta/model/md5/Read.luau"], [3666, "src/Rosetta/model/mdl/init.luau"], [3748, "src/Rosetta/model/mdl/HalfLife.luau"], [4052, "src/Rosetta/model/mdl/Quake.luau"], [4270, "src/Rosetta/model/ms3d/init.luau"], [4342, "src/Rosetta/model/ms3d/Read.luau"], [4788, "src/Rosetta/model/ms3d/Write.luau"], [5257, "src/Rosetta/model/obj/init.luau"], [5999, "src/Rosetta/model/obj/Mtl.luau"], [6286, "src/Rosetta/model/off/init.luau"], [6748, "src/Rosetta/model/ply/init.luau"]],
"model_4": [[8, "src/Rosetta/model/ply/Binary.luau"], [209, "src/Rosetta/model/pmx/init.luau"], [278, "src/Rosetta/model/pmx/Build.luau"], [574, "src/Rosetta/model/pmx/Pmd.luau"], [909, "src/Rosetta/model/pmx/Read.luau"], [1313, "src/Rosetta/model/proc/init.luau"], [1695, "src/Rosetta/model/qb/init.luau"], [2088, "src/Rosetta/model/rbxm/init.luau"], [2680, "src/Rosetta/model/rbxmx/init.luau"], [3333, "src/Rosetta/model/robloxmesh/init.luau"], [3992, "src/Rosetta/model/robloxmesh/Parse.luau"], [4449, "src/Rosetta/model/robloxmesh/Write.luau"], [4558, "src/Rosetta/model/schematic/init.luau"], [4879, "src/Rosetta/model/schematic/Common.luau"], [4999, "src/Rosetta/model/schematic/Litematic.luau"], [5210, "src/Rosetta/model/schematic/Mcedit.luau"], [5454, "src/Rosetta/model/schematic/Sponge.luau"], [5583, "src/Rosetta/model/smd/init.luau"], [5650, "src/Rosetta/model/smd/Read.luau"], [5919, "src/Rosetta/model/smd/Write.luau"], [6162, "src/Rosetta/model/sourcemdl/init.luau"], [6333, "src/Rosetta/model/sourcemdl/Build.luau"], [6763, "src/Rosetta/model/sourcemdl/Material.luau"], [6924, "src/Rosetta/model/sourcemdl/Mdl.luau"], [7451, "src/Rosetta/model/sourcemdl/Phy.luau"], [7574, "src/Rosetta/model/sourcemdl/Vtx.luau"], [7756, "src/Rosetta/model/sourcemdl/Vvd.luau"]],
"model_5": [[8, "src/Rosetta/model/stl/init.luau"], [458, "src/Rosetta/model/stl/Decode.luau"], [532, "src/Rosetta/model/udmf/init.luau"], [615, "src/Rosetta/model/usda/init.luau"], [824, "src/Rosetta/model/usda/Build.luau"], [2102, "src/Rosetta/model/usda/Parse.luau"], [2900, "src/Rosetta/model/usda/Write.luau"], [3717, "src/Rosetta/model/vbsp/init.luau"], [4163, "src/Rosetta/model/vbsp/Faces.luau"], [4387, "src/Rosetta/model/vbsp/Props.luau"], [4479, "src/Rosetta/model/vmf/init.luau"], [4804, "src/Rosetta/model/vmf/Build.luau"], [5228, "src/Rosetta/model/vox/init.luau"], [6114, "src/Rosetta/model/vox/Grid.luau"], [6171, "src/Rosetta/model/vrml/init.luau"], [6237, "src/Rosetta/model/x/init.luau"], [6367, "src/Rosetta/model/x/Build.luau"], [6930, "src/Rosetta/model/x/Parse.luau"], [7227, "src/Rosetta/model/x3d/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/blend/init.luau"], [3836, "src/Rosetta/model/blend/Anim.luau"], [4182, "src/Rosetta/model/blend/Material.luau"], [4534, "src/Rosetta/model/blend/Mesh.luau"], [5169, "src/Rosetta/model/blend/Normals.luau"], [5330, "src/Rosetta/model/blend/Prim.luau"], [5779, "src/Rosetta/model/blend/Read.luau"], [6679, "src/Rosetta/model/bsp/init.luau"], [6824, "src/Rosetta/model/bsp/Brush.luau"], [7087, "src/Rosetta/model/bsp/Quake3.luau"]],
"model_2": [[8, "src/Rosetta/model/buildmap/init.luau"], [280, "src/Rosetta/model/buildmap/Geometry.luau"], [683, "src/Rosetta/model/d3map/init.luau"], [965, "src/Rosetta/model/d3map/Parse.luau"], [1163, "src/Rosetta/model/dae/init.luau"], [1352, "src/Rosetta/model/dae/Math.luau"], [1399, "src/Rosetta/model/dae/Read.luau"], [3249, "src/Rosetta/model/dae/Write.luau"], [3618, "src/Rosetta/model/fbx/init.luau"], [3766, "src/Rosetta/model/fbx/Ascii.luau"], [4036, "src/Rosetta/model/fbx/Binary.luau"], [4491, "src/Rosetta/model/fbx/Read.luau"], [5853, "src/Rosetta/model/fbx/Write.luau"], [6838, "src/Rosetta/model/fbx/Xform.luau"], [6879, "src/Rosetta/model/gltf/init.luau"], [7116, "src/Rosetta/model/gltf/Pack.luau"]],
"model_3": [[8, "src/Rosetta/model/gltf/Read.luau"], [739, "src/Rosetta/model/gltf/Write.luau"], [1419, "src/Rosetta/model/iqm/init.luau"], [1495, "src/Rosetta/model/iqm/Read.luau"], [1850, "src/Rosetta/model/iqm/Write.luau"], [2537, "src/Rosetta/model/ldraw/init.luau"], [2615, "src/Rosetta/model/ldraw/Colors.luau"], [2933, "src/Rosetta/model/ldraw/Read.luau"], [3510, "src/Rosetta/model/lwo/init.luau"], [3586, "src/Rosetta/model/lwo/Build.luau"], [4048, "src/Rosetta/model/lwo/Parse.luau"], [4591, "src/Rosetta/model/map/init.luau"], [4908, "src/Rosetta/model/map/Build.luau"], [5151, "src/Rosetta/model/map/Parse.luau"], [5536, "src/Rosetta/model/map/Write.luau"], [5682, "src/Rosetta/model/mca/init.luau"], [6024, "src/Rosetta/model/mca/Chunk.luau"], [6157, "src/Rosetta/model/mca/Lz4Block.luau"], [6227, "src/Rosetta/model/md2/init.luau"], [6426, "src/Rosetta/model/md3/init.luau"], [6654, "src/Rosetta/model/md5/init.luau"], [6735, "src/Rosetta/model/md5/Read.luau"], [7168, "src/Rosetta/model/mdl/init.luau"], [7250, "src/Rosetta/model/mdl/HalfLife.luau"]],
"model_4": [[8, "src/Rosetta/model/mdl/Quake.luau"], [226, "src/Rosetta/model/ms3d/init.luau"], [298, "src/Rosetta/model/ms3d/Read.luau"], [744, "src/Rosetta/model/ms3d/Write.luau"], [1213, "src/Rosetta/model/obj/init.luau"], [1955, "src/Rosetta/model/obj/Mtl.luau"], [2242, "src/Rosetta/model/off/init.luau"], [2704, "src/Rosetta/model/ply/init.luau"], [3809, "src/Rosetta/model/ply/Binary.luau"], [4010, "src/Rosetta/model/pmx/init.luau"], [4079, "src/Rosetta/model/pmx/Build.luau"], [4375, "src/Rosetta/model/pmx/Pmd.luau"], [4710, "src/Rosetta/model/pmx/Read.luau"], [5114, "src/Rosetta/model/proc/init.luau"], [5496, "src/Rosetta/model/qb/init.luau"], [5889, "src/Rosetta/model/rbxm/init.luau"], [6481, "src/Rosetta/model/rbxmx/init.luau"], [7134, "src/Rosetta/model/robloxmesh/init.luau"]],
"model_5": [[8, "src/Rosetta/model/robloxmesh/Parse.luau"], [465, "src/Rosetta/model/robloxmesh/Write.luau"], [574, "src/Rosetta/model/schematic/init.luau"], [895, "src/Rosetta/model/schematic/Common.luau"], [1015, "src/Rosetta/model/schematic/Litematic.luau"], [1226, "src/Rosetta/model/schematic/Mcedit.luau"], [1470, "src/Rosetta/model/schematic/Sponge.luau"], [1599, "src/Rosetta/model/smd/init.luau"], [1666, "src/Rosetta/model/smd/Read.luau"], [1935, "src/Rosetta/model/smd/Write.luau"], [2178, "src/Rosetta/model/sourcemdl/init.luau"], [2349, "src/Rosetta/model/sourcemdl/Build.luau"], [2779, "src/Rosetta/model/sourcemdl/Material.luau"], [2940, "src/Rosetta/model/sourcemdl/Mdl.luau"], [3467, "src/Rosetta/model/sourcemdl/Phy.luau"], [3590, "src/Rosetta/model/sourcemdl/Vtx.luau"], [3772, "src/Rosetta/model/sourcemdl/Vvd.luau"], [3866, "src/Rosetta/model/stl/init.luau"], [4316, "src/Rosetta/model/stl/Decode.luau"], [4390, "src/Rosetta/model/udmf/init.luau"], [4473, "src/Rosetta/model/usda/init.luau"], [4682, "src/Rosetta/model/usda/Build.luau"], [5960, "src/Rosetta/model/usda/Parse.luau"], [6758, "src/Rosetta/model/usda/Write.luau"], [7575, "src/Rosetta/model/vbsp/init.luau"]],
"model_6": [[8, "src/Rosetta/model/vbsp/Faces.luau"], [232, "src/Rosetta/model/vbsp/Props.luau"], [324, "src/Rosetta/model/vmf/init.luau"], [649, "src/Rosetta/model/vmf/Build.luau"], [1073, "src/Rosetta/model/vox/init.luau"], [1959, "src/Rosetta/model/vox/Grid.luau"], [2016, "src/Rosetta/model/vrml/init.luau"], [2082, "src/Rosetta/model/x/init.luau"], [2212, "src/Rosetta/model/x/Build.luau"], [2775, "src/Rosetta/model/x/Parse.luau"], [3072, "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"]],
"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"]],
+3821 -110
View File
File diff suppressed because it is too large. Load diff
+3690
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1
View File
@@ -66,6 +66,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| model | 3ds | .3ds | yes | yes | materials: true, textures: true, animation: true, cameras: true, lights: true, instancing: true | `tests/model/3ds.luau` |
| model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` |
| model | b3d | .b3d | yes | - | materials: true, textures: true, skins: true, animation: true, colors: true | `tests/model/b3d.luau` |
| model | blend | .blend | yes | - | materials: true, textures: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true, compressed: true | `tests/model/blend.luau` |
| model | bsp | .bsp | yes | - | variants: "quake", "halflife", "quake2", "quake3", lightmaps: "quake3" | `tests/model/bsp.luau` |
| model | buildmap | .map | yes | yes | sprites: true, slopes: true | `tests/model/buildmap.luau` |
| model | d3map | .map | yes | - | patches: true, variants: "doom3", "quake4" | `tests/model/d3map.luau` |
+50 -1
View File
@@ -2,7 +2,7 @@
Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, 3DS, MS3D, B3D, LDraw, LightWave
LWO, DirectX .x, IQM, PMX / PMD, VRML, X3D, the [game models](#game-models) MD2 / MD3 / MDL / MD5 / BSP / SMD,
[Roblox meshes](roblox.md) and the [Minecraft and Qubicle voxel files](voxel.md)) loads as one `Scene`, a structure shaped like glTF 2.0: a node tree, meshes
[Blender .blend](#blender-blend), [Roblox meshes](roblox.md) and the [Minecraft and Qubicle voxel files](voxel.md)) loads as one `Scene`, a structure shaped like glTF 2.0: a node tree, meshes
made of primitives, flat attribute buffers (accessors), PBR materials, textures, cameras, lights, skins and animations.
Mesh-only formats (STL, PLY, OFF) give a one-node scene. MagicaVoxel files also carry voxel grids (`scene.voxels`).
Editing goes through `F.ops.mesh`.
@@ -884,6 +884,54 @@ assert(back.meta.source.format == "iqm" and back.meshes[1].name == "tri")
assert(back.meshes[1].primitives[1].indices.count == 3)
```
## Blender (.blend)
`.blend` files load read only, from every Blender version since 2.4x: plain, gzip (before 3.0) or zstd (3.0+)
compressed, 32 or 64-bit pointers, either byte order, and the 5.0+ header. Each file is read through its own SDNA (the
struct catalogue Blender writes into every file), so fields are found by name whatever version wrote them. The
current scene loads: objects (transforms with euler orders, quaternions, axis angles, delta transforms, the parent
inverse, bone parents), collections as nodes (`collections = false` flattens them), meshes, materials, images,
cameras, lights, armatures, skins, shape keys and actions. Blender is z-up (`meta.up = "z"`).
| Part | What loads |
|---|---|
| Meshes | every storage generation: MFace (before 2.63 and the 2.7x "legacy mesh format"), MPoly / MLoop (2.63 - 3.x), attribute layers (`position`, `.corner_vert`, ... 3.x - 4.x), AttributeStorage (5.x); a primitive per used material slot, `triangulate = false` keeps the faces (`"polygons"`) |
| Mesh data | UV maps (`TEXCOORD_n`, v flipped to glTF's origin), colour attributes (byte and float, point and corner) as linear `COLOR_n`, corner normals from Blender's smooth fans (sharp edges / faces, auto smooth before 4.1) or the stored custom normals, weights (`JOINTS_0` / `WEIGHTS_0`: the 4 largest deform-bone groups, normalized) |
| Materials | the Principled BSDF (base colour, metallic, roughness, alpha, emission and its strength, image textures on Base Color / Emission, Normal through a Normal Map node, Roughness / Metallic through Separate RGB), else the legacy `r, g, b` colour |
| Images | packed images as encoded bytes (`texture.data`), external ones as `uri` (relative to the `.blend`, bytes through `files` / `resolve`) |
| Cameras, lights | perspective (`yfov` from the lens, sensor fit and render aspect) / orthographic; point, sun, spot (watts to candela / lux as Blender's glTF exporter does); area lights are skipped (`meta.source.skippedLights`) |
| Armatures | a joint node per bone (rest pose times the saved pose), one skin per deformed mesh |
| Animation | the active action of each object, armature (pose bones) and shape key set, f-curves evaluated (constant, linear, bezier, easing; extrapolation) and sampled once per frame (`sampleStep`) into channels; time 0 is `meta.source.frameZero` at `meta.source.fps` |
| Not loaded | modifiers (listed per object in `meta.source.modifiers`, never applied), curves, text, metaballs, grease pencil, volumes, NLA strips, drivers, constraints, linked libraries |
```luau
local scene = assert(F.model.load(riggedBlendBytes))
local src = scene.meta.source
assert(src.format == "blend" and src.version >= 500 and src.compression == "zstd")
assert(scene.meta.up == "z" and #scene.skins == 1 and #scene.animations == 1)
local tube = scene.meshes[1].primitives[1]
assert(tube.attributes.JOINTS_0 and tube.attributes.WEIGHTS_0 and #tube.targets == 1)
assert(scene.materials[1].name == "Skin" and scene.materials[1].roughness > 0.69)
print(src.modifiers.Tube[1].type) -- Armature (not applied)
```
Anything else in the file is reachable through the container: `F.format("blend").open` parses the blocks and the
SDNA, and every struct reads by field name (`get`, `num`, `str`, `vec`, `sub`, `deref`, `list` for ListBase, `array`
and `pointers` behind pointers).
```luau
local blend = F.format("blend")
local file = assert(blend.open(F.Bytes.reader(riggedBlendBytes)))
local Blend = blend.container
for _, block in Blend.blocks(file, "OB") do
local ob = assert(Blend.struct(file, block))
print(ob:idName(), ob:num("type"), ob:vec("loc")[3]) -- Rig 25 0 / Tube 1 0
end
local arm = assert(Blend.struct(file, Blend.blocks(file, "AR")[1]))
local bones = arm:list("bonebase")
assert(bones[1]:str("name") == "lower" and bones[1]:list("childbase")[1]:str("name") == "upper")
```
## Formats
| Format | Read | Write | Notes |
@@ -921,6 +969,7 @@ assert(back.meshes[1].primitives[1].indices.count == 3)
| Doom 3 / Quake 4 `.proc` | yes | | render geometry per area, portals and BSP nodes as data |
| Doom 3 / Quake 4 `.map` (d3map) | yes | | brushDef3, patchDef2 / 3, entities as nodes |
| UDMF (`.udmf`, `TEXTMAP`) | yes | | Doom maps as text: see "Doom maps (UDMF)" above |
| Blender `.blend` | yes | | 2.4x - 5.x, compressed; meshes of every generation, materials, skins, shape keys, actions; see "Blender" above |
| 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) |
+12
View File
@@ -746,6 +746,18 @@ local list: { Entry } = {
return require("@rosetta/model/b3d")
end,
},
{
name = "blend",
category = "model",
path = "model/blend",
extensions = { "blend" },
mime = { "application/x-blender" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" },
caps = { decode = true, encode = false, materials = true, textures = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true, compressed = true },
load = function()
return require("@rosetta/model/blend")
end,
},
{
name = "bsp",
category = "model",
+737
View File
@@ -0,0 +1,737 @@
--!strict
-- containers/Blend: Blender .blend files (read only). New in rosetta, from the file layout: the 12-byte header
-- ("BLENDER", pointer size '_' 4 / '-' 8, endianness 'v' little / 'V' big, 3-digit version) or the 5.0+ header
-- ("BLENDER", header size "17", '-', format version "01", 'v', 4-digit version: 64-bit little endian, large BHeads);
-- file blocks (BHead: code, length, old address, SDNA index, count); the DNA1 block (SDNA: NAME / TYPE / TLEN / STRC,
-- each section 4-aligned from the block start); gzip (before 3.0) and zstd (3.0+, multi-frame) compressed files.
-- Structs are read by field name through the file's own SDNA; pointers resolve to blocks by old address.
local Err = require("@rosetta/core/Err")
local Deflate = require("@rosetta/codecs/compress/Deflate")
local Zstd = require("@rosetta/codecs/compress/Zstd")
local Blend = {}
local readu8, readu16, readu32, readi8, readi16, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi8, buffer.readi16, buffer.readi32
local readf32, readf64, readstring = buffer.readf32, buffer.readf64, buffer.readstring
export type Field = {
name: string, -- without '*', '(*...)()' and array dimensions
decl: string, -- as declared ("*next", "co[3]", "mat[4][4]")
type: string,
offset: number,
size: number, -- bytes of the whole field (all array elements)
pointer: boolean,
dims: { number },
count: number, -- array elements (1 for scalars)
elem: number, -- bytes of one element
}
export type Struct = { name: string, index: number, size: number, fields: { Field }, byName: { [string]: Field } }
export type Dna = {
names: { string },
types: { string },
lengths: { number },
structs: { Struct }, -- 1-based; a block's sdna is 0-based
byName: { [string]: Struct },
}
export type Block = {
code: string, -- "OB", "ME", "DATA", ... (trailing NULs removed)
sdna: number, -- 0-based struct index
addr: any, -- the old address (a key: a number for 4-byte pointers, an 8-byte string for 8-byte ones)
size: number, -- data bytes
count: number, -- struct elements
offset: number, -- data start in file.buf
index: number,
owner: number, -- the index of the ID block this block follows (DATA blocks belong to the ID before them)
}
export type File = {
buf: buffer, -- the (decompressed) file
version: number, -- 279, 293, 401, 502, ...
subversion: number?, -- from the GLOB block
pointerSize: number,
little: boolean,
format: number, -- 0 (12-byte header) or the 5.0+ file format version
compression: string?, -- "gzip" | "zstd"
blocks: { Block },
byAddr: { [any]: Block },
shared: { [any]: { Block } }, -- addresses used by several blocks (reused between IDs): every block with it
byCode: { [string]: { Block } },
dna: Dna,
-- endian-aware readers (the little-endian ones are buffer's own)
u16: (b: buffer, o: number) -> number,
i16: (b: buffer, o: number) -> number,
u32: (b: buffer, o: number) -> number,
i32: (b: buffer, o: number) -> number,
f32: (b: buffer, o: number) -> number,
f64: (b: buffer, o: number) -> number,
}
export type Options = { maxBytes: number?, maxBlocks: number? }
-- ------------------------------------------------------------------------------------------------ readers
local function swap16(b: buffer, o: number): number
return readu8(b, o) * 256 + readu8(b, o + 1)
end
local function swap32(b: buffer, o: number): number
return ((readu8(b, o) * 256 + readu8(b, o + 1)) * 256 + readu8(b, o + 2)) * 256 + readu8(b, o + 3)
end
local scratch = buffer.create(8)
local function bei16(b: buffer, o: number): number
local v = swap16(b, o)
return if v >= 32768 then v - 65536 else v
end
local function bei32(b: buffer, o: number): number
local v = swap32(b, o)
return if v >= 2147483648 then v - 4294967296 else v
end
local function bef32(b: buffer, o: number): number
for k = 0, 3 do
buffer.writeu8(scratch, k, readu8(b, o + 3 - k))
end
return readf32(scratch, 0)
end
local function bef64(b: buffer, o: number): number
for k = 0, 7 do
buffer.writeu8(scratch, k, readu8(b, o + 7 - k))
end
return readf64(scratch, 0)
end
-- ------------------------------------------------------------------------------------------------ open
function Blend.sniff(buf: buffer, offset: number?, length: number?): number
local o = offset or 0
local n = length or (buffer.len(buf) - o)
if n >= 12 and readstring(buf, o, 7) == "BLENDER" then
return 1
end
if n >= 4 and readu8(buf, o) == 0x1f and readu8(buf, o + 1) == 0x8b then
return 0.05 -- a gzip member: blend only once decompressed
end
return 0
end
local function decompress(buf: buffer, o: number, n: number, opts: Options?): (buffer?, string?, any)
local maxBytes = opts and opts.maxBytes or 2 ^ 31
if n >= 4 and readu8(buf, o) == 0x1f and readu8(buf, o + 1) == 0x8b then
local out, err = Deflate.gunzip(buf, o, n)
if not out then
return nil, nil, err
end
if buffer.len(out) > maxBytes then
return nil, nil, Err.new(Err.LIMIT, "decompressed file over maxBytes")
end
return out, "gzip", nil
end
if n >= 4 and readu32(buf, o) == 0xFD2FB528 then
local out, err = Zstd.decompress(buf, o, n, { maxBytes = maxBytes })
if not out then
return nil, nil, err
end
return out, "zstd", nil
end
return nil, nil, nil
end
local function header(b: buffer, n: number): (number?, number, boolean, number, number, string?)
if n < 12 or readstring(b, 0, 7) ~= "BLENDER" then
return nil, 0, false, 0, 0, "not a .blend file (no BLENDER magic)"
end
local c = readstring(b, 7, 1)
if c == "_" or c == "-" then
local e = readstring(b, 8, 1)
local v = tonumber(readstring(b, 9, 3))
if (e ~= "v" and e ~= "V") or not v then
return nil, 0, false, 0, 0, "bad header"
end
return 12, if c == "_" then 4 else 8, e == "v", v, 0, nil
end
local hs = tonumber(readstring(b, 7, 2))
if not hs or hs < 17 or hs > n then
return nil, 0, false, 0, 0, "bad header size"
end
if readstring(b, 9, 1) ~= "-" or readstring(b, 12, 1) ~= "v" then
return nil, 0, false, 0, 0, "unsupported header: " .. readstring(b, 7, math.min(10, n - 7))
end
local fmt, v = tonumber(readstring(b, 10, 2)), tonumber(readstring(b, 13, 4))
if not fmt or not v then
return nil, 0, false, 0, 0, "bad header"
end
if fmt ~= 1 then
return nil, 0, false, 0, 0, "unsupported: file format version " .. fmt
end
return hs, 8, true, v, fmt, nil
end
local PRIM: { [string]: boolean } = {
char = true, uchar = true, short = true, ushort = true, int = true, uint = true, long = true, ulong = true,
float = true, double = true, int64_t = true, uint64_t = true, int8_t = true, uint8_t = true, int16_t = true,
uint16_t = true, int32_t = true, uint32_t = true, bool = true, void = true,
}
Blend.PRIMITIVE = PRIM
local function parseDna(f: File, at: number, size: number): string?
local b = f.buf
local e = at + size
local i32 = f.i32
local function align(p: number): number
return at + ((p - at + 3) // 4) * 4
end
local function strings(p: number, tag: string): ({ string }?, number)
if p + 8 > e or readstring(b, p, 4) ~= tag then
return nil, p
end
local n = i32(b, p + 4)
p += 8
if n < 0 or n > e - p then
return nil, p
end
local out = table.create(n) :: { string }
for k = 1, n do
local q = p
while q < e and readu8(b, q) ~= 0 do
q += 1
end
if q >= e then
return nil, p
end
out[k] = readstring(b, p, q - p)
p = q + 1
end
return out, p
end
if e > buffer.len(b) or size < 8 or readstring(b, at, 4) ~= "SDNA" then
return "no SDNA in DNA1"
end
local names, p = strings(at + 4, "NAME")
if not names then
return "bad SDNA NAME"
end
local types
types, p = strings(align(p), "TYPE")
if not types then
return "bad SDNA TYPE"
end
p = align(p)
local nt = #types
if p + 4 + nt * 2 > e or readstring(b, p, 4) ~= "TLEN" then
return "bad SDNA TLEN"
end
local lengths = table.create(nt) :: { number }
for k = 1, nt do
lengths[k] = f.u16(b, p + 4 + (k - 1) * 2)
end
p = align(p + 4 + nt * 2)
if p + 8 > e or readstring(b, p, 4) ~= "STRC" then
return "bad SDNA STRC"
end
local ns = i32(b, p + 4)
p += 8
if ns < 0 or ns * 4 > e - p then
return "bad SDNA struct count"
end
local i16 = f.i16
local ps = f.pointerSize
local structs, byName = table.create(ns) :: { Struct }, {} :: { [string]: Struct }
for k = 1, ns do
if p + 4 > e then
return "truncated SDNA structs"
end
local t, nf = i16(b, p), i16(b, p + 2)
p += 4
if t < 0 or t >= nt or nf < 0 or p + nf * 4 > e then
return "bad SDNA struct " .. k
end
local tnames = types :: { string }
local s: Struct = { name = tnames[t + 1], index = k - 1, size = lengths[t + 1], fields = table.create(nf) :: { Field }, byName = {} }
local off = 0
for j = 1, nf do
local ft, fn = i16(b, p), i16(b, p + 2)
p += 4
if ft < 0 or ft >= nt or fn < 0 or fn >= #names then
return "bad SDNA field in " .. s.name
end
local decl: string = (names :: { string })[fn + 1]
local pointer = string.sub(decl, 1, 1) == "*" or string.sub(decl, 1, 2) == "(*"
local dims: { number }, count = {}, 1
for d in string.gmatch(decl, "%[(%d+)%]") do
local v = tonumber(d) or 1
table.insert(dims, v)
count *= v
end
local base = string.gsub(decl, "%[.*$", "")
base = string.gsub(base, "[%*%(%)]", "")
local elem: number = if pointer then ps else lengths[ft + 1]
local fld: Field = {
name = base, decl = decl, type = tnames[ft + 1], offset = off, size = elem * count,
pointer = pointer, dims = dims, count = count, elem = elem,
}
s.fields[j] = fld
if s.byName[base] == nil then
s.byName[base] = fld
end
off += fld.size
end
structs[k] = s
byName[s.name] = s
end
f.dna = { names = names :: { string }, types = types :: { string }, lengths = lengths, structs = structs, byName = byName }
return nil
end
function Blend.open(data: buffer, offset: number?, length: number?, opts: Options?): (File?, Err.Err?)
local o = offset or 0
local n = length or (buffer.len(data) - o)
if o < 0 or n < 0 or o + n > buffer.len(data) then
return nil, Err.new(Err.ARG, "bad range")
end
local b: buffer
local unpacked, compression, derr = decompress(data, o, n, opts)
if derr then
return nil, derr
end
if unpacked then
b = unpacked
n = buffer.len(b)
elseif o == 0 and n == buffer.len(data) then
b = data
else
b = buffer.create(n)
buffer.copy(b, 0, data, o, n)
end
local hs, ps, little, version, fmt, herr = header(b, n)
if not hs then
local code = if n < 12 then Err.TRUNCATED elseif herr and string.sub(herr, 1, 12) == "unsupported:" then Err.UNSUPPORTED else Err.CORRUPT
return nil, Err.new(code, herr or "bad header", 0)
end
local f: File = {
buf = b, version = version, subversion = nil, pointerSize = ps, little = little, format = fmt,
compression = compression, blocks = {}, byAddr = {}, shared = {}, byCode = {}, dna = nil :: any,
u16 = if little then readu16 else swap16,
i16 = if little then readi16 else bei16,
u32 = if little then readu32 else swap32,
i32 = if little then readi32 else bei32,
f32 = if little then readf32 else bef32,
f64 = if little then readf64 else bef64,
}
local u32, i32 = f.u32, f.i32
local maxBlocks = opts and opts.maxBlocks or 2 ^ 22
local bh = if fmt >= 1 then 32 elseif ps == 8 then 24 else 20
local p = hs
local dnaBlock: Block? = nil
local owner = 0
while true do
if p + bh > n then
if p + 4 <= n and readstring(b, p, 4) == "ENDB" then
break -- ENDB written with a short head
end
return nil, Err.new(Err.TRUNCATED, "truncated block header (no ENDB)", p)
end
local code = readstring(b, p, 4)
local size, addr, sdna, count
if fmt >= 1 then
sdna = i32(b, p + 4)
addr = readstring(b, p + 8, 8)
local lo, hi = u32(b, p + 16), i32(b, p + 20)
local clo, chi = u32(b, p + 24), i32(b, p + 28)
if hi ~= 0 or chi ~= 0 then
return nil, Err.new(Err.LIMIT, "block over 4 GiB", p)
end
size, count = lo, clo
else
size = i32(b, p + 4)
addr = if ps == 8 then readstring(b, p + 8, 8) else u32(b, p + 8)
sdna = i32(b, p + 8 + ps)
count = i32(b, p + 12 + ps)
end
p += bh
-- two-letter ID codes are a 16-bit value in a 32-bit field: "\0\0SC" in big-endian files
code = string.gsub(string.gsub(code, "%z+$", ""), "^%z+", "")
if code == "ENDB" then
break
end
if size < 0 or count < 0 or size > n - p then
return nil, Err.new(Err.TRUNCATED, "block " .. code .. " past the end", p - bh)
end
if #f.blocks >= maxBlocks then
return nil, Err.new(Err.LIMIT, "too many blocks")
end
local index = #f.blocks + 1
if code ~= "DATA" then
owner = index
end
local blk: Block = { code = code, sdna = sdna, addr = addr, size = size, count = count, offset = p, index = index, owner = owner }
table.insert(f.blocks, blk)
local prev = f.byAddr[addr]
if prev == nil then
f.byAddr[addr] = blk
else
local list = f.shared[addr]
if not list then
list = { prev }
f.shared[addr] = list
end
table.insert(list, blk)
end
local list = f.byCode[code]
if not list then
list = {}
f.byCode[code] = list
end
table.insert(list, blk)
if code == "DNA1" then
dnaBlock = blk
end
p += size
end
if not dnaBlock then
return nil, Err.new(Err.CORRUPT, "no DNA1 block")
end
local derr2 = parseDna(f, dnaBlock.offset, dnaBlock.size)
if derr2 then
return nil, Err.new(Err.CORRUPT, derr2, dnaBlock.offset)
end
f.byAddr[if ps == 8 then string.rep("\0", 8) else 0] = nil
local glob = f.byCode.GLOB
local fg = f.dna.byName.FileGlobal
local g1: Block? = if glob then glob[1] else nil
local fld = fg and fg.byName.subversion
if g1 and fld then
if fld.offset + 2 <= g1.size then
f.subversion = f.i16(b, g1.offset + fld.offset)
end
end
return f, nil
end
-- ------------------------------------------------------------------------------------------------ structs
local View = {}
View.__index = View
Blend.View = View
export type View = typeof(setmetatable(
{} :: {
file: File,
struct: Struct,
offset: number, -- the struct's first byte in file.buf
block: Block?,
},
View
))
local function view(f: File, s: Struct, offset: number, blk: Block?): View
return setmetatable({ file = f, struct = s, offset = offset, block = blk }, View)
end
function Blend.structOf(f: File, blk: Block): Struct?
return f.dna.structs[blk.sdna + 1]
end
function Blend.struct(f: File, blk: Block, i: number?, as: string?): View?
local s = if as then f.dna.byName[as] else f.dna.structs[blk.sdna + 1]
if not s then
return nil
end
local at = (i or 0) * s.size
if at < 0 or at + s.size > blk.size then
return nil
end
return view(f, s, blk.offset + at, blk)
end
function Blend.view(f: File, structName: string, offset: number): View?
local s = f.dna.byName[structName]
if not s or offset < 0 or offset + s.size > buffer.len(f.buf) then
return nil
end
return view(f, s, offset, nil)
end
function Blend.field(f: File, structName: string, ...: string): Field?
local s = f.dna.byName[structName]
if not s then
return nil
end
for _, name in { ... } do
local fld = s.byName[name]
if fld then
return fld
end
end
return nil
end
function Blend.blocks(f: File, code: string): { Block }
return f.byCode[code] or {}
end
local function pointerKey(f: File, o: number): any
local b = f.buf
if f.pointerSize == 8 then
if readu32(b, o) == 0 and readu32(b, o + 4) == 0 then
return nil
end
return readstring(b, o, 8)
end
local v = f.u32(b, o)
return if v == 0 then nil else v
end
Blend.pointerKey = pointerKey
-- addresses are unique among live allocations only: a DATA block is looked up among the blocks of the ID the
-- pointer comes from first (from = the block holding the pointer), as Blender's reader does
function Blend.resolve(f: File, addr: any, from: Block?): Block?
if addr == nil then
return nil
end
local list = f.shared[addr]
if list and from then
for _, b in list do
if b.owner == from.owner then
return b
end
end
end
return f.byAddr[addr]
end
local function find(self: View, names: { any }): Field?
local by = self.struct.byName
for _, name in names do
local fld = by[name]
if fld then
return fld
end
end
return nil
end
function View.has(self: View, ...: string): boolean
return find(self, { ... }) ~= nil
end
local function scalar(f: File, t: string, size: number, o: number): number
local b = f.buf
if t == "float" then
return f.f32(b, o)
elseif t == "double" then
return f.f64(b, o)
elseif t == "int" or t == "int32_t" or t == "long" then
return if size == 8 then f.u32(b, o + (if f.little then 0 else 4)) else f.i32(b, o)
elseif t == "short" or t == "int16_t" then
return f.i16(b, o)
elseif t == "ushort" or t == "uint16_t" then
return f.u16(b, o)
elseif t == "uint" or t == "uint32_t" or t == "ulong" then
return f.u32(b, o)
elseif t == "int8_t" then
return readi8(b, o)
elseif t == "int64_t" or t == "uint64_t" then
local lo, hi = f.u32(b, o + (if f.little then 0 else 4)), f.u32(b, o + (if f.little then 4 else 0))
if t == "int64_t" and hi >= 2147483648 then
return (hi - 4294967296) * 4294967296 + lo
end
return hi * 4294967296 + lo
end
return readu8(b, o) -- char, uchar, uint8_t, bool
end
function View.get(self: View, ...: string): any
local fld = find(self, { ... })
if not fld then
return nil
end
local f = self.file
local o = self.offset + fld.offset
if o + fld.size > buffer.len(f.buf) then
return nil
end
if fld.pointer then
if fld.count > 1 then
local out = table.create(fld.count)
for k = 0, fld.count - 1 do
out[k + 1] = pointerKey(f, o + k * f.pointerSize) or false
end
return out
end
return pointerKey(f, o)
end
local t = fld.type
if PRIM[t] then
if fld.count == 1 then
return scalar(f, t, fld.elem, o)
end
if t == "char" then
local s = readstring(f.buf, o, fld.size)
local z = string.find(s, "\0", 1, true)
return if z then string.sub(s, 1, z - 1) else s
end
local out = table.create(fld.count)
for k = 0, fld.count - 1 do
out[k + 1] = scalar(f, t, fld.elem, o + k * fld.elem)
end
return out
end
local s = f.dna.byName[t]
if not s then
return nil
end
if fld.count > 1 then
local out = table.create(fld.count)
for k = 0, fld.count - 1 do
out[k + 1] = view(f, s, o + k * s.size, self.block)
end
return out
end
return view(f, s, o, self.block)
end
function View.num(self: View, ...: string): number?
local v = self:get(...)
return if type(v) == "number" then v else nil
end
function View.str(self: View, ...: string): string?
local v = self:get(...)
return if type(v) == "string" then v else nil
end
function View.vec(self: View, ...: string): { number }?
local v = self:get(...)
return if type(v) == "table" and type(v[1]) == "number" then v else nil
end
function View.sub(self: View, ...: string): View?
local v = self:get(...)
return if type(v) == "table" and getmetatable(v) == View then v else nil
end
function View.ptr(self: View, ...: string): any
local fld = find(self, { ... })
if not fld or not fld.pointer or self.offset + fld.offset + self.file.pointerSize > buffer.len(self.file.buf) then
return nil
end
return pointerKey(self.file, self.offset + fld.offset)
end
function View.target(self: View, ...: string): Block?
return Blend.resolve(self.file, self:ptr(...), self.block)
end
function View.deref(self: View, name: string | { string }, i: number?, as: string?): View?
local names: { any } = if type(name) == "table" then name else { name }
local fld = find(self, names)
if not fld or not fld.pointer then
return nil
end
local blk = self:target(fld.name)
if not blk then
return nil
end
local f = self.file
local sname = as or fld.type
if not as and (sname == "void" or not f.dna.byName[sname]) then
local own = f.dna.structs[blk.sdna + 1]
sname = if own then own.name else sname
end
return Blend.struct(f, blk, i, sname)
end
function View.array(self: View, name: string | { string }, as: string?): { View }
local first = self:deref(name, 0, as)
if not first or not first.block then
return {}
end
local blk = first.block :: Block
local s = first.struct
local n = if s.size > 0 then blk.size // s.size else 0
local out = table.create(n) :: { View }
for k = 0, n - 1 do
out[k + 1] = view(self.file, s, blk.offset + k * s.size, blk)
end
return out
end
function View.pointers(self: View, name: string | { string }, n: number?): { any }
local names: { any } = if type(name) == "table" then name else { name }
local fld = find(self, names)
if not fld or not fld.pointer then
return {}
end
local blk = self:target(fld.name)
if not blk then
return {}
end
local f = self.file
local ps = f.pointerSize
local count = blk.size // ps
if n then
count = math.min(count, n)
end
local out = table.create(count)
for k = 0, count - 1 do
out[k + 1] = pointerKey(f, blk.offset + k * ps) or false
end
return out
end
function View.list(self: View, name: string | { string }, as: string?, limit: number?): { View }
local names: { any } = if type(name) == "table" then name else { name }
local lb = self:sub(table.unpack(names))
local out = {}
if not lb then
return out
end
local f = self.file
local addr = lb:ptr("first")
local seen = {}
local max = limit or 2 ^ 20
while addr ~= nil and not seen[addr] and #out < max do
seen[addr] = true
local blk = Blend.resolve(f, addr, self.block)
if not blk then
break
end
local v = Blend.struct(f, blk, 0, as)
if not v then
break
end
table.insert(out, v)
addr = v:ptr("next")
if addr == nil and not v.struct.byName.next then
-- structs that start with an embedded header (ModifierData, ...) keep the link there
local head = v.struct.fields[1]
local sub = head and not head.pointer and f.dna.byName[head.type]
if sub then
addr = view(f, sub, v.offset + head.offset, v.block):ptr("next")
end
end
end
return out
end
function View.data(self: View, ...: string): (number?, number)
local blk = self:target(...)
if not blk then
return nil, 0
end
return blk.offset, blk.size
end
function View.cstring(self: View, ...: string): string?
local blk = self:target(...)
if not blk then
return nil
end
local s = readstring(self.file.buf, blk.offset, blk.size)
local z = string.find(s, "\0", 1, true)
return if z then string.sub(s, 1, z - 1) else s
end
function View.idName(self: View): string?
local id = self:sub("id")
local n = if id then id:str("name") else self:str("name")
if not n then
return nil
end
return string.sub(n, 3)
end
return Blend
+344
View File
@@ -0,0 +1,344 @@
--!strict
-- model/blend/Anim: Blender actions (legacy bAction.curves, and the layered actions of 4.4+: layers -> strips ->
-- keyframe data -> channel bags matched by the AnimData slot handle) and f-curve evaluation: constant, linear,
-- bezier (handles shortened so the segment stays a function of time, as Blender does) and the Penner easing modes
-- (elastic uses Penner's amplitude / period, which Blender scales differently);
-- constant or linear extrapolation. F-curve modifiers and NLA strips are not evaluated.
local Blend = require("@rosetta/containers/Blend")
local Anim = {}
export type Key = {
x: number,
y: number,
lx: number, -- left handle
ly: number,
rx: number, -- right handle
ry: number,
ipo: number, -- 0 constant, 1 linear, 2 bezier, 3.. easing (back, bounce, circ, cubic, elastic, expo, quad, quart, quint, sine)
easing: number, -- 0 auto, 1 in, 2 out, 3 in-out
back: number,
amplitude: number,
period: number,
}
export type Curve = { path: string, index: number, keys: { Key }, extend: number, modifiers: number }
local CONST, LIN, BEZ = 0, 1, 2
local BACK, BOUNCE, CIRC, CUBIC, ELASTIC, EXPO, QUAD, QUART, QUINT, SINE = 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
-- ------------------------------------------------------------------------------------------------ reading
local function curve(f: Blend.File, fc: Blend.View): Curve?
local path = fc:cstring("rna_path")
if not path then
return nil
end
local keys: { Key } = {}
for _, b in fc:array("bezt", "BezTriple") do
local v = b:vec("vec")
if v and #v >= 9 then
table.insert(keys, {
lx = v[1], ly = v[2], x = v[4], y = v[5], rx = v[7], ry = v[8],
ipo = b:num("ipo") or BEZ, easing = b:num("easing") or 0, back = b:num("back") or 1.70158,
amplitude = b:num("amplitude") or 0.8, period = b:num("period") or 4.1,
})
end
end
if #keys == 0 then
for _, p in fc:array("fpt", "FPoint") do
local v = p:vec("vec")
if v and #v >= 2 then
table.insert(keys, { x = v[1], y = v[2], lx = v[1], ly = v[2], rx = v[1], ry = v[2], ipo = LIN, easing = 0, back = 0, amplitude = 0, period = 0 })
end
end
end
if #keys == 0 then
return nil
end
table.sort(keys, function(a: Key, b: Key): boolean
return a.x < b.x
end)
local mods = fc:list("modifiers")
return { path = path, index = fc:num("array_index") or 0, keys = keys, extend = fc:num("extend") or 0, modifiers = #mods }
end
function Anim.curves(f: Blend.File, adt: Blend.View?): ({ Curve }?, string?)
if not adt then
return nil, nil
end
local act = adt:deref("action", 0, "bAction")
if not act then
return nil, nil
end
local list: { Blend.View } = act:list("curves", "FCurve")
if #list == 0 and act:has("layer_array") then
local handle = adt:num("slot_handle") or 0
local datas = act:pointers("strip_keyframe_data_array", act:num("strip_keyframe_data_array_num"))
for _, la in act:pointers("layer_array", act:num("layer_array_num")) do
local lblk = la and Blend.resolve(f, la, act.block)
local layer = lblk and Blend.struct(f, lblk, 0, "ActionLayer")
if layer then
for _, sa in layer:pointers("strip_array", layer:num("strip_array_num")) do
local sblk = sa and Blend.resolve(f, sa, act.block)
local strip = sblk and Blend.struct(f, sblk, 0, "ActionStrip")
local di = strip and strip:num("data_index")
local dblk = di and datas[di + 1] and Blend.resolve(f, datas[di + 1], act.block)
local kd = dblk and Blend.struct(f, dblk, 0, "ActionStripKeyframeData")
if kd then
for _, ba in kd:pointers("channelbag_array", kd:num("channelbag_array_num")) do
local bblk = ba and Blend.resolve(f, ba, act.block)
local bag = bblk and (Blend.struct(f, bblk, 0, "ActionChannelBag") or Blend.struct(f, bblk, 0, "ActionChannelbag"))
if bag and (bag:num("slot_handle") or 0) == handle then
for _, ca in bag:pointers("fcurve_array", bag:num("fcurve_array_num")) do
local cblk = ca and Blend.resolve(f, ca, act.block)
local fc = cblk and Blend.struct(f, cblk, 0, "FCurve")
if fc then
table.insert(list, fc)
end
end
end
end
end
end
end
end
end
local out: { Curve } = {}
for _, fc in list do
local c = curve(f, fc)
if c then
table.insert(out, c)
end
end
return out, act:idName()
end
-- pre-2.5 IPO curves (Object.ipo / Key.ipo): the curve's adrcode picks the channel; object rotations are in units of
-- 10 degrees; the interpolation and extrapolation (0 constant, 1 linear; cyclic ones as constant) are per curve
local OB_ADR: { [number]: { any } } = {
[1] = { "location", 0 }, [2] = { "location", 1 }, [3] = { "location", 2 },
[4] = { "delta_location", 0 }, [5] = { "delta_location", 1 }, [6] = { "delta_location", 2 },
[7] = { "rotation_euler", 0, math.pi / 18 }, [8] = { "rotation_euler", 1, math.pi / 18 }, [9] = { "rotation_euler", 2, math.pi / 18 },
[10] = { "delta_rotation_euler", 0, math.pi / 18 }, [11] = { "delta_rotation_euler", 1, math.pi / 18 }, [12] = { "delta_rotation_euler", 2, math.pi / 18 },
[13] = { "scale", 0 }, [14] = { "scale", 1 }, [15] = { "scale", 2 },
}
function Anim.ipo(f: Blend.File, ipo: Blend.View?, keyNames: { string }?): ({ Curve }?, string?)
if not ipo then
return nil, nil
end
local out: { Curve } = {}
for _, icu in ipo:list("curve", "IpoCurve") do
local adr = icu:num("adrcode") or -1
local path, index, scale
if keyNames then
if adr >= 1 and keyNames[adr + 1] then
path, index, scale = 'key_blocks["' .. keyNames[adr + 1] .. '"].value', 0, 1
end
else
local m = OB_ADR[adr]
if m then
path, index, scale = m[1], m[2], m[3] or 1
end
end
if path then
local ipoMode = icu:num("ipo") or BEZ
local keys: { Key } = {}
for _, b in icu:array("bezt", "BezTriple") do
local v = b:vec("vec")
if v and #v >= 9 then
table.insert(keys, {
lx = v[1], ly = v[2] * scale, x = v[4], y = v[5] * scale, rx = v[7], ry = v[8] * scale,
ipo = if ipoMode == CONST or ipoMode == LIN then ipoMode else BEZ, easing = 0, back = 1.70158, amplitude = 0.8, period = 4.1,
})
end
end
local n = math.min(#keys, icu:num("totvert") or #keys)
while #keys > n do
table.remove(keys)
end
if #keys > 0 then
table.sort(keys, function(a: Key, b: Key): boolean
return a.x < b.x
end)
table.insert(out, { path = path, index = index, keys = keys, extend = if (icu:num("extrap") or 0) == 1 then 1 else 0, modifiers = 0 })
end
end
end
local _ = f
return out, ipo:idName()
end
-- ------------------------------------------------------------------------------------------------ evaluation
local function bezierAt(p0: number, p1: number, p2: number, p3: number, t: number): number
local u = 1 - t
return u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3
end
local function bezier(a: Key, b: Key, x: number): number
local x0, y0, x3, y3 = a.x, a.y, b.x, b.y
local x1, y1, x2, y2 = a.rx, a.ry, b.lx, b.ly
-- handles longer than the segment are scaled down together so x(t) stays monotonic
local len = x3 - x0
local h1x, h1y = x1 - x0, y1 - y0
local h2x, h2y = x2 - x3, y2 - y3
local l1, l2 = math.abs(h1x), math.abs(h2x)
if l1 + l2 > len and l1 + l2 > 0 then
local fac = len / (l1 + l2)
x1, y1 = x0 + h1x * fac, y0 + h1y * fac
x2, y2 = x3 + h2x * fac, y3 + h2y * fac
end
local lo, hi = 0, 1
local t = (x - x0) / len
for _ = 1, 60 do
local xt = bezierAt(x0, x1, x2, x3, t)
if math.abs(xt - x) < 1e-9 then
break
end
if xt < x then
lo = t
else
hi = t
end
local d = 3 * (1 - t) * (1 - t) * (x1 - x0) + 6 * (1 - t) * t * (x2 - x1) + 3 * t * t * (x3 - x2)
local nt = if d ~= 0 then t - (xt - x) / d else -1
t = if nt > lo and nt < hi then nt else (lo + hi) / 2
end
return bezierAt(y0, y1, y2, y3, t)
end
local function bounceOut(t: number, b: number, c: number, d: number): number
t /= d
if t < 1 / 2.75 then
return c * (7.5625 * t * t) + b
elseif t < 2 / 2.75 then
t -= 1.5 / 2.75
return c * (7.5625 * t * t + 0.75) + b
elseif t < 2.5 / 2.75 then
t -= 2.25 / 2.75
return c * (7.5625 * t * t + 0.9375) + b
end
t -= 2.625 / 2.75
return c * (7.5625 * t * t + 0.984375) + b
end
local function easeIn(ipo: number, t: number, a: Key): number -- 0..1 -> 0..1
if ipo == BACK then
local s = a.back
return t * t * ((s + 1) * t - s)
elseif ipo == BOUNCE then
return 1 - bounceOut(1 - t, 0, 1, 1)
elseif ipo == CIRC then
return 1 - math.sqrt(math.max(0, 1 - t * t))
elseif ipo == CUBIC then
return t * t * t
elseif ipo == ELASTIC then
if t <= 0 or t >= 1 then
return t
end
local p = if a.period > 0 then a.period / 10 else 0.3
local amp = a.amplitude
local s
if amp < 1 then
amp, s = 1, p / 4
else
s = p / (2 * math.pi) * math.asin(1 / amp)
end
t -= 1
return -(amp * 2 ^ (10 * t) * math.sin((t - s) * (2 * math.pi) / p))
elseif ipo == EXPO then
return (2 ^ (10 * (t - 1)) - 2 ^ -10) / (1 - 2 ^ -10) -- normalized to run from 0 to 1, as Blender's does
elseif ipo == QUAD then
return t * t
elseif ipo == QUART then
return t * t * t * t
elseif ipo == QUINT then
return t * t * t * t * t
elseif ipo == SINE then
return 1 - math.cos(t * math.pi / 2)
end
return t
end
local function ease(a: Key, b: Key, x: number): number
local t = (x - a.x) / (b.x - a.x)
local mode = a.easing
if mode == 0 then
mode = if a.ipo == BACK or a.ipo == BOUNCE or a.ipo == ELASTIC then 2 else 1
end
local s
if mode == 1 then
s = easeIn(a.ipo, t, a)
elseif mode == 2 then
s = 1 - easeIn(a.ipo, 1 - t, a)
elseif t < 0.5 then
s = easeIn(a.ipo, t * 2, a) / 2
else
s = 1 - easeIn(a.ipo, (1 - t) * 2, a) / 2
end
return a.y + (b.y - a.y) * s
end
function Anim.evaluate(c: Curve, x: number): number
local keys = c.keys
local n = #keys
local first, last = keys[1], keys[n]
if x <= first.x then
if c.extend == 1 and n > 0 and first.ipo ~= CONST then
if first.ipo == BEZ and first.lx ~= first.x then
return first.y + (x - first.x) * (first.y - first.ly) / (first.x - first.lx)
elseif n > 1 and keys[2].x ~= first.x then
return first.y + (x - first.x) * (keys[2].y - first.y) / (keys[2].x - first.x)
end
end
return first.y
end
if x >= last.x then
local prev = keys[n - 1]
if c.extend == 1 and n > 1 and prev.ipo ~= CONST then
if last.ipo == BEZ and last.rx ~= last.x then
return last.y + (x - last.x) * (last.ry - last.y) / (last.rx - last.x)
elseif last.x ~= prev.x then
return last.y + (x - last.x) * (last.y - prev.y) / (last.x - prev.x)
end
end
return last.y
end
local lo, hi = 1, n
while hi - lo > 1 do
local mid = (lo + hi) // 2
if keys[mid].x <= x then
lo = mid
else
hi = mid
end
end
local a, b = keys[lo], keys[hi]
if b.x <= a.x or a.ipo == CONST then
return a.y
elseif a.ipo == LIN then
return a.y + (b.y - a.y) * (x - a.x) / (b.x - a.x)
elseif a.ipo == BEZ then
return bezier(a, b, x)
end
return ease(a, b, x)
end
function Anim.range(curves: { Curve }): (number, number)
local lo, hi = math.huge, -math.huge
for _, c in curves do
lo = math.min(lo, c.keys[1].x)
hi = math.max(hi, c.keys[#c.keys].x)
end
return lo, hi
end
function Anim.split(path: string): (string?, string?, string)
local kind, name, rest = string.match(path, '^(%w[%w_%.]-)%["(.-)"%]%.([%w_]+)$')
if kind and name and rest then
name = string.gsub(name, '\\(.)', "%1")
return kind, name, rest
end
return nil, nil, path
end
return Anim
+350
View File
@@ -0,0 +1,350 @@
--!strict
-- model/blend/Material: Blender materials to Scene PBR materials. With nodes: the Principled BSDF (the one feeding the
-- material output, else the first): Base Color, Metallic, Roughness, Alpha, Emission (Color) x Emission Strength
-- (KHR_materials_emissive_strength above 1, as Blender's glTF exporter writes it), images linked directly to Base
-- Color / Emission and through a Normal Map node to Normal (its Strength as the scale), a Separate RGB / Color node to
-- Roughness (G) and Metallic (B), UV Map nodes for the texCoord. Without nodes (or before 2.8 without a
-- Principled node): Material.r / g / b / alpha, metallic, roughness. Images: packed files as encoded bytes, external
-- ones as uris (with the bytes when opts.files / opts.resolve has them).
local Blend = require("@rosetta/containers/Blend")
local Types = require("@rosetta/Types")
local Material = {}
type Ctx = { f: Blend.File, scene: Types.Scene, materials: { [any]: number }, textures: { [any]: number }, opts: any, meta: any }
local readu8, readstring = buffer.readu8, buffer.readstring
local function sniffMime(b: buffer, o: number, n: number, path: string?): string?
if n >= 8 and readstring(b, o, 8) == "\137PNG\r\n\26\n" then
return "image/png"
elseif n >= 3 and readu8(b, o) == 0xFF and readu8(b, o + 1) == 0xD8 then
return "image/jpeg"
elseif n >= 12 and readstring(b, o, 4) == "RIFF" and readstring(b, o + 8, 4) == "WEBP" then
return "image/webp"
elseif n >= 2 and readstring(b, o, 2) == "BM" then
return "image/bmp"
elseif n >= 4 and readstring(b, o, 4) == "\118\47\49\1" then
return "image/x-exr"
end
local ext = path and string.lower(string.match(path, "%.(%w+)$") or "")
local byExt = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", exr = "image/x-exr", hdr = "image/vnd.radiance", webp = "image/webp", tif = "image/tiff", tiff = "image/tiff" }
return if ext then byExt[ext] else nil
end
local function fetch(ctx: Ctx, uri: string): buffer?
local opts = ctx.opts
local v: any = nil
if type(opts.files) == "table" then
v = opts.files[uri]
if v == nil then
v = opts.files[string.match(uri, "[^/\\]+$") or uri]
end
end
if v == nil and type(opts.resolve) == "function" then
local ok, res = pcall(opts.resolve, uri)
v = if ok then res else nil
end
if type(v) == "string" then
return buffer.fromstring(v)
end
return if type(v) == "buffer" then v else nil
end
local function texture(ctx: Ctx, img: Blend.View, sampler: Types.Sampler?): number?
local f = ctx.f
local key = img.block and img.block.addr
if key ~= nil and ctx.textures[key] then
return ctx.textures[key]
end
local name = img:idName()
-- the path field keeps its DNA name "name" (char[1024]) in every version
local pf0 = img.struct.byName.filepath or img.struct.byName.name
local path = if pf0 and pf0.size >= 256 then img:str(pf0.name) else nil
local pf = img:deref("packedfile", 0, "PackedFile")
if not pf then
for _, ipf in img:list("packedfiles", "ImagePackedFile") do
pf = ipf:deref("packedfile", 0, "PackedFile")
if pf then
break
end
end
end
local tex: Types.Texture = { name = name, sampler = sampler }
if pf then
local blk = pf:target("data")
local size = pf:num("size") or 0
if blk then
local n = math.min(size, blk.size)
local data = buffer.create(n)
buffer.copy(data, 0, f.buf, blk.offset, n)
tex.data = data
tex.mime = sniffMime(data, 0, n, path)
end
end
if path and path ~= "" then
local uri = string.gsub(path, "^//", "")
uri = string.gsub(uri, "\\", "/")
if not tex.data then
tex.uri = uri
local data = fetch(ctx, uri)
if data then
tex.data = data
tex.mime = sniffMime(data, 0, buffer.len(data), uri)
else
tex.mime = sniffMime(buffer.create(0), 0, 0, uri)
end
end
tex.extras = { blend = { filepath = path } }
end
if not tex.data and not tex.uri then
tex.extras = { blend = { generated = true } }
end
table.insert(ctx.scene.textures, tex)
local idx = #ctx.scene.textures
if key ~= nil then
ctx.textures[key] = idx
end
return idx
end
type Node = { view: Blend.View, idname: string, inputs: { [string]: Blend.View }, outputs: { [any]: string } }
type Graph = { nodes: { [any]: Node }, links: { [any]: { node: Node, socket: string } } } -- links by tosock addr
local function graph(tree: Blend.View): Graph
local g: Graph = { nodes = {}, links = {} }
for _, n in tree:list("nodes", "bNode") do
local node: Node = { view = n, idname = n:str("idname") or "", inputs = {}, outputs = {} }
for _, s in n:list("inputs", "bNodeSocket") do
local id = s:str("identifier") or s:str("name") or ""
local nm = s:str("name") or id
node.inputs[nm] = s
if node.inputs[id] == nil then
node.inputs[id] = s
end
end
for _, s in n:list("outputs", "bNodeSocket") do
if s.block then
node.outputs[s.block.addr] = s:str("name") or ""
end
end
if n.block then
g.nodes[n.block.addr] = node
end
end
for _, l in tree:list("links", "bNodeLink") do
local from, fs, to = l:ptr("fromnode"), l:ptr("fromsock"), l:ptr("tosock")
local fn = from and g.nodes[from]
if fn and to ~= nil and bit32.band(l:num("flag") or 0, 0x10) == 0 then
g.links[to] = { node = fn, socket = (fs and fn.outputs[fs]) or "" }
end
end
return g
end
local function input(n: Node, ...: string): Blend.View?
for _, k in { ... } do
local s = n.inputs[k]
if s then
return s
end
end
return nil
end
local function link(g: Graph, s: Blend.View?): { node: Node, socket: string }?
if not s or not s.block then
return nil
end
return g.links[s.block.addr]
end
local function value(s: Blend.View?, kind: string): any
if not s then
return nil
end
if kind == "rgba" then
local v = s:deref("default_value", 0, "bNodeSocketValueRGBA")
return v and v:vec("value")
end
local v = s:deref("default_value", 0, "bNodeSocketValueFloat")
return v and v:num("value")
end
local function imageRef(ctx: Ctx, g: Graph, uvNames: any, s: Blend.View?, through: string?): (Types.TextureRef?, Node?)
local l = link(g, s)
if not l then
return nil, nil
end
local n = l.node
if through and n.idname == through then
local inner = input(n, "Color", "Image")
local ref, tn = imageRef(ctx, g, uvNames, inner, nil)
return ref, if ref then n else tn
end
if n.idname ~= "ShaderNodeTexImage" then
return nil, n
end
local img = n.view:deref("id", 0, "Image")
if not img then
return nil, n
end
local sampler: Types.Sampler = {}
local custom = false
local st = n.view:deref("storage", 0, "NodeTexImage")
if st then
local interp, ext = st:num("interpolation") or 0, st:num("extension") or 0
custom = interp == 1 or (ext >= 1 and ext <= 3)
if interp == 1 then
sampler.filter = "nearest"
sampler.minFilter = "nearest"
end
if ext == 1 or ext == 2 then
sampler.wrapS, sampler.wrapT = "clamp", "clamp"
elseif ext == 3 then
sampler.wrapS, sampler.wrapT = "mirror", "mirror"
end
end
local t = texture(ctx, img, if custom then sampler else nil)
if not t then
return nil, n
end
local ref: Types.TextureRef = { texture = t }
local vec = link(g, input(n, "Vector"))
if vec and vec.node.idname == "ShaderNodeUVMap" then
local uvs = vec.node.view:deref("storage", 0, "NodeShaderUVMap")
local name = uvs and uvs:str("uv_map")
if name and uvNames and uvNames[name] then
ref.texCoord = uvNames[name]
end
end
return ref, n
end
local function principled(g: Graph): Node?
local first: Node? = nil
for _, n in g.nodes do
if n.idname == "ShaderNodeOutputMaterial" then
local l = link(g, n.inputs.Surface)
if l and l.node.idname == "ShaderNodeBsdfPrincipled" then
return l.node
end
elseif n.idname == "ShaderNodeBsdfPrincipled" and (first == nil or (n.view.block and first.view.block and n.view.block.index < first.view.block.index)) then
first = n
end
end
return first
end
local function emissive(m: Types.Material, color: { number }, strength: number)
local e = { color[1] * strength, color[2] * strength, color[3] * strength }
local mx = math.max(e[1], e[2], e[3])
if mx > 1 then
m.extensions = m.extensions or {}
;(m.extensions :: any).KHR_materials_emissive_strength = { emissiveStrength = mx }
e = { e[1] / mx, e[2] / mx, e[3] / mx }
end
m.emissive = e
end
function Material.get(ctx: Ctx, mv: Blend.View): number
local key = mv.block and mv.block.addr
if key ~= nil and ctx.materials[key] then
return ctx.materials[key]
end
local f = ctx.f
local m = Types.Scene.material(mv:idName())
local extras: { [string]: any } = {}
m.extras = { blend = extras }
local legacyAlpha = mv:num("a", "alpha") or 1
m.baseColor = { mv:num("r") or 0.8, mv:num("g") or 0.8, mv:num("b") or 0.8, legacyAlpha }
m.metallic = mv:num("metallic") or 0
m.roughness = mv:num("roughness") or 0.5
if f.version < 280 then
m.roughness = 0.5
end
m.doubleSided = bit32.band(mv:num("blend_flag") or 0, 4) == 0
local tree = mv:deref("nodetree", 0, "bNodeTree")
local useNodes = (mv:num("use_nodes") or 0) ~= 0 or f.version >= 500
local bsdf = nil
local g: Graph? = nil
if tree and useNodes then
g = graph(tree)
bsdf = principled(g :: Graph)
end
if bsdf and g then
extras.principled = true
local uvNames = ctx.meta.uvNames
local base = value(input(bsdf, "Base Color"), "rgba")
local alpha = value(input(bsdf, "Alpha"), "float") or 1
if base then
m.baseColor = { base[1], base[2], base[3], alpha }
end
m.metallic = value(input(bsdf, "Metallic"), "float") or m.metallic
m.roughness = value(input(bsdf, "Roughness"), "float") or m.roughness
local bref = imageRef(ctx, g, uvNames, input(bsdf, "Base Color"), nil)
if bref then
m.baseColorTexture = bref
m.baseColor = { 1, 1, 1, alpha }
end
local aref = imageRef(ctx, g, uvNames, input(bsdf, "Alpha"), nil)
if aref and not m.baseColorTexture then
m.baseColorTexture = aref
end
local nref, nnode = imageRef(ctx, g, uvNames, input(bsdf, "Normal"), "ShaderNodeNormalMap")
if nref then
nref.scale = if nnode then value(nnode.inputs.Strength, "float") or 1 else 1
m.normalTexture = nref
end
local rl = link(g, input(bsdf, "Roughness"))
local ml = link(g, input(bsdf, "Metallic"))
local sep = (rl and rl.node) or (ml and ml.node)
if sep and (sep.idname == "ShaderNodeSeparateRGB" or sep.idname == "ShaderNodeSeparateColor") then
local mref = imageRef(ctx, g, uvNames, input(sep, "Image", "Color"), nil)
if mref then
m.metallicRoughnessTexture = mref
if rl then
m.roughness = 1
end
if ml then
m.metallic = 1
end
end
end
local es = input(bsdf, "Emission Color", "Emission")
local ecol = value(es, "rgba") or { 0, 0, 0, 1 }
local strength = value(input(bsdf, "Emission Strength"), "float") or 1
local eref = imageRef(ctx, g, uvNames, es, nil)
if eref then
m.emissiveTexture = eref
ecol = { 1, 1, 1, 1 }
end
emissive(m, ecol, strength)
if not eref and m.emissive[1] == 0 and m.emissive[2] == 0 and m.emissive[3] == 0 then
m.emissive = { 0, 0, 0 }
end
local alphaLinked = link(g, input(bsdf, "Alpha")) ~= nil
if alpha < 1 or alphaLinked then
local bm = mv:num("blend_method") or 0
if bm == 3 then
m.alphaMode = "mask"
m.alphaCutoff = mv:num("alpha_threshold") or 0.5
else
m.alphaMode = "blend"
end
end
else
extras.legacy = true
if legacyAlpha < 1 then
m.alphaMode = "blend"
end
end
table.insert(ctx.scene.materials, m)
local idx = #ctx.scene.materials
if key ~= nil then
ctx.materials[key] = idx
end
return idx
end
return Material
+633
View File
@@ -0,0 +1,633 @@
--!strict
-- model/blend/Mesh: a Blender Mesh ID of any storage generation to one polygon form (positions, faces as corner lists,
-- corner / point attributes, deform weights). Generations: MFace tessellated faces (< 2.63, and the 2.7x "legacy mesh
-- format" save); MVert / MEdge / MPoly / MLoop with MLoopUV / MLoopCol layers (2.63 - 3.x); CustomData attribute
-- layers ("position", ".edge_verts", ".corner_vert", poly_offset_indices, 3.x - 4.x); AttributeStorage (5.x).
local Blend = require("@rosetta/containers/Blend")
local Mesh = {}
export type Layer = {
name: string,
domain: string, -- "point" | "edge" | "face" | "corner" | "tess"
kind: string, -- a generic kind (float, float2, float3, color, bytecolor, int32, int2, int8, bool, short2, quat,
-- float4x4) or an SDNA struct name (MVert, MEdge, MPoly, MLoop, MFace, MTFace, MCol, MLoopUV, MDeformVert)
offset: number, -- data start in file.buf
bytes: number, -- data bytes available
elem: number, -- bytes per element
single: boolean?, -- one value for every element (AttributeStorage single storage)
activeRender: boolean?,
cdtype: number?,
}
export type Color = { name: string, domain: string, data: buffer } -- f32 x 4 (linear) per point or corner
export type Poly = {
name: string?,
nv: number,
nf: number,
nc: number,
pos: buffer, -- f32 x 3 per vertex
cornerVert: buffer, -- u32 per corner
faceStart: buffer, -- u32 per face + 1
faceMat: buffer, -- i32 per face
faceSmooth: buffer, -- u8 per face
uvs: { { name: string, data: buffer } }, -- f32 x 2 per corner
activeUV: number, -- 1-based index into uvs (the active render layer)
colors: { Color },
customNormals: buffer?, -- f32 x 3 per corner (free custom normals)
encodedNormals: buffer?, -- i16 x 2 per corner (custom normals in Blender's corner-fan space)
sharp: { [number]: boolean }, -- edge keys (min * nv + max) that split smooth fans
autoSmooth: number?, -- radians (Mesh.smoothresh with ME_AUTOSMOOTH, before 4.1)
weights: { { number } }?, -- per vertex: def_nr, weight, def_nr, weight, ...
generation: string, -- "mface" | "mpoly" | "attributes" | "storage"
layers: { Layer },
}
local CD_KIND: { [number]: string } = {
[0] = "MVert", [2] = "MDeformVert", [3] = "MEdge", [4] = "MFace", [5] = "MTFace", [6] = "MCol", [10] = "float",
[11] = "int32", [16] = "MLoopUV", [17] = "bytecolor", [25] = "MPoly", [26] = "MLoop", [41] = "short2", [45] = "int8",
[46] = "int2", [47] = "color", [48] = "float3", [49] = "float2", [50] = "bool", [52] = "quat",
}
-- AttributeStorage (5.x) data types and domains
local ATTR_KIND: { [number]: string } = {
[0] = "bool", [1] = "int8", [2] = "short2", [3] = "int32", [4] = "int2", [5] = "float", [6] = "float2", [7] = "float3",
[8] = "float4x4", [9] = "bytecolor", [10] = "color", [11] = "quat",
}
local DOMAIN: { [number]: string } = { [0] = "point", [1] = "edge", [2] = "face", [3] = "corner" }
local SIZE: { [string]: number } = {
bool = 1, int8 = 1, short2 = 4, int32 = 4, int2 = 8, float = 4, float2 = 8, float3 = 12, float4x4 = 64, bytecolor = 4,
color = 16, quat = 16,
}
local ME_SMOOTH = 1
local ME_SHARP = 0x200
local ME_AUTOSMOOTH = 0x20
local readu8, readi16 = buffer.readu8, buffer.readi16
-- sRGB byte -> linear
local SRGB = table.create(256, 0)
for i = 0, 255 do
local c = i / 255
SRGB[i + 1] = if c <= 0.04045 then c / 12.92 else ((c + 0.055) / 1.055) ^ 2.4
end
Mesh.SRGB = SRGB
local function customData(f: Blend.File, me: Blend.View, names: { string }, domain: string, out: { Layer })
local cd = me:sub(table.unpack(names))
if not cd then
return
end
local layers = cd:array("layers", "CustomDataLayer")
local n = cd:num("totlayer") or #layers
for i = 1, math.min(n, #layers) do
local L = layers[i]
local t = L:num("type") or -1
local kind = CD_KIND[t]
local blk = L:target("data")
if kind and blk then
local st = f.dna.byName[kind]
local elem = if st then st.size else SIZE[kind] or 0
if elem > 0 then
table.insert(out, {
name = L:str("name") or "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size,
elem = elem, activeRender = (L:num("active_rnd") or 0) == 0, cdtype = t,
})
end
end
end
end
local function storage(f: Blend.File, me: Blend.View, out: { Layer })
local st = me:sub("attribute_storage")
if not st then
return
end
local attrs = st:array("dna_attributes", "Attribute")
local n = st:num("dna_attributes_num") or #attrs
for i = 1, math.min(n, #attrs) do
local a = attrs[i]
local kind = ATTR_KIND[a:num("data_type") or -1]
local domain = DOMAIN[a:num("domain") or -1]
local single = (a:num("storage_type") or 0) == 1
local holder = a:deref("data", 0, if single then "AttributeSingle" else "AttributeArray")
local blk = holder and holder:target("data")
if kind and domain and blk then
table.insert(out, {
name = a:cstring("name") or "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size,
elem = SIZE[kind], single = single,
})
end
end
end
local function find(layers: { Layer }, domain: string, kind: string?, name: string?): Layer?
for _, L in layers do
if L.domain == domain and (kind == nil or L.kind == kind) and (name == nil or L.name == name) then
return L
end
end
return nil
end
local function legacy(f: Blend.File, me: Blend.View, field: string, kind: string, domain: string): Layer?
local blk = me:target(field)
local st = f.dna.byName[kind]
if not blk or not st or st.size <= 0 then
return nil
end
return { name = "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, elem = st.size }
end
local function reader(f: Blend.File, L: Layer): (number, number) -> number
local b = f.buf
local o, elem, k = L.offset, L.elem, L.kind
local max = L.bytes
local single = L.single
local f32, i32, i16 = f.f32, f.i32, f.i16
local comp = if k == "short2" then 2 elseif k == "int8" or k == "bool" or k == "bytecolor" then 1 else 4
return function(i: number, c: number): number
local at = (if single then 0 else i * elem) + c * comp
if at < 0 or at + comp > max then
return 0
end
if k == "float" or k == "float2" or k == "float3" or k == "color" or k == "quat" or k == "float4x4" then
return f32(b, o + at)
elseif k == "int32" or k == "int2" then
return i32(b, o + at)
elseif k == "short2" then
return i16(b, o + at)
elseif k == "int8" then
return buffer.readi8(b, o + at)
end
return readu8(b, o + at)
end
end
Mesh.reader = reader
local function fieldReader(f: Blend.File, L: Layer, field: string): ((number, number) -> number)?
local st = f.dna.byName[L.kind]
local fld = st and st.byName[field]
if not fld then
return nil
end
local b, o, elem, max = f.buf, L.offset, L.elem, L.bytes
local t, esz = fld.type, fld.elem
local fo = fld.offset
local f32, i32, i16, u32, u16 = f.f32, f.i32, f.i16, f.u32, f.u16
return function(i: number, c: number): number
local at = i * elem + fo + c * esz
if at < 0 or at + esz > max then
return 0
end
at += o
if t == "float" then
return f32(b, at)
elseif t == "int" or t == "int32_t" then
return i32(b, at)
elseif t == "uint" or t == "uint32_t" then
return u32(b, at)
elseif t == "short" or t == "int16_t" then
return i16(b, at)
elseif t == "ushort" or t == "uint16_t" then
return u16(b, at)
end
return readu8(b, at)
end
end
-- tessellated face colours: corner k of face i at offset + i * faceStride + first + k * cornerStride, bytes in MCol's
-- memory order (alpha, blue, green, red; reversed when an int held them in a big-endian file), sRGB -> linear;
-- TFace colours load opaque, as Blender's versioning makes them
local function tessColors(f: Blend.File, tess: buffer, nc: number, offset: number, bytes: number, faceStride: number, first: number, cornerStride: number, swap: boolean, opaque: boolean?): buffer
local d = buffer.create(nc * 16)
for i = 0, nc - 1 do
local tc = buffer.readu32(tess, i * 4)
local at = (tc // 4) * faceStride + first + (tc % 4) * cornerStride
if at + 4 <= bytes then
local o = offset + at
local aa, bb, gg, rr = readu8(f.buf, o), readu8(f.buf, o + 1), readu8(f.buf, o + 2), readu8(f.buf, o + 3)
if swap then
aa, bb, gg, rr = rr, gg, bb, aa
end
buffer.writef32(d, i * 16, SRGB[rr + 1])
buffer.writef32(d, i * 16 + 4, SRGB[gg + 1])
buffer.writef32(d, i * 16 + 8, SRGB[bb + 1])
buffer.writef32(d, i * 16 + 12, if opaque then 1 else aa / 255)
end
end
return d
end
function Mesh.layers(f: Blend.File, me: Blend.View): { Layer }
local layers: { Layer } = {}
customData(f, me, { "vdata", "vert_data" }, "point", layers)
customData(f, me, { "edata", "edge_data" }, "edge", layers)
customData(f, me, { "pdata", "face_data" }, "face", layers)
customData(f, me, { "ldata", "corner_data" }, "corner", layers)
customData(f, me, { "fdata", "fdata_legacy" }, "tess", layers)
storage(f, me, layers)
return layers
end
local function count(me: Blend.View, ...: string): number
local v = me:num(...)
return if v and v > 0 then v else 0
end
export type Limits = { maxVertices: number? }
function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, string?)
local layers = Mesh.layers(f, me)
local nv = count(me, "totvert", "verts_num")
local np = count(me, "totpoly", "faces_num")
local nl = count(me, "totloop", "corners_num")
local nt = count(me, "totface", "totface_legacy")
local maxV = limits and limits.maxVertices or 2 ^ 25
if nv > maxV or nl > maxV or nt > maxV or np > maxV then
return nil, "limit: mesh over maxVertices"
end
local pos = buffer.create(nv * 12)
local P = find(layers, "point", "float3", "position")
local mv = find(layers, "point", "MVert") or legacy(f, me, "mvert", "MVert", "point")
local get: ((number, number) -> number)? = nil
if P then
get = reader(f, P)
elseif mv then
get = fieldReader(f, mv, "co")
end
if not get then
if nv > 0 then
return nil, "mesh without positions"
end
get = function(_: number, _: number): number
return 0
end
end
local g = get :: (number, number) -> number
for i = 0, nv - 1 do
for c = 0, 2 do
buffer.writef32(pos, (i * 3 + c) * 4, g(i, c))
end
end
local poly: Poly = {
name = me:idName(), nv = nv, nf = 0, nc = 0, pos = pos, cornerVert = buffer.create(0), faceStart = buffer.create(4),
faceMat = buffer.create(0), faceSmooth = buffer.create(0), uvs = {}, activeUV = 1, colors = {}, sharp = {},
generation = if P and P.cdtype == nil then "storage" elseif P then "attributes" else "mpoly",
layers = layers,
}
local corner: { [string]: any } = {}
if np > 0 then
local offs = me:target("poly_offset_indices", "face_offset_indices")
local mp = find(layers, "face", "MPoly") or legacy(f, me, "mpoly", "MPoly", "face")
local cv = find(layers, "corner", "int32", ".corner_vert")
local ml = find(layers, "corner", "MLoop") or legacy(f, me, "mloop", "MLoop", "corner")
local starts = buffer.create((np + 1) * 4)
if offs and offs.size >= (np + 1) * 4 then
for i = 0, np do
buffer.writeu32(starts, i * 4, math.clamp(f.i32(f.buf, offs.offset + i * 4), 0, nl))
end
elseif mp then
local ls, tl = fieldReader(f, mp, "loopstart"), fieldReader(f, mp, "totloop")
if not ls or not tl then
return nil, "bad MPoly"
end
-- MPoly faces are usually in loop order; faces that are not get copied corners below
local at = 0
for i = 0, np - 1 do
buffer.writeu32(starts, i * 4, at)
at += math.max(0, tl(i, 0))
end
buffer.writeu32(starts, np * 4, at)
if at > maxV * 4 then
return nil, "limit: too many corners"
end
local verts = buffer.create(at * 4)
local vr = if cv then reader(f, cv) else if ml then fieldReader(f, ml, "v") else nil
if not vr then
return nil, "mesh without corners"
end
local remap = buffer.create(at * 4)
local w = 0
for i = 0, np - 1 do
local s0, n0 = ls(i, 0), tl(i, 0)
for k = 0, n0 - 1 do
local src = s0 + k
buffer.writeu32(verts, w * 4, math.clamp(vr(src, 0), 0, math.max(nv - 1, 0)))
buffer.writeu32(remap, w * 4, math.clamp(src, 0, math.max(nl - 1, 0)))
w += 1
end
end
corner.remap = remap
corner.verts = verts
nl = at
else
return nil, "mesh without face offsets"
end
poly.faceStart = starts
poly.nf = np
if not corner.verts then
local verts = buffer.create(nl * 4)
local vr = if cv then reader(f, cv) else if ml then fieldReader(f, ml, "v") else nil
if not vr then
return nil, "mesh without corners"
end
for i = 0, nl - 1 do
buffer.writeu32(verts, i * 4, math.clamp(vr(i, 0), 0, math.max(nv - 1, 0)))
end
corner.verts = verts
end
poly.cornerVert = corner.verts
poly.nc = nl
local mats = buffer.create(np * 4)
local smooth = buffer.create(np)
local mi = find(layers, "face", "int32", "material_index")
local sf = find(layers, "face", "bool", "sharp_face")
local mr = if mi then reader(f, mi) elseif mp then fieldReader(f, mp, "mat_nr") else nil
local flag = if mp then fieldReader(f, mp, "flag") else nil
local sr = if sf then reader(f, sf) else nil
for i = 0, np - 1 do
buffer.writei32(mats, i * 4, if mr then mr(i, 0) else 0)
local s
if sr then
s = sr(i, 0) == 0
elseif flag then
s = bit32.band(flag(i, 0), ME_SMOOTH) ~= 0
else
s = poly.generation ~= "mpoly"
end
buffer.writeu8(smooth, i, if s then 1 else 0)
end
poly.faceMat, poly.faceSmooth = mats, smooth
elseif nt > 0 then
local mf = find(layers, "tess", "MFace") or legacy(f, me, "mface", "MFace", "tess")
if not mf then
return nil, "mesh without faces"
end
poly.generation = "mface"
local v = { fieldReader(f, mf, "v1"), fieldReader(f, mf, "v2"), fieldReader(f, mf, "v3"), fieldReader(f, mf, "v4") }
local mr, flag = fieldReader(f, mf, "mat_nr"), fieldReader(f, mf, "flag")
if not (v[1] and v[2] and v[3] and v[4]) then
return nil, "bad MFace"
end
local starts = buffer.create((nt + 1) * 4)
local verts = buffer.create(nt * 16)
local tessCorner = buffer.create(nt * 16) -- face * 4 + k: where tess layers keep the corner
local mats, smooth = buffer.create(nt * 4), buffer.create(nt)
local at = 0
for i = 0, nt - 1 do
buffer.writeu32(starts, i * 4, at)
local k = if (v[4] :: any)(i, 0) ~= 0 then 4 else 3
for c = 1, k do
buffer.writeu32(verts, (at + c - 1) * 4, math.clamp((v[c] :: any)(i, 0), 0, math.max(nv - 1, 0)))
buffer.writeu32(tessCorner, (at + c - 1) * 4, i * 4 + c - 1)
end
at += k
buffer.writei32(mats, i * 4, if mr then mr(i, 0) else 0)
buffer.writeu8(smooth, i, if flag and bit32.band(flag(i, 0), ME_SMOOTH) ~= 0 then 1 else 0)
end
buffer.writeu32(starts, nt * 4, at)
poly.faceStart, poly.cornerVert, poly.nf, poly.nc = starts, verts, nt, at
poly.faceMat, poly.faceSmooth = mats, smooth
corner.tess = tessCorner
end
local nc = poly.nc
local remap: buffer? = corner.remap
local function src(i: number): number
return if remap then buffer.readu32(remap, i * 4) else i
end
for _, L in layers do
if L.domain == "corner" and (L.kind == "float2" or L.kind == "MLoopUV") and string.sub(L.name, 1, 1) ~= "." then
local r = if L.kind == "float2" then reader(f, L) else fieldReader(f, L, "uv")
if r then
local d = buffer.create(nc * 8)
for i = 0, nc - 1 do
local s = src(i)
buffer.writef32(d, i * 8, r(s, 0))
buffer.writef32(d, i * 8 + 4, r(s, 1))
end
table.insert(poly.uvs, { name = L.name, data = d })
if L.activeRender and L.kind == "MLoopUV" then
poly.activeUV = #poly.uvs
end
end
elseif L.domain == "tess" and L.kind == "MTFace" and corner.tess then
local r = fieldReader(f, L, "uv")
local tess = corner.tess :: buffer
if r then
local d = buffer.create(nc * 8)
for i = 0, nc - 1 do
local tc = buffer.readu32(tess, i * 4)
local face, k = tc // 4, tc % 4
buffer.writef32(d, i * 8, r(face, k * 2))
buffer.writef32(d, i * 8 + 4, r(face, k * 2 + 1))
end
table.insert(poly.uvs, { name = L.name, data = d })
end
end
end
-- before 2.42 (no CustomData): Mesh.tface (TFace, uv[4][2] per face) and Mesh.mcol (MCol x 4 per face)
if #poly.uvs == 0 and corner.tess then
local tf = legacy(f, me, "tface", "TFace", "tess")
local r = tf and fieldReader(f, tf, "uv")
if r then
local tess = corner.tess :: buffer
local d = buffer.create(nc * 8)
for i = 0, nc - 1 do
local tc = buffer.readu32(tess, i * 4)
buffer.writef32(d, i * 8, r(tc // 4, (tc % 4) * 2))
buffer.writef32(d, i * 8 + 4, r(tc // 4, (tc % 4) * 2 + 1))
end
table.insert(poly.uvs, { name = "UVMap", data = d })
end
end
local active = me:cstring("default_uv_map_attribute") or me:cstring("active_uv_map_attribute")
if active then
for k, u in poly.uvs do
if u.name == active then
poly.activeUV = k
end
end
end
for _, L in layers do
if (L.domain == "corner" or L.domain == "point") and (L.kind == "color" or L.kind == "bytecolor") and string.sub(L.name, 1, 1) ~= "." then
local n = if L.domain == "corner" then nc else nv
local r = reader(f, L)
local d = buffer.create(n * 16)
for i = 0, n - 1 do
local s = if L.domain == "corner" then src(i) else i
for c = 0, 3 do
local x = r(s, c)
if L.kind == "bytecolor" then
x = if c == 3 then x / 255 else SRGB[math.clamp(x, 0, 255) + 1]
end
buffer.writef32(d, (i * 4 + c) * 4, x)
end
end
table.insert(poly.colors, { name = L.name, domain = L.domain, data = d })
elseif L.kind == "MCol" and L.domain == "tess" and corner.tess then
local st = f.dna.byName.MCol
local stride = if st then st.size else 4
table.insert(poly.colors, { name = L.name, domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, L.offset, L.bytes, stride * 4, 0, stride, false) })
end
end
-- before 2.42 (no CustomData): Mesh.mcol, or TFace.col (unsigned int col[4], MCol's byte layout in memory)
if #poly.colors == 0 and corner.tess then
local mc = legacy(f, me, "mcol", "MCol", "tess")
local tf = legacy(f, me, "tface", "TFace", "tess")
local col = f.dna.byName.TFace and f.dna.byName.TFace.byName.col
if mc then
table.insert(poly.colors, { name = "Col", domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, mc.offset, mc.bytes, mc.elem * 4, 0, mc.elem, false) })
elseif tf and col then
table.insert(poly.colors, { name = "Col", domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, tf.offset, tf.bytes, tf.elem, col.offset, 4, not f.little, true) })
end
end
local cn = find(layers, "corner", "short2", "custom_normal")
for _, L in layers do
if not cn and L.domain == "corner" and L.cdtype == 41 then
cn = L
end
end
if cn then
local r = reader(f, cn)
local d = buffer.create(nc * 4)
for i = 0, nc - 1 do
local s = src(i)
buffer.writei16(d, i * 4, r(s, 0))
buffer.writei16(d, i * 4 + 2, r(s, 1))
end
poly.encodedNormals = d
end
local free = find(layers, "corner", "float3", "custom_normal") or find(layers, "point", "float3", "custom_normal")
or find(layers, "face", "float3", "custom_normal")
if free then
local r = reader(f, free)
local d = buffer.create(nc * 12)
local starts = poly.faceStart
for fi = 0, poly.nf - 1 do
local s0, s1 = buffer.readu32(starts, fi * 4), buffer.readu32(starts, fi * 4 + 4)
for i = s0, s1 - 1 do
local e = if free.domain == "corner" then src(i) elseif free.domain == "face" then fi else buffer.readu32(poly.cornerVert, i * 4)
for c = 0, 2 do
buffer.writef32(d, (i * 3 + c) * 4, r(e, c))
end
end
end
poly.customNormals = d
end
-- sharp edges
local ne = count(me, "totedge", "edges_num")
local ev = find(layers, "edge", "int2", ".edge_verts")
local se = find(layers, "edge", "bool", "sharp_edge")
local medge = find(layers, "edge", "MEdge") or legacy(f, me, "medge", "MEdge", "edge")
local flags = me:num("flag") or 0
local smoothresh = me:num("smoothresh")
local autoSmooth = f.version < 401 and bit32.band(flags, ME_AUTOSMOOTH) ~= 0
if autoSmooth then
poly.autoSmooth = smoothresh or math.rad(30)
end
local useSharp = f.version >= 401 or autoSmooth
if useSharp and ne > 0 then
local v1, v2, sharp
if ev and se then
local er, sr = reader(f, ev), reader(f, se)
v1 = function(i: number): number return er(i, 0) end
v2 = function(i: number): number return er(i, 1) end
sharp = function(i: number): boolean return sr(i, 0) ~= 0 end
elseif medge then
local a, b, fl = fieldReader(f, medge, "v1"), fieldReader(f, medge, "v2"), fieldReader(f, medge, "flag")
if a and b and fl then
v1 = function(i: number): number return a(i, 0) end
v2 = function(i: number): number return b(i, 0) end
local ser = if se then reader(f, se) else nil
sharp = function(i: number): boolean
if ser then
return ser(i, 0) ~= 0
end
return bit32.band(fl(i, 0), ME_SHARP) ~= 0
end
end
end
if v1 and v2 and sharp then
for i = 0, ne - 1 do
if sharp(i) then
local a, b = v1(i), v2(i)
local lo, hi = math.min(a, b), math.max(a, b)
poly.sharp[lo * nv + hi] = true
end
end
end
end
-- deform weights
local dv = find(layers, "point", "MDeformVert") or legacy(f, me, "dvert", "MDeformVert", "point")
if dv then
local st = f.dna.byName.MDeformVert
local dwf, twf = st and st.byName.dw, st and st.byName.totweight
local mw = f.dna.byName.MDeformWeight
local nrf, wf = mw and mw.byName.def_nr, mw and mw.byName.weight
if dwf and twf and mw and nrf and wf then
local weights = table.create(nv) :: { { number } }
for i = 0, nv - 1 do
local list = {}
local at = i * dv.elem
if at + dv.elem <= dv.bytes then
local vw = Blend.view(f, "MDeformVert", dv.offset + at)
local blk = vw and vw:target("dw")
local n = vw and vw:num("totweight") or 0
if blk then
n = math.min(n, blk.size // mw.size)
for k = 0, n - 1 do
local o = blk.offset + k * mw.size
table.insert(list, f.i32(f.buf, o + nrf.offset))
table.insert(list, f.f32(f.buf, o + wf.offset))
end
end
end
weights[i + 1] = list
end
poly.weights = weights
end
end
return poly, nil
end
-- shape keys: { name, value, relative (0-based), data: f32 x 3 per vertex } in file order, and the reference index
export type Shape = { name: string, value: number, relative: number, data: buffer, mute: boolean, min: number, max: number }
function Mesh.shapes(f: Blend.File, me: Blend.View, nv: number): ({ Shape }, number?, Blend.View?)
local key = me:deref("key", 0, "Key")
if not key then
return {}, nil, nil
end
local blocks = key:list("block", "KeyBlock")
local refAddr = key:ptr("refkey")
local out: { Shape } = {}
local ref: number? = nil
for i, kb in blocks do
local blk = kb:target("data")
local d = buffer.create(nv * 12)
if blk then
local n = math.min(nv * 12, blk.size)
buffer.copy(d, 0, f.buf, blk.offset, n)
if not f.little then
for k = 0, n // 4 - 1 do
buffer.writef32(d, k * 4, f.f32(f.buf, blk.offset + k * 4))
end
end
end
if kb.block and kb.block.addr == refAddr then
ref = i
end
table.insert(out, {
-- unnamed in old files: Key 0 (the basis), Key 1, ...
name = kb:str("name") or ("Key " .. (i - 1)), value = kb:num("curval") or 0, relative = kb:num("relative") or 0, data = d,
mute = bit32.band(kb:num("flag") or 0, 2) ~= 0,
min = kb:num("slidermin") or 0,
max = kb:num("slidermax") or 1,
})
end
if ref == nil and #out > 0 then
ref = 1
end
return out, ref, key
end
return Mesh
+159
View File
@@ -0,0 +1,159 @@
--!strict
-- model/blend/Normals: Blender's encoded custom normals (CD_CUSTOMLOOPNORMAL / the "custom_normal" int16 x 2 corner
-- attribute) decoded in each smooth fan's space: the fan normal N, a reference edge direction R projected
-- perpendicular to N, O = N x R; alpha = the mean angle of the fan's edges to N, beta = the angle from R to the fan's
-- other end edge around N (2 pi for closed fans). A stored (a, b) (units of 1 / 32767) gives the angle a * alpha
-- (a > 0) or a * (2 pi - alpha) from N, turned b * beta (b > 0) or b * (2 pi - beta) from R towards O.
local Normals = {}
local readu32, readf32, writef32, readi16 = buffer.readu32, buffer.readf32, buffer.writef32, buffer.readi16
local sqrt, acos, cos, sin = math.sqrt, math.acos, math.cos, math.sin
local TAU = 2 * math.pi
local NEAR = 0.99999
type Fans = { next: buffer, prev: buffer, face: buffer, across: { [number]: number } }
local function dir(pos: buffer, from: number, to: number): (number, number, number)
local x = readf32(pos, to * 12) - readf32(pos, from * 12)
local y = readf32(pos, to * 12 + 4) - readf32(pos, from * 12 + 4)
local z = readf32(pos, to * 12 + 8) - readf32(pos, from * 12 + 8)
local l = sqrt(x * x + y * y + z * z)
if l > 0 then
return x / l, y / l, z / l
end
return 0, 0, 0
end
function Normals.decode(poly: any, lnor: buffer, fanId: buffer, fans: Fans, _ang: buffer): buffer
local nc = poly.nc
local cv, pos = poly.cornerVert, poly.pos
local enc = poly.encodedNormals :: buffer
local out = buffer.create(nc * 12)
buffer.copy(out, 0, lnor, 0, nc * 12)
local across = fans.across
local nxt, prv = fans.next, fans.prev
local done: { [number]: boolean } = {}
for c = 0, nc - 1 do
local id = readu32(fanId, c * 4)
if not done[id] then
done[id] = true
local start = c
local cyclic = false
local guard = 0
while true do
local p = across[readu32(prv, start * 4)]
if p == nil then
break
end
if p == c then
cyclic = true
break
end
start = p
guard += 1
if guard > nc then
cyclic = true
break
end
end
if cyclic then
local m, q = c, c
repeat
local nq = across[q]
q = if nq then readu32(nxt, nq * 4) else c
if q < m then
m = q
end
guard += 1
until q == c or guard > 2 * nc + 4
start = m
end
local v = readu32(cv, start * 4)
local nx, ny, nz = readf32(lnor, start * 12), readf32(lnor, start * 12 + 4), readf32(lnor, start * 12 + 8)
local corners = { start }
local edges = { readu32(cv, readu32(prv, start * 4) * 4) }
local q = start
while true do
table.insert(edges, readu32(cv, readu32(nxt, q * 4) * 4))
local a = across[q]
if a == nil then
break
end
local nq = readu32(nxt, a * 4)
if nq == start or #corners > nc then
break
end
table.insert(corners, nq)
q = nq
end
local alpha, count = 0, 0
for k, e in edges do
if not (cyclic and k == #edges) then
local x, y, z = dir(pos, v, e)
alpha += acos(math.clamp(x * nx + y * ny + z * nz, -1, 1))
count += 1
end
end
alpha /= math.max(count, 1)
-- Blender walks each fan backwards from the corner whose next edge ends it (in a closed fan: its lowest
-- corner): R is that corner's next edge, the other end the last corner's previous edge
local refEdge = if cyclic then edges[2] else edges[#edges]
local rx, ry, rz = dir(pos, v, refEdge)
local ox, oy, oz = dir(pos, v, if cyclic then refEdge else edges[1])
local dr, dother = rx * nx + ry * ny + rz * nz, ox * nx + oy * ny + oz * nz
local valid = math.abs(dr) < NEAR and math.abs(dother) < NEAR
local beta = 0
local tx, ty, tz = 0, 0, 0
if valid then
rx, ry, rz = rx - nx * dr, ry - ny * dr, rz - nz * dr
local l = sqrt(rx * rx + ry * ry + rz * rz)
rx, ry, rz = rx / l, ry / l, rz / l
tx, ty, tz = ny * rz - nz * ry, nz * rx - nx * rz, nx * ry - ny * rx
l = sqrt(tx * tx + ty * ty + tz * tz)
if l > 0 then
tx, ty, tz = tx / l, ty / l, tz / l
end
ox, oy, oz = ox - nx * dother, oy - ny * dother, oz - nz * dother
l = sqrt(ox * ox + oy * oy + oz * oz)
if l > 0 then
ox, oy, oz = ox / l, oy / l, oz / l
end
local d = rx * ox + ry * oy + rz * oz
if d < NEAR then
beta = acos(math.clamp(d, -1, 1))
if tx * ox + ty * oy + tz * oz < 0 then
beta = TAU - beta
end
else
beta = TAU
end
end
for _, k in corners do
local a, b = readi16(enc, k * 4) / 32767, readi16(enc, k * 4 + 2) / 32767
if a ~= 0 and valid and alpha ~= 0 and beta ~= 0 then
local al = (if a > 0 then alpha else TAU - alpha) * a
local sa = sin(al)
local x, y, z = nx * cos(al), ny * cos(al), nz * cos(al)
if b == 0 then
x, y, z = x + rx * sa, y + ry * sa, z + rz * sa
else
local be = (if b > 0 then beta else TAU - beta) * b
x += sa * (rx * cos(be) + tx * sin(be))
y += sa * (ry * cos(be) + ty * sin(be))
z += sa * (rz * cos(be) + tz * sin(be))
end
local l = sqrt(x * x + y * y + z * z)
if l > 0 then
x, y, z = x / l, y / l, z / l
end
writef32(out, k * 12, x)
writef32(out, k * 12 + 4, y)
writef32(out, k * 12 + 8, z)
end
end
end
end
return out
end
return Normals
+447
View File
@@ -0,0 +1,447 @@
--!strict
-- model/blend/Prim: model/blend/Mesh polygons to Scene primitives (one per material slot): corner normals from smooth
-- fans (angle-weighted face normals; sharp faces, sharp edges, auto smooth before 4.1 and non-manifold or flipped edges
-- split fans, as Blender does), custom normals, vertices shared by corners with equal attributes, n-gons by ear
-- clipping, deform weights (top 4) and shape keys as morph targets.
local Types = require("@rosetta/Types")
local Polygon = require("@rosetta/codecs/model/Polygon")
local Rig = require("@rosetta/codecs/model/Rig")
local Normals = require("@rosetta/model/blend/Normals")
local MeshT = require("@rosetta/model/blend/Mesh")
local Prim = {}
local Scene = Types.Scene
local readu32, readf32, writef32, writeu32 = buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32
local sqrt, acos = math.sqrt, math.acos
export type Options = {
triangulate: boolean?, -- default true
flipV: boolean?, -- default true (glTF's top-left UV origin)
normals: boolean?, -- default true
}
export type Skinning = { joints: { [number]: number } } -- def_nr (0-based) -> joint index (0-based) in the skin
local function face(poly: MeshT.Poly, fi: number): (number, number)
return readu32(poly.faceStart, fi * 4), readu32(poly.faceStart, fi * 4 + 4)
end
local function vec(pos: buffer, v: number): (number, number, number)
return readf32(pos, v * 12), readf32(pos, v * 12 + 4), readf32(pos, v * 12 + 8)
end
-- face normals (Newell) and corner angles
function Prim.geometry(poly: MeshT.Poly): (buffer, buffer)
local fn = buffer.create(poly.nf * 12)
local ang = buffer.create(poly.nc * 4)
local cv, pos = poly.cornerVert, poly.pos
for fi = 0, poly.nf - 1 do
local s0, s1 = face(poly, fi)
local nx, ny, nz = 0, 0, 0
local n = s1 - s0
for c = s0, s1 - 1 do
local d = if c + 1 < s1 then c + 1 else s0
local x1, y1, z1 = vec(pos, readu32(cv, c * 4))
local x2, y2, z2 = vec(pos, readu32(cv, d * 4))
nx += (y1 - y2) * (z1 + z2)
ny += (z1 - z2) * (x1 + x2)
nz += (x1 - x2) * (y1 + y2)
end
local l = sqrt(nx * nx + ny * ny + nz * nz)
if l > 0 then
nx, ny, nz = nx / l, ny / l, nz / l
end
writef32(fn, fi * 12, nx)
writef32(fn, fi * 12 + 4, ny)
writef32(fn, fi * 12 + 8, nz)
if n >= 3 then
for c = s0, s1 - 1 do
local pc = if c > s0 then c - 1 else s1 - 1
local nc = if c + 1 < s1 then c + 1 else s0
local x, y, z = vec(pos, readu32(cv, c * 4))
local ax, ay, az = vec(pos, readu32(cv, pc * 4))
local bx, by, bz = vec(pos, readu32(cv, nc * 4))
ax, ay, az = ax - x, ay - y, az - z
bx, by, bz = bx - x, by - y, bz - z
local la, lb = sqrt(ax * ax + ay * ay + az * az), sqrt(bx * bx + by * by + bz * bz)
local a = 0
if la > 0 and lb > 0 then
a = acos(math.clamp((ax * bx + ay * by + az * bz) / (la * lb), -1, 1))
end
writef32(ang, c * 4, a)
end
end
end
return fn, ang
end
-- smooth fans: for each corner the corner after it in its face, and the fan links across smooth edges
export type Fans = {
next: buffer, -- u32 per corner: the next corner of its face
prev: buffer, -- u32 per corner
face: buffer, -- u32 per corner: its face
-- per corner: the corner of the neighbouring face across the edge from this corner to the next one (the corner
-- at this corner's next vertex), or -1 where the edge splits fans
across: { [number]: number },
}
function Prim.fans(poly: MeshT.Poly, fn: buffer): Fans
local nc, nv = poly.nc, poly.nv
local cv = poly.cornerVert
local nxt, prv, fc = buffer.create(nc * 4), buffer.create(nc * 4), buffer.create(nc * 4)
for fi = 0, poly.nf - 1 do
local s0, s1 = face(poly, fi)
for c = s0, s1 - 1 do
writeu32(nxt, c * 4, if c + 1 < s1 then c + 1 else s0)
writeu32(prv, c * 4, if c > s0 then c - 1 else s1 - 1)
writeu32(fc, c * 4, fi)
end
end
local first: { [number]: number } = {}
local second: { [number]: number } = {}
local uses: { [number]: number } = {}
for c = 0, nc - 1 do
local a, b = readu32(cv, c * 4), readu32(cv, readu32(nxt, c * 4) * 4)
local key = math.min(a, b) * nv + math.max(a, b)
local u = (uses[key] or 0) + 1
uses[key] = u
if u == 1 then
first[key] = c
elseif u == 2 then
second[key] = c
end
end
local across: { [number]: number } = {}
local smooth = poly.faceSmooth
local cosLimit = if poly.autoSmooth then math.cos(poly.autoSmooth) else nil
for key, u in uses do
if u == 2 then
local c1, c2 = first[key], second[key]
local f1, f2 = readu32(fc, c1 * 4), readu32(fc, c2 * 4)
local a1 = readu32(cv, c1 * 4)
local a2 = readu32(cv, c2 * 4)
local ok = a1 ~= a2 and f1 ~= f2 and buffer.readu8(smooth, f1) ~= 0 and buffer.readu8(smooth, f2) ~= 0
and not poly.sharp[key]
if ok and cosLimit then
local d = readf32(fn, f1 * 12) * readf32(fn, f2 * 12) + readf32(fn, f1 * 12 + 4) * readf32(fn, f2 * 12 + 4)
+ readf32(fn, f1 * 12 + 8) * readf32(fn, f2 * 12 + 8)
ok = d >= cosLimit
end
if ok then
-- c1 runs a -> b, c2 runs b -> a: the corner at b in face 2 is c2, at a it is next(c2)
across[c1] = c2
across[c2] = c1
end
end
end
return { next = nxt, prev = prv, face = fc, across = across }
end
-- corner normals: angle-weighted face normals summed over each smooth fan; with fan ids (u32 per corner)
function Prim.cornerNormals(poly: MeshT.Poly, fn: buffer, ang: buffer, fans: Fans): (buffer, buffer)
local nc = poly.nc
local parent = buffer.create(nc * 4)
for c = 0, nc - 1 do
writeu32(parent, c * 4, c)
end
local function root(c: number): number
local r = c
while readu32(parent, r * 4) ~= r do
r = readu32(parent, r * 4)
end
while readu32(parent, c * 4) ~= r do
local nx = readu32(parent, c * 4)
writeu32(parent, c * 4, r)
c = nx
end
return r
end
local function union(a: number, b: number)
local ra, rb = root(a), root(b)
if ra ~= rb then
writeu32(parent, math.max(ra, rb) * 4, math.min(ra, rb))
end
end
for c1, c2 in fans.across do
if c1 < c2 then
-- edge c1 (a -> b) shared with c2 (b -> a): corners at b are next(c1) and c2, at a c1 and next(c2)
union(readu32(fans.next, c1 * 4), c2)
union(c1, readu32(fans.next, c2 * 4))
end
end
local acc = buffer.create(nc * 12)
local fanId = buffer.create(nc * 4)
for c = 0, nc - 1 do
local r = root(c)
writeu32(fanId, c * 4, r)
local fi = readu32(fans.face, c * 4)
local w = readf32(ang, c * 4)
for k = 0, 2 do
writef32(acc, (r * 3 + k) * 4, readf32(acc, (r * 3 + k) * 4) + readf32(fn, (fi * 3 + k) * 4) * w)
end
end
local out = buffer.create(nc * 12)
for c = 0, nc - 1 do
local r = readu32(fanId, c * 4)
local x, y, z = readf32(acc, r * 12), readf32(acc, r * 12 + 4), readf32(acc, r * 12 + 8)
local l = sqrt(x * x + y * y + z * z)
local fi = readu32(fans.face, c * 4)
writef32(out, c * 12, if l > 1e-20 then x / l else readf32(fn, fi * 12))
writef32(out, c * 12 + 4, if l > 1e-20 then y / l else readf32(fn, fi * 12 + 4))
writef32(out, c * 12 + 8, if l > 1e-20 then z / l else readf32(fn, fi * 12 + 8))
end
return out, fanId
end
function Prim.normals(poly: MeshT.Poly): buffer
local fn, ang = Prim.geometry(poly)
local fans = Prim.fans(poly, fn)
local nrm, fanId = Prim.cornerNormals(poly, fn, ang, fans)
if poly.customNormals then
return poly.customNormals :: buffer
end
if poly.encodedNormals then
return Normals.decode(poly, nrm, fanId, fans, ang)
end
return nrm
end
-- triangles of face fi as corner indices (appended to out)
local function triangulate(poly: MeshT.Poly, fi: number, fnx: number, fny: number, fnz: number, out: { number })
local s0, s1 = face(poly, fi)
local n = s1 - s0
if n < 3 then
return
end
if n == 3 then
table.insert(out, s0)
table.insert(out, s0 + 1)
table.insert(out, s0 + 2)
return
end
local ax, ay, az = math.abs(fnx), math.abs(fny), math.abs(fnz)
local cu, cv, sign = 0, 1, fnz
if ax >= ay and ax >= az then
cu, cv, sign = 1, 2, fnx
elseif ay >= az then
cu, cv, sign = 2, 0, fny
end
local ring = table.create(n * 2) :: { number }
for c = s0, s1 - 1 do
local v = readu32(poly.cornerVert, c * 4)
local u, w = readf32(poly.pos, (v * 3 + cu) * 4), readf32(poly.pos, (v * 3 + cv) * 4)
table.insert(ring, if sign < 0 then -u else u)
table.insert(ring, w)
end
local tris = Polygon.triangulate({ ring })
if #tris == (n - 2) * 6 then
for k = 2, #tris, 2 do
table.insert(out, s0 + tris[k] - 1)
end
return
end
for k = 1, n - 2 do -- degenerate: a fan
table.insert(out, s0)
table.insert(out, s0 + k)
table.insert(out, s0 + k + 1)
end
end
local function accessor(t: { number }, comps: number): Types.Accessor
local n = #t // comps
local b = buffer.create(#t * 4)
for i = 1, #t do
writef32(b, (i - 1) * 4, t[i])
end
return Scene.accessor(b, "f32", comps, n)
end
export type Built = { mesh: Types.Mesh, slots: { number }, vertexSource: { { number } } }
-- slots[k] = the scene material of slot k - 1 (or 0 for none); skin maps deform groups to joints
function Prim.build(poly: MeshT.Poly, slots: { number }, opts: Options?, skin: Skinning?, shapes: { MeshT.Shape }?, ref: number?): Built
local triangulateOn = not (opts and opts.triangulate == false)
local flipV = not (opts and opts.flipV == false)
local withNormals = not (opts and opts.normals == false)
local nrm = if withNormals and poly.nf > 0 then Prim.normals(poly) else nil
local fn = if poly.nf > 0 then (Prim.geometry(poly)) else buffer.create(0)
local nslots = math.max(#slots, 1)
local groups: { [number]: { number } } = {}
local order: { number } = {}
for fi = 0, poly.nf - 1 do
local m = math.clamp(buffer.readi32(poly.faceMat, fi * 4), 0, nslots - 1)
local g = groups[m]
if not g then
g = {}
groups[m] = g
table.insert(order, m)
end
table.insert(g, fi)
end
table.sort(order)
local cornerColors: { MeshT.Color }, pointColors: { MeshT.Color } = {}, {}
for _, c in poly.colors do
table.insert(if c.domain == "corner" then cornerColors else pointColors, c)
end
local keyBytes = 4 + (if nrm then 12 else 0) + #poly.uvs * 8 + #cornerColors * 16
local scratch = buffer.create(keyBytes)
local mesh: Types.Mesh = { name = poly.name, primitives = {} }
local sources: { { number } } = {}
local cv = poly.cornerVert
for _, m in order do
local faces = groups[m]
local map: { [string]: number } = {}
local vsrc: { number } = {}
local corners: { number } = {} -- the first corner of each output vertex
local cornerOut = {} -- corner -> output vertex
for _, fi in faces do
local s0, s1 = face(poly, fi)
for c = s0, s1 - 1 do
local v = readu32(cv, c * 4)
buffer.writeu32(scratch, 0, v)
local o = 4
if nrm then
buffer.copy(scratch, o, nrm, c * 12, 12)
o += 12
end
for _, uv in poly.uvs do
buffer.copy(scratch, o, uv.data, c * 8, 8)
o += 8
end
for _, col in cornerColors do
buffer.copy(scratch, o, col.data, c * 16, 16)
o += 16
end
local key = buffer.readstring(scratch, 0, keyBytes)
local idx = map[key]
if not idx then
idx = #vsrc
map[key] = idx
table.insert(vsrc, v)
table.insert(corners, c)
end
cornerOut[c] = idx
end
end
local n = #vsrc
local attrs: { [string]: Types.Accessor } = {}
local P = buffer.create(n * 12)
for i = 1, n do
buffer.copy(P, (i - 1) * 12, poly.pos, vsrc[i] * 12, 12)
end
attrs.POSITION = Scene.accessor(P, "f32", 3, n)
if nrm then
local N = buffer.create(n * 12)
for i = 1, n do
buffer.copy(N, (i - 1) * 12, nrm, corners[i] * 12, 12)
end
attrs.NORMAL = Scene.accessor(N, "f32", 3, n)
end
for k, uv in poly.uvs do
local T = buffer.create(n * 8)
for i = 1, n do
local c = corners[i]
writef32(T, (i - 1) * 8, readf32(uv.data, c * 8))
local v = readf32(uv.data, c * 8 + 4)
writef32(T, (i - 1) * 8 + 4, if flipV then 1 - v else v)
end
local acc = Scene.accessor(T, "f32", 2, n)
acc.name = uv.name
attrs["TEXCOORD_" .. (k - 1)] = acc
end
local ci = 0
for _, col in poly.colors do
local C = buffer.create(n * 16)
for i = 1, n do
local e = if col.domain == "corner" then corners[i] else vsrc[i]
buffer.copy(C, (i - 1) * 16, col.data, e * 16, 16)
end
local acc = Scene.accessor(C, "f32", 4, n)
acc.name = col.name
attrs["COLOR_" .. ci] = acc
ci += 1
end
if skin and poly.weights then
local lists = table.create(n) :: { { number } }
for i = 1, n do
local src = poly.weights[vsrc[i] + 1] or {}
local l = {}
for k = 1, #src - 1, 2 do
local j = skin.joints[src[k]]
if j then
table.insert(l, j)
table.insert(l, src[k + 1])
end
end
lists[i] = l
end
attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists)
end
local prim: Types.Primitive = { attributes = attrs, mode = "triangles" }
local idx: { number } = {}
if triangulateOn then
for _, fi in faces do
local tri: { number } = {}
triangulate(poly, fi, readf32(fn, fi * 12), readf32(fn, fi * 12 + 4), readf32(fn, fi * 12 + 8), tri)
for _, c in tri do
table.insert(idx, cornerOut[c])
end
end
else
local sizes = buffer.create(#faces * 4)
for k, fi in faces do
local s0, s1 = face(poly, fi)
writeu32(sizes, (k - 1) * 4, s1 - s0)
for c = s0, s1 - 1 do
table.insert(idx, cornerOut[c])
end
end
prim.mode = "polygons"
prim.faces = Scene.accessor(sizes, "u32", 1, #faces)
end
local I = buffer.create(#idx * 4)
for k, v in idx do
writeu32(I, (k - 1) * 4, v)
end
prim.indices = Scene.accessor(I, "u32", 1, #idx)
local mat = slots[m + 1]
if mat and mat > 0 then
prim.material = mat
end
if shapes and ref and #shapes > 1 then
local base = shapes[ref].data
local targets: { { [string]: Types.Accessor } } = {}
for k, s in shapes do
if k ~= ref then
local t = table.create(n * 3) :: { number }
for i = 1, n do
local v = vsrc[i]
for c = 0, 2 do
t[(i - 1) * 3 + c + 1] = readf32(s.data, (v * 3 + c) * 4) - readf32(base, (v * 3 + c) * 4)
end
end
table.insert(targets, { POSITION = accessor(t, 3) } :: { [string]: Types.Accessor })
end
end
prim.targets = targets
end
table.insert(mesh.primitives, prim)
table.insert(sources, vsrc)
end
if shapes and ref and #shapes > 1 then
local w = {}
for k, s in shapes do
if k ~= ref then
table.insert(w, s.value)
end
end
mesh.weights = w
end
local usedSlots = {}
for _, m in order do
table.insert(usedSlots, m)
end
return { mesh = mesh, slots = usedSlots, vertexSource = sources }
end
return Prim
+898
View File
@@ -0,0 +1,898 @@
--!strict
-- model/blend/Read: a parsed .blend (containers/Blend) to a Scene: the current scene's objects (from its collections,
-- or Base list before 2.8) with their transforms (euler orders, quaternion, axis angle, delta transforms, parent
-- inverse; bone parents), meshes (model/blend/Mesh, model/blend/Prim), materials (Principled BSDF node or the legacy
-- colour), images (packed bytes or external uris), cameras, lights (watts to candela / lux as Blender's glTF exporter
-- does: 683 lm/W, / 4 pi for point and spot), armatures (bones to joint nodes with the saved pose), skins, shape keys
-- and actions sampled into channels.
local Blend = require("@rosetta/containers/Blend")
local Types = require("@rosetta/Types")
local Mat4 = require("@rosetta/codecs/model/Mat4")
local Rig = require("@rosetta/codecs/model/Rig")
local Mesh = require("@rosetta/model/blend/Mesh")
local Prim = require("@rosetta/model/blend/Prim")
local Anim = require("@rosetta/model/blend/Anim")
local Material = require("@rosetta/model/blend/Material")
local Read = {}
local Scene = Types.Scene
type M4 = { number }
export type Options = {
triangulate: boolean?,
flipV: boolean?,
collections: boolean?, -- collections as nodes (default true)
scene: string?, -- the scene to read (default: the file's current scene)
sampleStep: number?, -- frames between animation samples (default 1)
animations: boolean?, -- default true
resolve: ((uri: string) -> any)?,
files: { [string]: any }?,
maxVertices: number?,
}
local OB_EMPTY, OB_MESH, OB_LAMP, OB_CAMERA, OB_ARMATURE = 0, 1, 10, 11, 25
local PARSKEL, PARBONE = 4, 7
local LA_LOCAL, LA_SUN, LA_SPOT, LA_HEMI, LA_AREA = 0, 1, 2, 3, 4
local EULER = { [1] = "xyz", [2] = "xzy", [3] = "yxz", [4] = "yzx", [5] = "zxy", [6] = "zyx" }
local TYPE_NAME: { [number]: string } = {
[0] = "empty", [1] = "mesh", [2] = "curve", [3] = "surface", [4] = "text", [5] = "metaball", [10] = "light",
[11] = "camera", [12] = "speaker", [13] = "lightprobe", [22] = "lattice", [25] = "armature", [26] = "gpencil",
[27] = "curves", [28] = "pointcloud", [29] = "volume", [30] = "grease_pencil",
}
local W2LM = 683
-- ------------------------------------------------------------------------------------------------ transforms
local function quatWXYZ(q: { number }?): { number }
if not q or #q < 4 then
return { 0, 0, 0, 1 }
end
local w, x, y, z = q[1], q[2], q[3], q[4]
local l = math.sqrt(w * w + x * x + y * y + z * z)
if l < 1e-12 then
return { 0, 0, 0, 1 }
end
return { x / l, y / l, z / l, w / l }
end
local function rotation(mode: number, eul: { number }?, quat: { number }?, axis: { number }?, angle: number?): M4
if mode == 0 then
return Mat4.fromQuat(quatWXYZ(quat))
elseif mode == -1 then
local a = axis or { 0, 1, 0 }
return Mat4.fromQuat(Mat4.axisAngle(a[1], a[2], a[3], math.deg(angle or 0)))
end
local e = eul or { 0, 0, 0 }
return Mat4.euler(math.deg(e[1]), math.deg(e[2]), math.deg(e[3]), EULER[mode] or "xyz")
end
local function scaleM(m: M4, s: { number }): M4
local r = table.clone(m)
for c = 0, 2 do
for k = 1, 3 do
r[c * 4 + k] *= s[c + 1]
end
end
return r
end
local function trs(t: { number }, r: M4, s: { number }): M4
local m = scaleM(r, s)
m[13], m[14], m[15] = t[1], t[2], t[3]
return m
end
export type Props = { [string]: { number } } -- location / rotation_euler / ... as Blender data paths, rotmode
local function objectProps(ob: Blend.View): Props
-- fields missing from old files take their neutral value
local function v(fallback: { number }, ...: string): { number }
local x = ob:vec(...)
if x and #x >= #fallback then
return table.clone(x)
end
return fallback
end
local p: Props = {
location = v({ 0, 0, 0 }, "loc"),
rotation_euler = v({ 0, 0, 0 }, "rot"),
rotation_quaternion = v({ 1, 0, 0, 0 }, "quat"),
rotation_axis_angle = { ob:num("rotAngle") or 0, table.unpack(v({ 0, 1, 0 }, "rotAxis")) },
scale = v({ 1, 1, 1 }, "scale", "size"),
delta_location = v({ 0, 0, 0 }, "dloc"),
delta_rotation_euler = v({ 0, 0, 0 }, "drot"),
delta_rotation_quaternion = v({ 1, 0, 0, 0 }, "dquat"),
delta_rotation_axis_angle = { ob:num("drotAngle") or 0, table.unpack(v({ 0, 1, 0 }, "drotAxis")) },
delta_scale = v({ 1, 1, 1 }, "dscale"),
rotmode = { ob:num("rotmode") or 1 },
}
if not ob:has("dscale") then
-- before 2.5x the delta scale ("dsize") was added to the scale
local d = v({ 0, 0, 0 }, "dsize")
p.scale = { p.scale[1] + d[1], p.scale[2] + d[2], p.scale[3] + d[3] }
end
return p
end
local function poseProps(pc: Blend.View?): Props
if not pc then
return {
location = { 0, 0, 0 }, rotation_euler = { 0, 0, 0 }, rotation_quaternion = { 1, 0, 0, 0 },
rotation_axis_angle = { 0, 0, 1, 0 }, scale = { 1, 1, 1 }, rotmode = { 0 },
}
end
local function v(n: number, ...: string): { number }
local x = pc:vec(...)
if x and #x >= n then
return table.clone(x)
end
return table.create(n, 0)
end
return {
location = v(3, "loc"),
rotation_euler = v(3, "eul"),
rotation_quaternion = v(4, "quat"),
rotation_axis_angle = { pc:num("rotAngle") or 0, table.unpack(v(3, "rotAxis")) },
scale = v(3, "scale", "size"),
rotmode = { pc:num("rotmode") or 0 },
}
end
-- Blender's object matrix: T(loc + dloc) * Rdelta * R * S(scale * dscale)
local function objectBasis(p: Props): M4
local mode = p.rotmode[1]
local aa, daa = p.rotation_axis_angle, p.delta_rotation_axis_angle
local r = rotation(mode, p.rotation_euler, p.rotation_quaternion, { aa[2], aa[3], aa[4] }, aa[1])
if p.delta_location then
local d = rotation(mode, p.delta_rotation_euler, p.delta_rotation_quaternion, { daa[2], daa[3], daa[4] }, daa[1])
r = Mat4.mul(d, r)
local l, dl, s, ds = p.location, p.delta_location, p.scale, p.delta_scale
return trs({ l[1] + dl[1], l[2] + dl[2], l[3] + dl[3] }, r, { s[1] * ds[1], s[2] * ds[2], s[3] * ds[3] })
end
return trs(p.location, r, p.scale)
end
local function nodeTRS(node: Types.Node, m: M4)
local t, r, s = Mat4.decomposeStrict(m)
if t and r and s then
node.translation, node.rotation, node.scale = t, r, s
node.matrix = nil
else
node.matrix = m
node.translation, node.rotation, node.scale = nil, nil, nil
end
end
local function mat4(v: Blend.View?, ...: string): M4?
local m = v and v:vec(...)
if m and #m == 16 then
return m
end
return nil
end
-- ------------------------------------------------------------------------------------------------ scene
type Ctx = {
f: Blend.File,
scene: Types.Scene,
opts: Options,
objects: { [any]: number }, -- OB addr -> node
objView: { [number]: Blend.View }, -- node -> its object
parentOf: { [number]: number },
world: { [number]: M4 },
meshes: { [string]: number },
materials: { [any]: number },
textures: { [any]: number },
armatures: { [any]: { joints: { number }, names: { [string]: number }, rest: { M4 }, restLocal: { M4 }, bones: { Blend.View }, deform: { boolean }, node: number, poseNames: { [string]: Blend.View } } },
prefix: { [number]: M4 }, -- node -> the matrix before its basis (parent inverse, bone tail offset)
props: { [number]: Props },
meta: { [string]: any },
pending: { { node: number, ob: Blend.View } },
}
local function worldOf(ctx: Ctx, node: number): M4
local cached = ctx.world[node]
if cached then
return cached
end
local m = Scene.nodeMatrix(ctx.scene.nodes[node])
local p = ctx.parentOf[node]
local w = if p then Mat4.mul(worldOf(ctx, p), m) else m
ctx.world[node] = w
return w
end
local function addNode(ctx: Ctx, node: Types.Node, parent: number?): number
table.insert(ctx.scene.nodes, node)
local idx = #ctx.scene.nodes
if parent then
table.insert(ctx.scene.nodes[parent].children, idx)
ctx.parentOf[idx] = parent
else
table.insert(ctx.scene.roots, idx)
end
return idx
end
local function armature(ctx: Ctx, ob: Blend.View, node: number)
local f = ctx.f
local arm = ob:deref("data", 0, "bArmature")
if not arm then
return
end
local pose = ob:deref("pose", 0, "bPose")
local poseNames: { [string]: Blend.View } = {}
if pose then
for _, pc in pose:list("chanbase", "bPoseChannel") do
local n = pc:str("name")
if n then
poseNames[n] = pc
end
end
end
local info = { joints = {}, names = {}, rest = {}, restLocal = {}, bones = {}, deform = {}, node = node, poseNames = poseNames }
local function walk(list: { Blend.View }, parentJoint: number?, parentRest: M4?, depth: number)
if depth > 256 then
return
end
for _, bone in list do
local name = bone:str("name") or ""
local rest = mat4(bone, "arm_mat") or Mat4.identity()
local restLocal = if parentRest then Mat4.mul(Mat4.inverseFull(parentRest) or Mat4.identity(), rest) else rest
local props = poseProps(poseNames[name])
local basis = objectBasis(props)
local jnode: Types.Node = { name = name, children = {} }
nodeTRS(jnode, Mat4.mul(restLocal, basis))
local parentNode = if parentJoint then info.joints[parentJoint] else node
local idx = addNode(ctx, jnode, parentNode)
table.insert(info.joints, idx)
table.insert(info.bones, bone)
table.insert(info.rest, rest)
table.insert(info.restLocal, restLocal)
table.insert(info.deform, bit32.band(bone:num("flag") or 0, 0x1000) == 0)
local j = #info.joints
info.names[name] = j
ctx.props[idx] = props
ctx.prefix[idx] = restLocal
jnode.extras = { blend = { bone = true, length = bone:num("length") or 0 } }
walk(bone:list("childbase", "Bone"), j, rest, depth + 1)
end
end
walk(arm:list("bonebase", "Bone"), nil, nil, 0)
ctx.armatures[ob.block and ob.block.addr or node] = info
local _ = f
end
local function camera(ctx: Ctx, ob: Blend.View, node: number)
local cam = ob:deref("data", 0, "Camera")
if not cam then
return
end
local r = ctx.meta.render
local aspect = r.aspect
local znear, zfar = cam:num("clip_start", "clipsta") or 0.1, cam:num("clip_end", "clipend") or 100
local c: Types.Camera
if (cam:num("type") or 0) == 1 then
-- files without ortho_scale (before 2.3x) scaled orthographic views by 256 / lens, as Blender's versioning sets it
local half = (cam:num("ortho_scale") or 256 / math.max(cam:num("lens") or 35, 1e-3)) / 2
local xmag, ymag = half, half / aspect
if aspect < 1 then
xmag, ymag = half * aspect, half
end
c = { name = ob:idName(), type = "orthographic", xmag = xmag, ymag = ymag, znear = znear, zfar = zfar } :: Types.Camera
else
local lens = cam:num("lens") or 50
local sx, sy = cam:num("sensor_x") or 36, cam:num("sensor_y") or 24
local fit = cam:num("sensor_fit") or 0
local yfov
if fit == 2 then
yfov = 2 * math.atan(sy / 2 / lens)
elseif fit == 1 or aspect >= 1 then
yfov = 2 * math.atan(math.tan(math.atan(sx / 2 / lens)) / aspect)
else
yfov = 2 * math.atan(sx / 2 / lens)
end
c = { name = ob:idName(), type = "perspective", yfov = yfov, aspect = aspect, znear = znear, zfar = zfar } :: Types.Camera
end
table.insert(ctx.scene.cameras, c)
ctx.scene.nodes[node].camera = #ctx.scene.cameras
end
local function light(ctx: Ctx, ob: Blend.View, node: number)
local la = ob:deref("data", 0, "Light") or ob:deref("data", 0, "Lamp")
if not la then
return
end
local t = la:num("type") or 0
local color = { la:num("r") or 1, la:num("g") or 1, la:num("b") or 1 }
local energy = la:num("energy") or 1
if ctx.f.version < 280 and ctx.meta.engine ~= "CYCLES" then
-- Blender's 2.8 versioning: Blender Internal energies times 100 (suns unchanged)
if t ~= LA_SUN and t ~= LA_HEMI then
energy *= 100
end
elseif ctx.f.version < 280 then
-- Cycles took the strength from the lamp's Emission node, else 100 (sun: 1)
energy = if t == LA_SUN or t == LA_HEMI then 1 else 100
local tree = (la:num("use_nodes") or 0) ~= 0 and la:deref("nodetree", 0, "bNodeTree") or nil
for _, n in if tree then tree:list("nodes", "bNode") else {} do
if n:str("idname") == "ShaderNodeEmission" then
for _, s in n:list("inputs", "bNodeSocket") do
local v = s:str("name") == "Strength" and s:deref("default_value", 0, "bNodeSocketValueFloat")
if v then
energy = v:num("value") or energy
end
end
end
end
end
local name = ob:idName()
local l: Types.Light
if t == LA_SUN or t == LA_HEMI then
l = { name = name, type = "directional", color = color, intensity = energy * W2LM } :: Types.Light
elseif t == LA_SPOT then
local size = la:num("spotsize") or math.rad(45)
if ctx.f.version < 263 then
size = math.rad(size) -- degrees before 2.63
end
local outer = size / 2
local blend = la:num("spotblend") or 0
l = { name = name, type = "spot", color = color, intensity = energy / (4 * math.pi) * W2LM, outerCone = outer, innerCone = outer - outer * blend } :: Types.Light
elseif t == LA_LOCAL then
l = { name = name, type = "point", color = color, intensity = energy / (4 * math.pi) * W2LM } :: Types.Light
else
local skipped = ctx.meta.skippedLights or {}
ctx.meta.skippedLights = skipped
table.insert(skipped, { name = name, type = if t == LA_AREA then "area" else tostring(t) })
return
end
table.insert(ctx.scene.lights, l)
ctx.scene.nodes[node].light = #ctx.scene.lights
end
local function slotMaterials(ctx: Ctx, ob: Blend.View, me: Blend.View): { number }
local obMats = ob:pointers("mat", ob:num("totcol"))
local meMats = me:pointers("mat", me:num("totcol"))
local bits = ob:target("matbits")
local n = math.max(#obMats, #meMats)
local out = {}
for i = 1, n do
local useOb = bits ~= nil and i - 1 < bits.size and buffer.readu8(ctx.f.buf, bits.offset + i - 1) ~= 0
local addr = if useOb then obMats[i] else meMats[i]
local m = 0
if addr then
local blk = Blend.resolve(ctx.f, addr)
local mv = blk and Blend.struct(ctx.f, blk, 0, "Material")
if mv then
m = Material.get(ctx :: any, mv)
end
end
out[i] = m
end
return out
end
local function deformArmature(ctx: Ctx, ob: Blend.View): Blend.View?
for _, md in ob:list("modifiers") do
if md.struct.name == "ArmatureModifierData" then
local a = md:deref("object", 0, "Object")
if a then
return a
end
end
end
local p = ob:deref("parent", 0, "Object")
if p and (ob:num("partype") or 0) == PARSKEL and (p:num("type") or -1) == OB_ARMATURE then
return p
end
return nil
end
local function groupNames(ob: Blend.View, me: Blend.View): { string }
local list = me:list("vertex_group_names", "bDeformGroup")
if #list == 0 then
list = ob:list("defbase", "bDeformGroup")
end
local out = {}
for i, g in list do
out[i] = g:str("name") or ""
end
return out
end
local function mesh(ctx: Ctx, ob: Blend.View, node: number)
local f = ctx.f
local me = ob:deref("data", 0, "Mesh")
if not me then
return
end
local slots = slotMaterials(ctx, ob, me)
local armOb = deformArmature(ctx, ob)
local armInfo = armOb and armOb.block and ctx.armatures[armOb.block.addr]
local key = tostring(me.block and me.block.index) .. ":" .. table.concat(slots, ",") .. ":" .. tostring(armOb and armOb.block and armOb.block.index)
local skin: Prim.Skinning? = nil
if armInfo then
local joints = {}
for gi, name in groupNames(ob, me) do
local j = armInfo.names[name]
if j and armInfo.deform[j] then
joints[gi - 1] = j - 1
end
end
skin = { joints = joints }
end
local idx = ctx.meshes[key]
if not idx then
local poly, err = Mesh.read(f, me, { maxVertices = ctx.opts.maxVertices })
if not poly then
error(err or "bad mesh", 0)
end
local shapes, ref = Mesh.shapes(f, me, poly.nv)
local built = Prim.build(poly, slots, { triangulate = ctx.opts.triangulate, flipV = ctx.opts.flipV }, skin, shapes, ref)
local m = built.mesh
m.extras = { blend = { vertices = poly.nv, faces = poly.nf, corners = poly.nc, generation = poly.generation, uvs = #poly.uvs, colors = #poly.colors, shapes = #shapes } }
table.insert(ctx.scene.meshes, m)
idx = #ctx.scene.meshes
ctx.meshes[key] = idx
local gens = ctx.meta.generations
gens[poly.generation] = (gens[poly.generation] or 0) + 1
if #shapes > 1 then
ctx.meta.shapeKeys[idx] = { key = me:deref("key", 0, "Key"), mesh = me, shapes = shapes, ref = ref }
end
end
local n = ctx.scene.nodes[node]
n.mesh = idx
if ctx.scene.meshes[idx].weights then
n.weights = table.clone(ctx.scene.meshes[idx].weights :: { number })
end
if armInfo then
table.insert(ctx.pending, { node = node, ob = ob })
end
end
local function skins(ctx: Ctx)
for _, p in ctx.pending do
local armOb = deformArmature(ctx, p.ob)
local info = armOb and armOb.block and ctx.armatures[armOb.block.addr]
if info then
local armWorld = worldOf(ctx, info.node)
local meshWorld = worldOf(ctx, p.node)
local n = #info.joints
local ibm = buffer.create(n * 64)
for j = 1, n do
local inv = Mat4.inverseFull(Mat4.mul(armWorld, info.rest[j])) or Mat4.identity()
local m = Mat4.mul(inv, meshWorld)
for k = 1, 16 do
buffer.writef32(ibm, ((j - 1) * 16 + k - 1) * 4, m[k])
end
end
local acc = Scene.accessor(ibm, "f32", 16, n)
acc.matrix = true
table.insert(ctx.scene.skins, { name = armOb and armOb:idName(), joints = table.clone(info.joints), inverseBindMatrices = acc, skeleton = info.node })
ctx.scene.nodes[p.node].skin = #ctx.scene.skins
end
end
end
local function object(ctx: Ctx, ob: Blend.View, under: number?, depth: number): number?
local addr = ob.block and ob.block.addr
if addr ~= nil and ctx.objects[addr] then
return ctx.objects[addr]
end
if depth > 512 then
return nil
end
local parentOb = ob:deref("parent", 0, "Object")
local parentNode: number? = under
local prefix = Mat4.identity()
local partype = ob:num("partype") or 0
if parentOb then
local pn = object(ctx, parentOb, under, depth + 1)
if pn then
parentNode = pn
prefix = mat4(ob, "parentinv") or Mat4.identity()
if partype == PARBONE then
local info = parentOb.block and ctx.armatures[parentOb.block.addr]
local bone = ob:str("parsubstr") or ""
local j = info and info.names[bone]
if info and j then
parentNode = info.joints[j]
local len = info.bones[j]:num("length") or 0
prefix = Mat4.mul(Mat4.translation(0, len, 0), prefix)
end
end
end
end
if addr ~= nil and ctx.objects[addr] then
return ctx.objects[addr]
end
local props = objectProps(ob)
local node: Types.Node = { name = ob:idName(), children = {} }
nodeTRS(node, Mat4.mul(prefix, objectBasis(props)))
local idx = addNode(ctx, node, parentNode)
if addr ~= nil then
ctx.objects[addr] = idx
end
ctx.objView[idx] = ob
ctx.props[idx] = props
ctx.prefix[idx] = prefix
local t = ob:num("type") or -1
local extras: { [string]: any } = { type = TYPE_NAME[t] or tostring(t) }
node.extras = { blend = extras }
local lay = ob:num("lay")
if lay and ctx.f.version < 280 then
extras.layers = lay
end
local mods = {}
for _, md in ob:list("modifiers") do
table.insert(mods, { name = md:sub("modifier") and (md:sub("modifier") :: Blend.View):str("name") or md:str("name") or "", type = (string.gsub(md.struct.name, "ModifierData$", "")) })
end
if #mods > 0 then
extras.modifiers = mods
ctx.meta.modifiers[node.name or tostring(idx)] = mods
end
if t == OB_ARMATURE then
armature(ctx, ob, idx)
elseif t == OB_CAMERA then
camera(ctx, ob, idx)
elseif t == OB_LAMP then
light(ctx, ob, idx)
elseif t ~= OB_EMPTY and t ~= OB_MESH then
ctx.meta.unsupported[TYPE_NAME[t] or tostring(t)] = (ctx.meta.unsupported[TYPE_NAME[t] or tostring(t)] or 0) + 1
end
return idx
end
-- ------------------------------------------------------------------------------------------------ animation
local function apply(props: Props, curves: { Curve }, frame: number, prefix: string?, name: string?): Props
local p: Props = {}
for k, v in props do
p[k] = table.clone(v)
end
for _, c in curves do
local kind, who, rest = Anim.split(c.path)
if (prefix == nil and kind == nil) or (prefix ~= nil and kind == prefix and who == name) then
local arr = p[rest]
if arr and c.index >= 0 and c.index < #arr then
local v = Anim.evaluate(c, frame)
if rest == "rotation_axis_angle" or rest == "delta_rotation_axis_angle" then
arr[c.index + 1] = v
else
arr[c.index + 1] = v
end
end
end
end
return p
end
type Curve = Anim.Curve
local function frames(lo: number, hi: number, step: number): { number }
local out = {}
local f = lo
while f < hi - 1e-9 and #out < 2 ^ 20 do
table.insert(out, f)
f += step
end
table.insert(out, hi)
return out
end
type Job = { kind: string, node: number?, nodes: { number }?, info: any?, curves: { Curve }, action: string, meshIdx: number? }
local function animations(ctx: Ctx)
local f = ctx.f
local jobs: { Job } = {}
-- an IPO shared by several objects animates the first by name only, as Blender's 2.5 conversion leaves it
local ipoOwner: { [any]: string } = {}
for _, ob in ctx.objView do
local a, nm = ob:ptr("ipo"), ob:idName() or ""
if a ~= nil and (ipoOwner[a] == nil or nm < ipoOwner[a]) then
ipoOwner[a] = nm
end
end
for node = 1, #ctx.scene.nodes do
local ob = ctx.objView[node]
local curves, name
if ob then
curves, name = Anim.curves(f, ob:deref("adt", 0, "AnimData"))
local ipoAddr = ob:ptr("ipo")
if not curves and not ob:has("adt") and ipoAddr ~= nil and ipoOwner[ipoAddr] == ob:idName() then
curves, name = Anim.ipo(f, ob:deref("ipo", 0, "Ipo"))
end
end
if curves and #curves > 0 and name then
table.insert(jobs, { kind = "object", node = node, curves = curves, action = name })
local info = ob.block and ctx.armatures[ob.block.addr]
if info then
table.insert(jobs, { kind = "pose", info = info, curves = curves, action = name })
end
end
end
for meshIdx, sk in ctx.meta.shapeKeys do
local found, name = Anim.curves(f, sk.key and sk.key:deref("adt", 0, "AnimData"))
local curves: { Curve }? = found
if not curves and sk.key and not sk.key:has("adt") then
local names = {}
for i, s in sk.shapes do
names[i] = s.name
end
curves, name = Anim.ipo(f, sk.key:deref("ipo", 0, "Ipo"), names)
end
-- 2.7x could key shape values from the mesh ("shape_keys.key_blocks[...].value")
local mc, mname = Anim.curves(f, sk.mesh:deref("adt", 0, "AnimData"))
for _, c in mc or {} do
if string.sub(c.path, 1, 11) == "shape_keys." then
c.path = string.sub(c.path, 12)
local list: { Curve } = curves or {}
curves = list
name = name or mname
table.insert(list, c)
end
end
if curves and #curves > 0 and name then
local nodes = {}
for i, n in ctx.scene.nodes do
if n.mesh == meshIdx then
table.insert(nodes, i)
end
end
table.insert(jobs, { kind = "shapes", nodes = nodes, curves = curves :: { Curve }, action = name, meshIdx = meshIdx })
end
end
if #jobs == 0 then
return
end
table.sort(jobs, function(a: Job, b: Job): boolean
return a.action < b.action
end)
local zero = ctx.meta.frameStart
for _, j in jobs do
local lo = Anim.range(j.curves)
zero = math.min(zero, math.floor(lo))
end
ctx.meta.frameZero = zero
local fps = ctx.meta.fps
local step = ctx.opts.sampleStep or 1
local byAction: { [string]: Types.Animation } = {}
for _, j in jobs do
local anim = byAction[j.action]
if not anim then
anim = { name = j.action, channels = {} } :: Types.Animation
byAction[j.action] = anim
table.insert(ctx.scene.animations, anim)
end
local lo, hi = Anim.range(j.curves)
local fs = frames(math.floor(lo), math.ceil(hi), step) -- whole frames, as Blender plays them
local times = {}
for i, fr in fs do
times[i] = (fr - zero) / fps
end
local tmp = Scene.new()
if j.kind == "object" then
local node = j.node :: number
local track = { translation = {}, rotation = {}, scale = {} }
local last: { number }? = nil
for _, fr in fs do
local p = apply(ctx.props[node], j.curves, fr, nil, nil)
local t, r, s = Mat4.decompose(Mat4.mul(ctx.prefix[node], objectBasis(p)))
if last and last[1] * r[1] + last[2] * r[2] + last[3] * r[3] + last[4] * r[4] < 0 then
r = { -r[1], -r[2], -r[3], -r[4] }
end
last = r
table.move(t, 1, 3, #track.translation + 1, track.translation)
table.move(r, 1, 4, #track.rotation + 1, track.rotation)
table.move(s, 1, 3, #track.scale + 1, track.scale)
end
local nd = ctx.scene.nodes[node]
if nd.matrix then
local t, r, s = Mat4.decompose(nd.matrix)
nd.translation, nd.rotation, nd.scale, nd.matrix = t, r, s, nil
end
Rig.animation(tmp, nil, { node }, times, { [1] = track :: any }, nil)
elseif j.kind == "pose" then
local info = j.info
local tracks = {}
local touched = {}
for _, c in j.curves do
local kind, who = Anim.split(c.path)
if kind == "pose.bones" and who and info.names[who] then
touched[info.names[who]] = true
end
end
for b in touched do
local name = info.bones[b]:str("name") or ""
local node = info.joints[b]
local track = { translation = {}, rotation = {}, scale = {} }
local last: { number }? = nil
for _, fr in fs do
local p = apply(ctx.props[node], j.curves, fr, "pose.bones", name)
local t, r, s = Mat4.decompose(Mat4.mul(info.restLocal[b], objectBasis(p)))
if last and last[1] * r[1] + last[2] * r[2] + last[3] * r[3] + last[4] * r[4] < 0 then
r = { -r[1], -r[2], -r[3], -r[4] }
end
last = r
table.move(t, 1, 3, #track.translation + 1, track.translation)
table.move(r, 1, 4, #track.rotation + 1, track.rotation)
table.move(s, 1, 3, #track.scale + 1, track.scale)
end
tracks[b] = track
end
Rig.animation(tmp, nil, info.joints, times, tracks :: any, nil)
elseif j.kind == "shapes" then
local sk = ctx.meta.shapeKeys[j.meshIdx]
local count = #sk.shapes - 1
local out = buffer.create(#fs * count * 4)
for i, fr in fs do
local k = 0
for si, s in sk.shapes do
if si ~= sk.ref then
local v = s.value
for _, c in j.curves do
local kind, who, rest = Anim.split(c.path)
if kind == "key_blocks" and who == s.name and rest == "value" then
v = math.clamp(Anim.evaluate(c, fr), math.min(s.min, s.max), math.max(s.min, s.max)) -- the slider range
end
end
buffer.writef32(out, ((i - 1) * count + k) * 4, v)
k += 1
end
end
end
local tb = buffer.create(#times * 4)
for i, t in times do
buffer.writef32(tb, (i - 1) * 4, t)
end
for _, node in j.nodes :: { number } do
table.insert(tmp.animations, { channels = {
{ node = node, path = "weights" :: any, input = Scene.accessor(tb, "f32", 1, #times), output = Scene.accessor(out, "f32", 1, #fs * count), interpolation = "LINEAR" :: any },
} })
end
end
for _, a in tmp.animations do
for _, ch in a.channels do
table.insert(anim.channels, ch)
end
end
end
end
-- ------------------------------------------------------------------------------------------------ entry
local function pickScene(f: Blend.File, name: string?): Blend.View?
local scenes = Blend.blocks(f, "SC")
if name then
for _, b in scenes do
local v = Blend.struct(f, b, 0, "Scene")
if v and v:idName() == name then
return v
end
end
return nil
end
local glob = Blend.blocks(f, "GLOB")[1]
local g = glob and Blend.struct(f, glob, 0, "FileGlobal")
local cur = g and g:target("curscene")
if cur and cur.code == "SC" then
return Blend.struct(f, cur, 0, "Scene")
end
return if scenes[1] then Blend.struct(f, scenes[1], 0, "Scene") else nil
end
function Read.scene(f: Blend.File, opts: Options?): (Types.Scene?, string?)
local o: Options = opts or {}
local scene = Scene.new()
local sc = pickScene(f, o.scene)
if o.scene and not sc then
return nil, "no scene named " .. o.scene
end
local meta: { [string]: any } = {
modifiers = {}, unsupported = {}, generations = {}, shapeKeys = {}, collections = {},
fps = 24, frameStart = 1, render = { aspect = 16 / 9 },
}
local ctx: Ctx = {
f = f, scene = scene, opts = o, objects = {}, objView = {}, parentOf = {}, world = {}, meshes = {}, materials = {},
textures = {}, armatures = {}, prefix = {}, props = {}, meta = meta, pending = {},
}
local order: { { ob: Blend.View, under: number? } } = {}
if sc then
local r = sc:sub("r")
if r then
local fps = (r:num("frs_sec") or 24) / math.max(r:num("frs_sec_base") or 1, 1e-6)
meta.fps = if fps > 0 then fps else 24
meta.frameStart = r:num("sfra") or 1
meta.engine = r:str("engine")
local xs, ys = r:num("xsch") or 1920, r:num("ysch") or 1080
local xa, ya = r:num("xasp") or 1, r:num("yasp") or 1
if xs > 0 and ys > 0 and xa > 0 and ya > 0 then
meta.render = { aspect = (xs * xa) / (ys * ya), width = xs, height = ys }
end
end
local units = sc:sub("unit")
local scale = units and units:num("scale_length")
if scale and scale > 0 then
scene.meta.unit = scale
end
local master = sc:deref("master_collection", 0, "Collection")
if master then
local seen = {}
local function walk(col: Blend.View, under: number?, depth: number)
if depth > 64 or (col.block and seen[col.block.addr]) then
return
end
if col.block then
seen[col.block.addr] = true
end
for _, co in col:list("gobject", "CollectionObject") do
local ob = co:deref("ob", 0, "Object")
if ob then
table.insert(order, { ob = ob, under = under })
end
end
for _, cc in col:list("children", "CollectionChild") do
local child = cc:deref("collection", 0, "Collection")
if child then
local cn: number? = nil
if o.collections ~= false then
cn = addNode(ctx, { name = child:idName(), children = {}, extras = { blend = { collection = true } } }, under)
end
table.insert(meta.collections, child:idName() or "")
walk(child, cn, depth + 1)
end
end
end
walk(master, nil, 0)
else
for _, base in sc:list("base", "Base") do
local ob = base:deref("object", 0, "Object")
if ob then
table.insert(order, { ob = ob, under = nil })
end
end
end
end
if #order == 0 then
for _, b in Blend.blocks(f, "OB") do
local ob = Blend.struct(f, b, 0, "Object")
if ob then
table.insert(order, { ob = ob, under = nil })
end
end
end
local firstUnder: { [any]: number? } = {}
for _, e in order do
local a = e.ob.block and e.ob.block.addr
if a ~= nil and firstUnder[a] == nil then
firstUnder[a] = e.under or 0
end
end
for _, e in order do
local a = e.ob.block and e.ob.block.addr
local u = a ~= nil and firstUnder[a] or nil
object(ctx, e.ob, if u and u > 0 then u else nil, 0)
end
for node = 1, #scene.nodes do
local ob = ctx.objView[node]
if ob and (ob:num("type") or -1) == OB_MESH then
mesh(ctx, ob, node)
end
end
skins(ctx)
if o.animations ~= false then
animations(ctx)
end
meta.shapeKeys = nil
meta.engine = nil
local render = meta.render
meta.render = nil
scene.meta.up = "z"
scene.meta.source = {
format = "blend", version = f.version, subversion = f.subversion, pointerSize = f.pointerSize,
littleEndian = f.little, compression = f.compression, fps = meta.fps, frameStart = meta.frameStart,
frameZero = meta.frameZero, modifiers = meta.modifiers, unsupported = meta.unsupported,
generations = meta.generations, collections = meta.collections, skippedLights = meta.skippedLights,
aspect = render.aspect, scene = sc and sc:idName(),
}
return scene, nil
end
return Read
+94
View File
@@ -0,0 +1,94 @@
--!strict
-- model/blend: Blender .blend files (read only), every version from 2.4x to 5.x: plain, gzip or zstd compressed;
-- 32 / 64-bit pointers, either byte order; the 5.0+ header. New in rosetta (from the file layout, read through each
-- file's own SDNA). Supports: the scene's objects and collections, transforms with parent inverse and bone parents,
-- meshes of every storage generation (MFace, MPoly / MLoop, attribute layers, AttributeStorage) with UV maps, colour
-- attributes, custom normals, material slots; Principled BSDF materials; packed and external images; cameras; lights;
-- armatures, skins (vertex groups, top 4 weights), shape keys; actions sampled into channels.
-- Not supported: modifiers (listed in meta.source.modifiers), curves / text / metaballs / grease pencil / volumes,
-- NLA strips, drivers, constraints, f-curve modifiers, linked libraries, collection instances.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Blend = require("@rosetta/containers/Blend")
local Deflate = require("@rosetta/codecs/compress/Deflate")
local Zstd = require("@rosetta/codecs/compress/Zstd")
local Read = require("@rosetta/model/blend/Read")
local Anim = require("@rosetta/model/blend/Anim")
-- ------------------------------------------------------------------------------------------------ contract
local BlendFormat = {
name = "blend",
category = "model",
extensions = { "blend" },
mime = { "application/x-blender" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" },
caps = { decode = true, encode = false, materials = true, textures = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true, compressed = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
triangulate: boolean?, -- default true (false: "polygons" primitives)
flipV: boolean?, -- default true (glTF's top-left UV origin)
collections: boolean?, -- collections as nodes (default true)
scene: string?, -- a scene by name (default: the file's current scene)
sampleStep: number?, -- frames between animation samples (default 1)
animations: boolean?, -- default true
resolve: ((uri: string) -> any)?, -- external images
files: { [string]: any }?,
maxBytes: number?, -- decompressed size limit (default 2^31)
maxVertices: number?, -- per mesh (default 2^25)
}
-- ------------------------------------------------------------------------------------------------ sniff
-- compressed files: gzip by peeking the first bytes; zstd by decompressing files up to 4 MB (larger zstd streams
-- score 0.5: picked for model loads, the archive otherwise). Ties with archive/gzip and archive/zst go to the extension.
function BlendFormat.sniff(r: Bytes.Reader): number
local head = r:peek(7)
if head == "BLENDER" then
return 1
end
local n = r.limit - r.base
if string.sub(head, 1, 3) == "\31\139\8" then
local inner = Deflate.peek(r.buf, r.base, n, 7)
return if inner and buffer.tostring(inner) == "BLENDER" then 1 else 0
end
if string.sub(head, 1, 4) == Zstd.MAGIC then
if n > 4 * 2 ^ 20 then
return 0.5
end
local out = Zstd.decompress(r.buf, r.base, n, { verify = false })
return if out and buffer.len(out) >= 7 and buffer.readstring(out, 0, 7) == "BLENDER" then 1 else 0
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function BlendFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Blend.File?, Err.Err?)
return Blend.open(r.buf, r.base, r.limit - r.base, { maxBytes = opts and opts.maxBytes })
end
function BlendFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local f, err = BlendFormat.open(r, opts)
if not f then
return nil, err
end
local ok, scene, msg = pcall(Read.scene, f, opts)
if not ok then
return nil, Err.from(tostring(scene))
end
if not scene then
return nil, Err.from(msg or "bad file")
end
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ extras
BlendFormat.container = Blend
BlendFormat.evaluate = Anim.evaluate
BlendFormat.curves = Anim.curves
BlendFormat.ipo = Anim.ipo
return BlendFormat
+294
View File
@@ -0,0 +1,294 @@
-- containers/Blend tests: synthetic files in every header / pointer size / byte order (12-byte header with 4 and 8
-- byte pointers, little and big endian; the 5.0+ 17-byte header with large block heads), structs by name, arrays,
-- pointers, ListBase walks, addresses reused between IDs, gzip; the real files of tools/fixtures/blend.py (headers,
-- versions, zstd); errors; the fuzz pass.
local T = require("@tests/T")
local Blend = require("@rosetta/containers/Blend")
local Deflate = require("@rosetta/codecs/compress/Deflate")
local Err = require("@rosetta/core/Err")
local Cur = require("@tests/gen/blend_cur")
local Old = require("@tests/gen/blend_293")
local t = T.suite("containers/Blend")
-- a writer of either byte order
local function writer(little: boolean)
local parts: { string } = {}
local w = {}
local function bytes(v: number, n: number): string
local s = {}
for k = 0, n - 1 do
s[k + 1] = string.char(math.floor(v / 256 ^ k) % 256)
end
local str = table.concat(s)
return if little then str else string.reverse(str)
end
function w.u8(v: number)
table.insert(parts, string.char(v))
end
function w.i16(v: number)
table.insert(parts, bytes(v % 65536, 2))
end
function w.i32(v: number)
table.insert(parts, bytes(v % 4294967296, 4))
end
function w.u64(v: number)
table.insert(parts, bytes(v, 8))
end
function w.f32(v: number)
local b = buffer.create(4)
buffer.writef32(b, 0, v)
local s = buffer.tostring(b)
table.insert(parts, if little then s else string.reverse(s))
end
function w.f64(v: number)
local b = buffer.create(8)
buffer.writef64(b, 0, v)
local s = buffer.tostring(b)
table.insert(parts, if little then s else string.reverse(s))
end
function w.str(s: string)
table.insert(parts, s)
end
function w.ptr(v: number, ps: number)
if ps == 8 then
w.u64(v)
else
w.i32(v)
end
end
function w.done(): string
return table.concat(parts)
end
return w
end
-- SDNA: ListBase { void *first, *last }; Thing { Thing *next, *prev; int a; float b[2]; char name[8]; short s;
-- char pad[2]; void *data }; Holder { ListBase things; Thing *one; double d; ID-less }
local NAMES = { "*first", "*last", "*next", "*prev", "a", "b[2]", "name[8]", "s", "pad[2]", "*data", "things", "*one", "d" }
local TYPES = { "char", "short", "int", "float", "double", "void", "ListBase", "Thing", "Holder" }
local function sdna(little: boolean, ps: number): string
local w = writer(little)
local function pad()
local s = w.done()
return (4 - #s % 4) % 4
end
w.str("SDNA")
w.str("NAME")
w.i32(#NAMES)
for _, n in NAMES do
w.str(n .. "\0")
end
for _ = 1, pad() do
w.u8(0)
end
w.str("TYPE")
w.i32(#TYPES)
for _, n in TYPES do
w.str(n .. "\0")
end
for _ = 1, pad() do
w.u8(0)
end
w.str("TLEN")
local thing = ps * 2 + 4 + 8 + 8 + 2 + 2 + ps
for _, l in { 1, 2, 4, 4, 8, 0, ps * 2, thing, ps * 2 + ps + 8 } do
w.i16(l)
end
for _ = 1, pad() do
w.u8(0)
end
w.str("STRC")
w.i32(3)
local function struct(ty: number, fields: { { number } })
w.i16(ty)
w.i16(#fields)
for _, f in fields do
w.i16(f[1])
w.i16(f[2])
end
end
-- type / name indices are 0-based
struct(6, { { 5, 0 }, { 5, 1 } })
struct(7, { { 7, 2 }, { 7, 3 }, { 2, 4 }, { 3, 5 }, { 0, 6 }, { 1, 7 }, { 0, 8 }, { 5, 9 } })
struct(8, { { 6, 10 }, { 7, 11 }, { 4, 12 } })
return w.done()
end
local function file(little: boolean, ps: number, large: boolean, dupe: boolean?): string
local w = writer(little)
if large then
w.str("BLENDER17-01v0502")
else
w.str("BLENDER" .. (if ps == 8 then "-" else "_") .. (if little then "v" else "V") .. "279")
end
local function head(code: string, size: number, addr: number, sdnaIndex: number, count: number)
w.str(code .. string.rep("\0", 4 - #code))
if large then
w.i32(sdnaIndex)
w.u64(addr)
w.u64(size)
w.u64(count)
else
w.i32(size)
w.ptr(addr, ps)
w.i32(sdnaIndex)
w.i32(count)
end
end
local thingSize = ps * 2 + 24 + ps
head("HO", ps * 3 + 8, 0x1000, 2, 1)
w.ptr(0x2000, ps) -- things.first
w.ptr(0x3000, ps) -- things.last
w.ptr(0x3000, ps) -- one
w.f64(2.5)
local function thing(next: number, prev: number, a: number, b1: number, b2: number, name: string, s: number, data: number)
w.ptr(next, ps)
w.ptr(prev, ps)
w.i32(a)
w.f32(b1)
w.f32(b2)
w.str(name .. string.rep("\0", 8 - #name))
w.i16(s)
w.str("\0\0")
w.ptr(data, ps)
end
head("DATA", thingSize, 0x2000, 1, 1)
thing(0x3000, 0, -7, 1.5, -2.25, "first", -300, 0x4000)
head("DATA", thingSize, 0x3000, 1, 1)
thing(0, 0x2000, 123456, 0.5, 4, "second!", 1234, 0)
head("DATA", 6, 0x4000, 0, 1)
w.str("hello\0")
if dupe then
-- a second ID whose own data reuses the address 0x4000
head("H2", ps * 3 + 8, 0x5000, 2, 1)
w.ptr(0, ps)
w.ptr(0, ps)
w.ptr(0x4000, ps)
w.f64(-1)
head("DATA", thingSize, 0x4000, 1, 1)
thing(0, 0, 99, 0, 0, "dup", 0, 0)
end
local dna = sdna(little, ps)
head("DNA1", #dna, 0x9000, 0, 1)
w.str(dna)
head("ENDB", 0, 0, 0, 0)
return w.done()
end
for _, v in { { true, 8, false }, { true, 4, false }, { false, 8, false }, { false, 4, false }, { true, 8, true } } do
local little, ps, large = v[1], v[2], v[3]
local label = string.format("%s-endian, %d-byte pointers%s", if little then "little" else "big", ps, if large then ", 5.0 header" else "")
local f, err = Blend.open(buffer.fromstring(file(little, ps, large)))
t:check(f, label .. ": open: " .. tostring(err))
if not f then
continue
end
t:eq(f.pointerSize, ps, label .. ": pointer size")
t:eq(f.little, little, label .. ": byte order")
t:eq(f.version, if large then 502 else 279, label .. ": version")
t:eq(f.format, if large then 1 else 0, label .. ": format")
t:eq(#f.blocks, 5, label .. ": blocks (ENDB not listed)")
t:eq(f.dna.byName.Thing.size, ps * 3 + 24, label .. ": struct size from TLEN")
t:eq(f.dna.byName.Thing.byName.data.offset, ps * 2 + 24, label .. ": field offsets")
local ho = assert(Blend.struct(f, Blend.blocks(f, "HO")[1]))
t:eq(ho:num("d"), 2.5, label .. ": double")
local list = ho:list("things")
t:eq(#list, 2, label .. ": ListBase walk")
t:eq(list[1]:num("a"), -7, label .. ": int")
t:eq(list[2]:num("a"), 123456, label .. ": int 2")
t:eq(list[1]:num("s"), -300, label .. ": short")
t:eq(list[1]:str("name"), "first", label .. ": char array")
t:eq(list[2]:str("name"), "second!", label .. ": char array 2")
local b = list[1]:vec("b")
t:check(b and b[1] == 1.5 and b[2] == -2.25, label .. ": float array")
t:eq(list[1]:cstring("data"), "hello", label .. ": pointer to raw data")
local one = ho:deref("one")
t:check(one and one:num("a") == 123456, label .. ": deref by field type")
t:check(ho:ptr("one") ~= nil and list[2]:ptr("next") == nil, label .. ": null pointers are nil")
t:check(ho:get("missing") == nil and ho:has("d") and not ho:has("missing"), label .. ": unknown fields")
t:eq(ho:num("missing", "d"), 2.5, label .. ": the first existing of several names")
local fld = Blend.field(f, "Thing", "nope", "b")
t:check(fld and fld.count == 2 and fld.type == "float" and #fld.dims == 1, label .. ": Blend.field")
end
-- an address reused by another ID's data resolves inside the ID that points at it
do
local f = assert(Blend.open(buffer.fromstring(file(true, 8, false, true))))
local h1 = assert(Blend.struct(f, Blend.blocks(f, "HO")[1]))
local h2 = assert(Blend.struct(f, Blend.blocks(f, "H2")[1]))
t:eq(h1:list("things")[1]:cstring("data"), "hello", "reused address: the first ID's raw data")
local d = h2:deref("one")
t:check(d and d:num("a") == 99 and d:str("name") == "dup", "reused address: the second ID's own block")
end
-- gzip (Blender before 3.0)
do
local raw = file(true, 8, false)
local gz = assert(Deflate.gzip(raw))
local f, err = Blend.open(gz)
t:check(f and f.compression == "gzip" and #f.blocks == 5, "gzip: " .. tostring(err))
t:eq(Blend.sniff(gz), 0.05, "gzip sniffs weakly")
t:eq(Blend.sniff(buffer.fromstring(raw)), 1, "magic")
end
-- the real files: headers and compression
for _, set in { Cur, Old } do
for _, c in set do
local f, err = Blend.open(buffer.fromstring(c.data))
t:check(f, c.name .. ": " .. tostring(err))
if f then
local want = c.ref.version[1] * 100 + c.ref.version[2]
t:eq(f.version, want, c.name .. ": version")
t:eq(f.format, if want >= 500 then 1 else 0, c.name .. ": header format")
if string.find(c.name, "_z%.blend$") then
t:eq(f.compression, if want >= 300 then "zstd" else "gzip", c.name .. ": compression")
end
t:check(f.dna.byName.Object and f.dna.byName.Mesh and #Blend.blocks(f, "OB") > 0, c.name .. ": SDNA and objects")
end
end
end
-- errors
local function code(s: string): string?
local f, e = Blend.open(buffer.fromstring(s))
return if f then nil else e.code
end
local good = file(true, 8, false)
t:eq(code("BLEND"), Err.TRUNCATED, "short file")
t:eq(code("NOTBLEND-v279" .. string.rep("\0", 40)), Err.CORRUPT, "bad magic")
t:eq(code(string.sub(good, 1, #good - 30)), Err.TRUNCATED, "no ENDB")
t:eq(code("BLENDER17-02v0502" .. string.rep("\0", 40)), Err.UNSUPPORTED, "unknown header format version")
local noDna = string.gsub(good, "DNA1", "DNA2")
t:eq(code(noDna), Err.CORRUPT, "no DNA1")
local badDna = string.gsub(good, "STRC", "STRX")
t:eq(code(badDna), Err.CORRUPT, "bad SDNA")
local _, e = Blend.open(buffer.fromstring(good), 0, 999999)
t:eq(e and e.code, Err.ARG, "bad range")
local samples = { good, file(false, 4, false), file(true, 8, true, true) }
t:fuzz("open", function(b: buffer)
local f = Blend.open(b)
if f then
for _, blk in f.blocks do
local v = Blend.struct(f, blk)
if v then
for _, fld in v.struct.fields do
local x = v:get(fld.name)
if fld.pointer then
v:deref(fld.name)
v:array(fld.name)
v:pointers(fld.name)
v:cstring(fld.name)
elseif fld.type == "ListBase" then
v:list(fld.name)
end
local _ = x
end
end
end
end
return f
end, samples, { mutations = 64 })
t:done()
+652
View File
@@ -0,0 +1,652 @@
-- model/blend tests: scenes saved by Blender 2.79, 2.93, 3.5, 4.1 and 5.x (plain, gzip, zstd; the 2.79 legacy mesh
-- format) against the current Blender's own values for the same files (world matrices, mesh counts, bounds, UV / colour
-- sums, corner normals, weights, shape keys, f-curve values, posed matrices per frame, skinned positions) and its
-- glTF exporter (materials, cameras, lights, skins, triangle counts). Fixtures: tools/fixtures/blend.py.
local T = require("@tests/T")
local F = require("@rosetta")
local B = require("@rosetta/model/blend")
local Blend = require("@rosetta/containers/Blend")
local Bytes = require("@rosetta/core/Bytes")
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Mat4 = require("@rosetta/codecs/model/Mat4")
local Sampler = require("@rosetta/codecs/model/Sampler")
local Versions = require("@tests/gen/blend_versions")
local Files = require("@tests/gen/blend_files")
local Sets = {
["279"] = require("@tests/gen/blend_279"),
["293"] = require("@tests/gen/blend_293"),
["35"] = require("@tests/gen/blend_35"),
["41"] = require("@tests/gen/blend_41"),
cur = require("@tests/gen/blend_cur"),
old = require("@tests/gen/blend_old"), -- Blender 1.66 - 2.04 demo files (big-endian among them)
}
local t = T.suite("blend")
local Scene = Types.Scene
t:eq(B.name, "blend", "name")
t:eq(B.category, "model", "category")
t:check(B.caps.decode and not B.caps.encode, "read only")
t:eq(#Versions, 5, "every Blender version made its files (" .. table.concat(Versions, " ") .. ")")
local function decode(data: string, opts: any?): (any, any)
return B.decode(Bytes.reader(buffer.fromstring(data)), opts)
end
local function near(a: number, b: number, eps: number): boolean
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
end
local function nearList(a: { number }?, b: { number }?, eps: number): boolean
if not a or not b or #a ~= #b then
return false
end
for i = 1, #a do
if not near(a[i], b[i], eps) then
return false
end
end
return true
end
local function fmt(m: { number }?): string
if not m then
return "nil"
end
local s = {}
for i, v in m do
s[i] = string.format("%.4f", v)
end
return table.concat(s, " ")
end
-- world matrices of every node, with an optional pose ({ [node] = { translation, rotation, scale, weights } })
local function worlds(scene: any, pose: any?): { [number]: { number } }
local out = {}
local function walk(i: number, parent: { number })
local n = scene.nodes[i]
local p = pose and pose[i]
local m
if p then
local base = if n.matrix then { Mat4.decompose(n.matrix) } else { n.translation, n.rotation, n.scale }
m = Mat4.compose(p.translation or base[1], p.rotation or base[2], p.scale or base[3])
else
m = Scene.nodeMatrix(n)
end
local w = Scene.mul(parent, m)
out[i] = w
for _, c in n.children do
walk(c, w)
end
end
for _, r in scene.roots do
walk(r, Mat4.identity())
end
return out
end
local function byName(scene: any): ({ [string]: number }, { [string]: number })
local objects, bones = {}, {}
for i, n in scene.nodes do
local e = n.extras and n.extras.blend
if e and e.bone then
bones[n.name] = i
elseif e and e.type then
objects[n.name] = i
end
end
return objects, bones
end
local function read(acc: any): (number, number) -> number
return assert(Scene.reader(acc))
end
-- the corners of the polygons decode in Blender's loop order: { prim, vertex } per corner
local function corners(mesh: any, facemats: { number }, faceSizes: { number }?): { { any } }?
local slots = {}
local cursor = {}
for _, p in mesh.primitives do
table.insert(slots, p)
end
local used = {}
for _, m in facemats do
used[m] = true
end
local order = {}
for m in used do
table.insert(order, m)
end
table.sort(order)
local primOf = {}
for k, m in order do
primOf[m] = slots[k]
end
local out = {}
for fi, m in facemats do
local p = primOf[m]
if not p or not p.faces then
return nil
end
local c = cursor[p] or { face = 0, at = 0 }
cursor[p] = c
local size = buffer.readu32(p.faces.data, c.face * 4)
if faceSizes and faceSizes[fi] ~= size then
return nil
end
for k = 0, size - 1 do
table.insert(out, { p, buffer.readu32(p.indices.data, (c.at + k) * 4) })
end
c.face += 1
c.at += size
end
return out
end
local checked = { worlds = 0, meshes = 0, normals = 0, weights = 0, shapes = 0, frames = 0, skinned = 0, curves = 0, materials = 0, cameras = 0, lights = 0 }
local samples = {}
t:check(#Sets.old >= 4, "the old demo files were fetched (" .. #Sets.old .. ")")
for _, tag in { "old", "279", "293", "35", "41", "cur" } do
for _, c in Sets[tag] do
local ref = c.ref
local label = c.name
local scene, err = decode(c.data, { files = Files })
t:check(scene, label .. ": decode: " .. tostring(err))
if not scene then
continue
end
if #c.data < 500000 and #samples < 2 then
table.insert(samples, c.data)
end
local src = scene.meta.source
t:eq(src.format, "blend", label .. ": meta.source.format")
t:eq(scene.meta.up, "z", label .. ": z up")
if string.find(label, "_z%.blend$") then
t:eq(src.compression, if src.version < 300 then "gzip" else "zstd", label .. ": compression")
end
local objects, bones = byName(scene)
local W = worlds(scene)
-- objects: world matrices at the saved frame
for _, o in ref.objects do
local i = objects[o.name]
t:check(i, label .. ": object " .. o.name)
if i then
t:check(nearList(W[i], o.world, 1e-4), label .. ": " .. o.name .. " world\n got " .. fmt(W[i]) .. "\n want " .. fmt(o.world))
checked.worlds += 1
end
end
-- meshes
local polyScene = decode(c.data, { triangulate = false })
local polyObjects = polyScene and byName(polyScene)
for _, o in ref.objects do
local mi = o.mesh
local i = objects[o.name]
if not mi or not i then
continue
end
local node = scene.nodes[i]
local mesh = scene.meshes[node.mesh]
t:check(mesh, label .. ": " .. o.name .. " has a mesh")
if not mesh then
continue
end
local e = mesh.extras.blend
t:eq(e.vertices, mi.vertices, label .. ": " .. o.name .. " vertices")
local tris = 0
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
for _, p in mesh.primitives do
tris += p.indices.count // 3
local P = read(p.attributes.POSITION)
for v = 0, p.attributes.POSITION.count - 1 do
for k = 1, 3 do
lo[k] = math.min(lo[k], P(v, k - 1))
hi[k] = math.max(hi[k], P(v, k - 1))
end
end
end
t:eq(tris, mi.triangles, label .. ": " .. o.name .. " triangles")
if e.generation == "mface" then
-- the 2.7x legacy save drops n-gons, leaving their vertices loose: inside the bounds
local inside = true
for k = 1, 3 do
inside = inside and lo[k] >= mi.min[k] - 1e-5 and hi[k] <= mi.max[k] + 1e-5
end
t:check(inside, label .. ": " .. o.name .. " bounds")
else
t:check(nearList(lo, mi.min, 1e-5) and nearList(hi, mi.max, 1e-5), label .. ": " .. o.name .. " bounds")
end
t:eq(e.faces, mi.faces, label .. ": " .. o.name .. " faces")
t:eq(e.corners, mi.corners, label .. ": " .. o.name .. " corners")
t:eq(#mesh.primitives, (function()
local u, n = {}, 0
for _, m in mi.facemats do
if not u[m] then
u[m] = true
n += 1
end
end
return n
end)(), label .. ": " .. o.name .. " one primitive per used slot")
checked.meshes += 1
-- corner level (the polygons decode, in Blender's loop order)
local pm = polyScene and polyScene.meshes[polyScene.nodes[polyObjects[o.name]].mesh]
local cs = pm and corners(pm, mi.facemats)
t:check(cs and #cs == mi.corners, label .. ": " .. o.name .. " corners in loop order")
if not cs then
continue
end
for k, uv in mi.uvs do
local su, sv = 0, 0
for _, cv in cs do
local acc = cv[1].attributes["TEXCOORD_" .. (k - 1)]
if acc then
local get = read(acc)
su += get(cv[2], 0)
sv += 1 - get(cv[2], 1)
end
end
t:check(near(su, uv.sum[1], 1e-4) and near(sv, uv.sum[2], 1e-4), label .. ": " .. o.name .. " uv " .. uv.name .. " sums " .. su .. " " .. sv)
end
for _, col in mi.colors do
local s = { 0, 0, 0, 0 }
local found = false
for _, cv in cs do
for name, acc in cv[1].attributes do
if string.sub(name, 1, 6) == "COLOR_" and acc.name == col.name then
found = true
local get = read(acc)
for k = 1, 4 do
s[k] += get(cv[2], k - 1)
end
end
end
end
t:check(found and nearList(s, col.cornerSum, 1e-3), label .. ": " .. o.name .. " colour " .. col.name .. " " .. fmt(s) .. " / " .. fmt(col.cornerSum))
end
if mi.normals then
local worst = 0
for ci, cv in cs do
local get = read(cv[1].attributes.NORMAL)
local want = mi.normals[ci]
for k = 1, 3 do
worst = math.max(worst, math.abs(get(cv[2], k - 1) - want[k]))
end
end
t:check(worst < (if mi.custom then 2e-3 else 1e-4), label .. ": " .. o.name .. " corner normals (worst " .. string.format("%.2g", worst) .. (if mi.custom then ", custom" else "") .. ")")
checked.normals += 1
end
-- deform weights: the deform bones' groups, top 4 normalized
local arm = nil
for _, a in ref.armatures do
arm = a
end
if mi.weights and arm and node.skin then
local deform = {}
for _, b in arm do
deform[b.name] = b.deform
end
local skin = scene.skins[node.skin]
local jointOf = {}
for j, n in skin.joints do
jointOf[scene.nodes[n].name] = j - 1
end
local bad = 0
for ci, cv in cs do
local list = {}
for _, g in mi.weights[mi.cornerVerts[ci] + 1] do
if deform[g[1]] and g[2] > 0 then
table.insert(list, { jointOf[g[1]], g[2] })
end
end
table.sort(list, function(a, b)
return a[2] > b[2]
end)
local sum = 0
for k = 1, math.min(4, #list) do
sum += list[k][2]
end
local J, Wt = read(cv[1].attributes.JOINTS_0), read(cv[1].attributes.WEIGHTS_0)
for k = 1, math.min(4, #list) do
local ok = false
for q = 0, 3 do
if J(cv[2], q) == list[k][1] and near(Wt(cv[2], q), list[k][2] / sum, 1e-5) then
ok = true
end
end
if not ok then
bad += 1
end
end
end
t:eq(bad, 0, label .. ": " .. o.name .. " joints / weights per corner")
checked.weights += 1
end
if mi.shapes then
local refIndex = 1
for k, s in mi.shapes do
if s.name == mi.reference then
refIndex = k
end
end
t:eq(#(mesh.weights or {}), #mi.shapes - 1, label .. ": " .. o.name .. " morph weights")
local ti = 0
local worst = 0
for k, s in mi.shapes do
if k ~= refIndex then
ti += 1
if not o.shapeAction then -- animated values are checked per frame below
t:check(near(mesh.weights[ti], s.value, 1e-6), label .. ": " .. o.name .. " " .. s.name .. " weight")
end
for ci, cv in if mi.cornerVerts then cs else {} do
local tgt = cv[1].targets and cv[1].targets[ti]
local get = tgt and read(tgt.POSITION)
local v = mi.cornerVerts[ci]
for q = 1, 3 do
local want = s.co[v * 3 + q] - mi.shapes[refIndex].co[v * 3 + q]
worst = math.max(worst, if get then math.abs(get(cv[2], q - 1) - want) else math.huge)
end
end
end
end
t:check(worst < 1e-5, label .. ": " .. o.name .. " shape key deltas (worst " .. worst .. ")")
checked.shapes += 1
end
end
-- materials against the glTF exporter (Principled) or the legacy colour
local gl = ref.gltf or {}
local glMats = {}
for _, m in gl.materials or {} do
glMats[m.name] = m
end
for _, m in scene.materials do
local g = glMats[m.name]
if m.extras.blend.principled and g then
local pbr = g.pbrMetallicRoughness or {}
t:check(nearList(m.baseColor, pbr.baseColorFactor or { 1, 1, 1, 1 }, 1e-5), label .. ": " .. m.name .. " base colour " .. fmt(m.baseColor))
t:check(near(m.metallic, pbr.metallicFactor or 1, 1e-5) and near(m.roughness, pbr.roughnessFactor or 1, 1e-5), label .. ": " .. m.name .. " metallic / roughness")
t:check(nearList(m.emissive, g.emissiveFactor or { 0, 0, 0 }, 1e-5), label .. ": " .. m.name .. " emissive " .. fmt(m.emissive))
local ges = g.extensions and g.extensions.KHR_materials_emissive_strength
local es = m.extensions and m.extensions.KHR_materials_emissive_strength
t:check(near(es and es.emissiveStrength or 1, ges and ges.emissiveStrength or 1, 1e-5), label .. ": " .. m.name .. " emissive strength")
t:eq(string.upper(m.alphaMode), g.alphaMode or "OPAQUE", label .. ": " .. m.name .. " alpha mode")
t:eq(m.baseColorTexture ~= nil, pbr.baseColorTexture ~= nil, label .. ": " .. m.name .. " base colour texture")
t:eq(m.emissiveTexture ~= nil, g.emissiveTexture ~= nil, label .. ": " .. m.name .. " emissive texture")
t:eq(m.normalTexture ~= nil, g.normalTexture ~= nil, label .. ": " .. m.name .. " normal texture")
if g.normalTexture and m.normalTexture then
t:check(near(m.normalTexture.scale, g.normalTexture.scale or 1, 1e-5), label .. ": " .. m.name .. " normal scale")
end
checked.materials += 1
elseif not m.extras.blend.principled then
for _, rm in ref.materials do
if rm.name == m.name then
t:check(nearList({ m.baseColor[1], m.baseColor[2], m.baseColor[3] }, { rm.diffuse[1], rm.diffuse[2], rm.diffuse[3] }, 1e-5), label .. ": " .. m.name .. " legacy colour")
checked.materials += 1
end
end
end
end
-- images: packed bytes, external uris (with the bytes from opts.files)
for _, im in ref.images do
local tex = nil
for _, x in scene.textures do
if x.name == im.name then
tex = x
end
end
if not tex then
continue -- not used by a node material (legacy texture slots, face images)
elseif im.packed > 0 then
t:check(tex.data and buffer.len(tex.data) == im.packed and (tag == "old" or tex.mime == "image/png"), label .. ": packed image " .. im.name)
else
t:eq(tex.uri, "outside.png", label .. ": external image uri")
t:check(tex.data and buffer.len(tex.data) == #Files["outside.png"], label .. ": external image bytes through opts.files")
end
end
-- cameras and lights against the glTF exporter
for _, gc in gl.cameras or {} do
local cam = nil
for _, x in scene.cameras do
if x.name == gc.name then
cam = x
end
end
t:check(cam, label .. ": camera " .. gc.name)
if cam then
if gc.type == "perspective" then
t:check(cam.type == "perspective" and near(cam.yfov, gc.perspective.yfov, 1e-5) and near(cam.znear, gc.perspective.znear, 1e-5) and near(cam.zfar, gc.perspective.zfar, 1e-5), label .. ": perspective " .. gc.name)
else
t:check(cam.type == "orthographic" and near(cam.xmag, gc.orthographic.xmag, 1e-5) and near(cam.ymag, gc.orthographic.ymag, 1e-5), label .. ": orthographic " .. gc.name)
end
checked.cameras += 1
end
end
local glLights = gl.extensions and gl.extensions.KHR_lights_punctual and gl.extensions.KHR_lights_punctual.lights or {}
t:eq(#scene.lights, #glLights, label .. ": lights (the area light is skipped)")
for _, gli in glLights do
local l = nil
for _, x in scene.lights do
if x.name == gli.name then
l = x
end
end
t:check(l and l.type == gli.type and near(l.intensity, gli.intensity, 1e-5) and nearList(l.color, gli.color, 1e-5), label .. ": light " .. gli.name .. " " .. (l and l.intensity or -1) .. " " .. gli.intensity)
if l and gli.spot then
t:check(near(l.outerCone, gli.spot.outerConeAngle, 1e-5) and near(l.innerCone, gli.spot.innerConeAngle, 1e-5), label .. ": spot cones")
end
checked.lights += 1
end
-- triangles: the glTF exporter's meshes
local curves = false -- the exporter turns curves / text / surfaces / metaballs into meshes; we do not
for _, o in ref.objects do
curves = curves or o.type == "CURVE" or o.type == "FONT" or o.type == "SURFACE" or o.type == "META"
end
if gl.meshes and not curves then
-- per instance (both sides share meshes differently)
local want = 0
for _, n in gl.nodes or {} do
if n.mesh then
for _, p in gl.meshes[n.mesh + 1].primitives do
want += gl.accessors[p.indices + 1].count // 3
end
end
end
local got = 0
for _, n in scene.nodes do
if n.mesh then
for _, p in scene.meshes[n.mesh].primitives do
got += p.indices.count // 3
end
end
end
t:eq(got, want, label .. ": triangles (glTF exporter)")
end
t:eq(#scene.skins, #(gl.skins or {}), label .. ": skins (glTF exporter)")
for k, s in scene.skins do
t:eq(#s.joints, #gl.skins[k].joints, label .. ": skin joints")
end
-- bones at the saved frame (the rest pose here)
for armName, list in ref.armatures do
local aw = W[objects[armName]]
for _, b in list do
local j = bones[b.name]
t:check(j and nearList(W[j], Scene.mul(aw, b["local"]), 1e-4), label .. ": bone " .. b.name)
end
end
-- f-curves through the evaluator, at every half frame (bezier, linear, constant, extrapolation)
local file = assert(Blend.open(buffer.fromstring(c.data)))
for _, o in ref.objects do
local refCurves = o.action and ref.actions[o.action]
if refCurves then
local ob = nil
for _, blk in Blend.blocks(file, "OB") do
local v = Blend.struct(file, blk)
if v and v:idName() == o.name then
ob = v
end
end
local curves = B.curves(file, ob and ob:deref("adt", 0, "AnimData"))
if not curves and ob and not ob:has("adt") then
curves = B.ipo(file, ob:deref("ipo", 0, "Ipo")) -- before 2.5
end
curves = curves or {}
for _, rc in refCurves do
local p = rc.path
if not (p == "location" or p == "scale" or string.find(p, "rotation") or string.find(p, "^delta_")) then
continue -- only the transform curves are read
end
local cur = nil
for _, x in curves do
if x.path == rc.path and x.index == rc.index then
cur = x
end
end
local worst = 0
for k, want in rc.values do
local got = if cur then B.evaluate(cur, 1 + 0.5 * (k - 1)) else math.huge
worst = math.max(worst, math.abs(got - want))
end
t:check(worst < 1e-4, label .. ": " .. o.name .. " " .. rc.path .. "[" .. rc.index .. "] (worst " .. worst .. ")")
checked.curves += 1
end
end
end
-- the animations sampled at whole frames: posed world matrices, bones, shape key values, skinned positions
if #ref.poses > 0 then
local animated = false -- transform or shape key curves (others, such as an object colour, are not read)
for _, list in ref.actions do
for _, rc in list do
local p = rc.path
animated = animated or p == "location" or p == "scale" or string.find(p, "rotation") ~= nil or string.find(p, "key_blocks") ~= nil
end
end
t:check(#scene.animations > 0 or not animated, label .. ": animations")
local caches = {}
for _, p in ref.poses do
local frame = p.frame
if frame ~= math.floor(frame) or frame > 20 then
continue
end
local time = (frame - (src.frameZero or src.frameStart)) / src.fps
local pose = {}
for ai, a in scene.animations do
caches[ai] = caches[ai] or {}
for node, v in Sampler.pose(scene, a, time, caches[ai]) do
pose[node] = pose[node] or {}
for k, x in v do
pose[node][k] = x
end
end
end
local PW = worlds(scene, pose)
for name, want in p.objects do
local i = objects[name]
t:check(i and nearList(PW[i], want, 1e-3), label .. ": frame " .. frame .. " " .. name .. "\n got " .. fmt(i and PW[i]) .. "\n want " .. fmt(want))
end
for key, want in p.bones do
local j = bones[string.match(key, "/(.+)$")]
t:check(j and nearList(PW[j], want, 1e-3), label .. ": frame " .. frame .. " bone " .. key)
end
for name, values in p.shapes do
local i = objects[name]
local w = pose[i] and pose[i].weights or scene.nodes[i].weights
local want = table.move(values, 2, #values, 1, {})
-- pre-2.5 IPO bezier keys: Blender recomputes auto handles when converting them; we keep the stored ones
local eps = if tag == "old" then 1e-2 else 1e-3
t:check(nearList(w, want, eps), label .. ": frame " .. frame .. " " .. name .. " shape values " .. fmt(w) .. " / " .. fmt(want))
end
for name, want in p.skinned or {} do
-- morph, then skin: sum of w * jointWorld * inverseBind * position
local i = objects[name]
local node = polyScene.nodes[polyObjects[name]]
local mi = nil
for _, o in ref.objects do
if o.name == name then
mi = o.mesh
end
end
local pm = polyScene.meshes[node.mesh]
local cs = corners(pm, mi.facemats)
local skin = scene.skins[scene.nodes[i].skin]
local IB = read(skin.inverseBindMatrices)
local weights = pose[i] and pose[i].weights or scene.nodes[i].weights or {}
local worst = 0
for ci, cv in cs do
local P = read(cv[1].attributes.POSITION)
local x, y, z = P(cv[2], 0), P(cv[2], 1), P(cv[2], 2)
for ti, tg in cv[1].targets or {} do
local D = read(tg.POSITION)
x += D(cv[2], 0) * (weights[ti] or 0)
y += D(cv[2], 1) * (weights[ti] or 0)
z += D(cv[2], 2) * (weights[ti] or 0)
end
local J, Wt = read(cv[1].attributes.JOINTS_0), read(cv[1].attributes.WEIGHTS_0)
local ox, oy, oz = 0, 0, 0
for q = 0, 3 do
local w = Wt(cv[2], q)
if w > 0 then
local j = J(cv[2], q)
local ib = {}
for k = 0, 15 do
ib[k + 1] = IB(j, k)
end
local m = Scene.mul(PW[skin.joints[j + 1]], ib)
local px, py, pz = Mat4.point(m, x, y, z)
ox += w * px
oy += w * py
oz += w * pz
end
end
local v = mi.cornerVerts[ci]
worst = math.max(worst, math.abs(ox - want[v * 3 + 1]), math.abs(oy - want[v * 3 + 2]), math.abs(oz - want[v * 3 + 3]))
end
t:check(worst < 1e-3, label .. ": frame " .. frame .. " " .. name .. " skinned positions (worst " .. worst .. ")")
checked.skinned += 1
end
checked.frames += 1
end
end
end
end
t:note("checked: %d world matrices, %d meshes, %d corner normal sets, %d weight sets, %d shape key sets, %d f-curves, %d posed frames, %d skinned frames, %d materials, %d cameras, %d lights",
checked.worlds, checked.meshes, checked.normals, checked.weights, checked.shapes, checked.curves, checked.frames, checked.skinned, checked.materials, checked.cameras, checked.lights)
-- the api: by extension and magic, compressed files included
local cur = Sets.cur[1]
if cur then
t:eq(F.detect(buffer.fromstring(cur.data)), "blend", "F.detect")
local s = F.load(buffer.fromstring(cur.data))
t:check(s and s.kind == "scene", "F.load")
end
-- compressed files: by content for model loads, by extension otherwise
for _, c in Sets.cur do
if string.find(c.name, "_z%.blend$") then
local b = buffer.fromstring(c.data)
local s = F.model.load(b)
t:check(s and s.meta.source.compression == "zstd", "F.model.load of a zstd .blend")
t:eq(F.detect(b, { name = "x.blend" }), "blend", "F.detect of a zstd .blend by name")
end
end
for _, c in Sets["293"] do
if string.find(c.name, "_z%.blend$") then
local s = F.model.load(buffer.fromstring(c.data))
t:check(s and s.meta.source.compression == "gzip", "F.model.load of a gzip .blend")
end
end
-- errors
local function code(data: string): string?
local s, e = decode(data)
return if s then nil else e.code
end
t:eq(code("BLENDER"), Err.TRUNCATED, "a 7-byte file is truncated")
t:eq(code("BLENDER-v279REND"), Err.TRUNCATED, "a truncated block header")
t:eq(code("BLENDERxv279" .. string.rep("\0", 24)), Err.CORRUPT, "bad pointer size")
t:eq(code("BLENDER-v279ENDB" .. string.rep("\0", 20)), Err.CORRUPT, "no DNA1 block")
t:fuzz("decode", function(b: buffer)
return B.decode(Bytes.reader(b))
end, samples, { mutations = 24 })
t:done()
+9
View File
@@ -961,6 +961,15 @@ do
bench("fbx ascii decode (" .. buffer.len(fbxa) // 1000 .. " KB)", 2, buffer.len(fbxa), function()
Fbx.decode(Bytes.reader(fbxa))
end)
local BlendFmt = require("@rosetta/model/blend")
for _, c in require("@tests/gen/blend_cur") do
if c.name == "rig_52.blend" or c.name == "scene_52_z.blend" then
local bb = buffer.fromstring(c.data)
bench("blend decode " .. c.name .. " (" .. buffer.len(bb) // 1000 .. " KB)", 5, buffer.len(bb), function()
BlendFmt.decode(Bytes.reader(bb))
end)
end
end
local ThreeMf = require("@rosetta/model/3mf")
local tmf = assert(ThreeMf.encode(scene))
bench("3mf decode (" .. buffer.len(tmf) // 1000 .. " KB zipped)", 2, buffer.len(tmf), function()
+402
View File
@@ -0,0 +1,402 @@
# tools/fixtures/_blend_make: run by tools/fixtures/blend.py inside Blender 2.79 .. 5.x (blender -b --python <this> --
# <outdir>): builds the test scenes with whatever API the running version has and saves them as .blend files:
# scene_<ver>.blend collections, transforms (euler / quaternion / delta), parenting with a parent inverse,
# meshes (quads, an n-gon, smooth / flat), two UV maps, colour attributes, materials (Principled
# + packed and external images, a legacy one), cameras, lights, modifiers
# rig_<ver>.blend armature with rolls, a skinned mesh (vertex groups, 5 influences on some vertices), shape
# keys, actions on bones / objects / shape keys (bezier, linear, constant), a bone parent
# scene_<ver>_z.blend scene_<ver> saved compressed (gzip before 3.0, zstd after)
# compat_<ver>.blend 2.7x only: the "legacy mesh format" save (MFace tessellated faces)
import bpy, sys, os, math
out = sys.argv[sys.argv.index("--") + 1]
V = bpy.app.version
TAG = "%d%d" % (V[0], V[1])
OLD = V < (2, 80)
def reset():
bpy.ops.wm.read_factory_settings(use_empty=True) if not OLD else bpy.ops.wm.read_factory_settings()
if OLD:
for o in list(bpy.data.objects):
bpy.data.objects.remove(o, do_unlink=True)
sc = bpy.context.scene
sc.render.fps = 24
if OLD:
sc.render.engine = "CYCLES"
sc.frame_start, sc.frame_end = 1, 20
def link(obj, coll=None):
sc = bpy.context.scene
if OLD:
sc.objects.link(obj)
else:
(coll or sc.collection).objects.link(obj)
return obj
def mesh(name, verts, faces, smooth=False):
me = bpy.data.meshes.new(name)
me.from_pydata(verts, [], faces)
me.update()
for p in me.polygons:
p.use_smooth = smooth
return me
def uv(me, name, f):
if OLD:
me.uv_textures.new(name)
layer = me.uv_layers[name]
else:
layer = me.uv_layers.new(name=name)
for i, d in enumerate(layer.data):
d.uv = f(i)
def byte_colors(me, name):
if V >= (3, 2):
a = me.color_attributes.new(name, "BYTE_COLOR", "CORNER")
data = a.data
else:
data = me.vertex_colors.new(name=name).data
for i, d in enumerate(data):
c = ((i % 3) / 2, (i % 5) / 4, (i % 7) / 6)
d.color = c + (1.0,) if len(d.color) == 4 else c
def image(name, w, h, f, pack=True, path=None):
img = bpy.data.images.new(name, w, h)
px = []
for y in range(h):
for x in range(w):
px.extend(f(x, y))
img.pixels = px
if path:
img.filepath_raw = path
img.file_format = "PNG"
img.save()
img.filepath = "//" + os.path.basename(path)
if pack:
if OLD:
img.pack(as_png=True)
else:
img.pack()
return img
def socket(node, *names):
for n in names:
if n in node.inputs:
return node.inputs[n]
return None
def principled(mat, base, metallic, rough, emission=None, strength=1.0, alpha=1.0):
mat.use_nodes = True
nt = mat.node_tree
bsdf = None
for n in nt.nodes:
if n.bl_idname == "ShaderNodeBsdfPrincipled":
bsdf = n
if bsdf is None:
for n in list(nt.nodes):
if n.bl_idname != "ShaderNodeOutputMaterial":
nt.nodes.remove(n)
bsdf = nt.nodes.new("ShaderNodeBsdfPrincipled")
outs = [n for n in nt.nodes if n.bl_idname == "ShaderNodeOutputMaterial"]
outn = outs[0] if outs else nt.nodes.new("ShaderNodeOutputMaterial")
nt.links.new(bsdf.outputs[0], outn.inputs["Surface"])
socket(bsdf, "Base Color").default_value = base
socket(bsdf, "Metallic").default_value = metallic
socket(bsdf, "Roughness").default_value = rough
e = socket(bsdf, "Emission Color", "Emission")
if emission and e:
e.default_value = emission + (1.0,)
s = socket(bsdf, "Emission Strength")
if s:
s.default_value = strength
a = socket(bsdf, "Alpha")
if a:
a.default_value = alpha
return bsdf
def tex(mat, img, to, normal=False):
nt = mat.node_tree
t = nt.nodes.new("ShaderNodeTexImage")
t.image = img
if normal:
if not OLD:
img.colorspace_settings.name = "Non-Color"
nm = nt.nodes.new("ShaderNodeNormalMap")
nm.inputs["Strength"].default_value = 0.7
nt.links.new(t.outputs["Color"], nm.inputs["Color"])
nt.links.new(nm.outputs["Normal"], to)
else:
nt.links.new(t.outputs["Color"], to)
def camera(name, ortho=False):
cam = bpy.data.cameras.new(name)
if ortho:
cam.type = "ORTHO"
cam.ortho_scale = 7.0
else:
cam.lens = 35.0
cam.sensor_width = 36.0
cam.clip_start, cam.clip_end = 0.1, 100.0
return cam
def light(name, kind):
data = (bpy.data.lamps if OLD else bpy.data.lights).new(name, kind)
data.color = (1.0, 0.5, 0.25)
data.energy = {"POINT": 1000.0, "SUN": 3.0, "SPOT": 500.0, "AREA": 200.0}[kind]
if kind == "SPOT":
data.spot_size = 0.8
data.spot_blend = 0.2
return data
def save(path, compress=False, compat=False):
kw = {"filepath": path, "compress": compress}
if compat:
kw["use_mesh_compat"] = True
bpy.ops.wm.save_as_mainfile(**kw)
def update():
if OLD:
bpy.context.scene.update()
else:
bpy.context.view_layer.update()
def scene_file():
reset()
sc = bpy.context.scene
props = inner = None
if not OLD:
props = bpy.data.collections.new("Props")
sc.collection.children.link(props)
inner = bpy.data.collections.new("Inner")
props.children.link(inner)
cube_v = [(-1, -1, -1), (1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, 1), (1, -1, 1), (1, 1, 1), (-1, 1, 1)]
cube_f = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)]
me = mesh("BoxMesh", cube_v, cube_f)
uv(me, "UVMap", lambda i: ((i % 4) / 4 + 0.1, (i // 4) / 6))
uv(me, "Second", lambda i: (1 - (i % 3) / 3, (i % 2) * 0.5))
byte_colors(me, "Col")
if V >= (3, 2):
pc = me.color_attributes.new("PCol", "FLOAT_COLOR", "POINT")
for i, d in enumerate(pc.data):
d.color = (i / 8, 1 - i / 8, 0.5 + i / 16, 1.0)
checker = image("checker", 8, 8, lambda x, y: [float((x + y) % 2), 0.5, 0.25, 1.0])
bumps = image("bumps", 4, 4, lambda x, y: [0.5 + x / 8, 0.5 + y / 8, 1.0, 1.0])
outside = image("outside", 2, 2, lambda x, y: [1.0, 0.0, x * 1.0, 1.0], pack=False,
path=os.path.join(out, "outside.png"))
red = bpy.data.materials.new("Red")
bsdf = principled(red, (0.8, 0.1, 0.1, 1.0), 0.3, 0.4, (0.2, 0.3, 0.4), 2.0, 0.9)
tex(red, checker, socket(bsdf, "Base Color"))
tex(red, bumps, socket(bsdf, "Normal"), normal=True)
blue = bpy.data.materials.new("Blue")
blue.diffuse_color = (0.1, 0.2, 0.9) if OLD else (0.1, 0.2, 0.9, 1.0)
if not OLD:
blue.metallic = 0.25
blue.roughness = 0.6
if V >= (5, 0):
blue.use_nodes = False
me.materials.append(red)
me.materials.append(blue)
for i, p in enumerate(me.polygons):
p.material_index = i % 2
box = link(bpy.data.objects.new("Box", me), props)
box.location = (1, 2, 3)
box.rotation_euler = (0.3, 0.2, 0.1)
box.scale = (1, 2, 0.5)
box.modifiers.new("Subdiv", "SUBSURF")
# triangle, quad, convex pentagon, concave hexagon
sv = [(0, 0, 0), (1, 0, 0), (0, 1, 0), (2, 0, 0), (3, 0, 0), (3, 1, 0), (2, 1, 0),
(4, 0, 0), (5, 0, 0), (5.5, 0.8, 0), (4.5, 1.5, 0), (3.6, 0.8, 0),
(6, 0, 0), (8, 0, 0), (8, 2, 0), (7, 0.5, 0), (6, 2, 0), (6.5, 1, 0.2)]
sf = [(0, 1, 2), (3, 4, 5, 6), (7, 8, 9, 10, 11), (12, 13, 14, 15, 16, 17)]
shape_me = mesh("ShapeMesh", sv, sf, smooth=True)
glow = bpy.data.materials.new("Glow")
gb = principled(glow, (0.2, 0.9, 0.2, 1.0), 0.0, 0.8, (1.0, 0.8, 0.1), 5.0)
tex(glow, outside, socket(gb, "Emission Color", "Emission") or socket(gb, "Subsurface Color"))
shape_me.materials.append(glow)
shape = link(bpy.data.objects.new("Shape", shape_me), props)
shape.location = (-4, 0, 1)
shape.modifiers.new("Mirror", "MIRROR")
ball_me = mesh("BallMesh", [(math.cos(a * math.pi / 3) * 0.5, math.sin(a * math.pi / 3) * 0.5, z)
for z in (-0.4, 0.4) for a in range(6)],
[(0, 1, 7, 6), (1, 2, 8, 7), (2, 3, 9, 8), (3, 4, 10, 9), (4, 5, 11, 10), (5, 0, 6, 11),
(5, 4, 3, 2, 1, 0), (6, 7, 8, 9, 10, 11)], smooth=True)
ball = link(bpy.data.objects.new("Ball", ball_me), inner)
ball.location = (-3, 1, 0.5)
ball.rotation_euler = (0, 0, 0.7)
update()
ball.parent = box
ball.matrix_parent_inverse = box.matrix_world.inverted()
pivot = link(bpy.data.objects.new("Pivot", None), props)
pivot.location = (0, -3, 1)
pivot.rotation_mode = "QUATERNION"
q = (0.9, 0.1, 0.3, 0.2)
n = math.sqrt(sum(c * c for c in q))
pivot.rotation_quaternion = tuple(c / n for c in q)
leaf_me = mesh("LeafMesh", [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)], [(0, 1, 2, 3)])
leaf_me.materials.append(glow)
leaf = link(bpy.data.objects.new("Leaf", leaf_me), props)
leaf.parent = pivot
leaf.location = (0.5, 0.25, 0)
leaf.rotation_mode = "ZXY"
leaf.rotation_euler = (0.4, -0.3, 1.1)
leaf.scale = (1.5, 1, 1)
leaf.delta_location = (0, 0, 0.5)
leaf.delta_rotation_euler = (0, 0.2, 0)
leaf.delta_scale = (1, 1, 2)
# smooth grid with custom normals
gv = [(x, y, 0.1 * x * y) for y in range(3) for x in range(3)]
gf = [(0, 1, 4, 3), (1, 2, 5, 4), (3, 4, 7, 6), (4, 5, 8, 7)]
grid_me = mesh("BentMesh", gv, gf, smooth=True)
if V < (4, 1):
grid_me.use_auto_smooth = True
grid_me.normals_split_custom_set_from_vertices([(0.3 * (i % 3 - 1), 0.2 * (i // 3 - 1), 1.0) for i in range(9)])
bent = link(bpy.data.objects.new("Bent", grid_me), props)
bent.location = (0, 4, 0)
cp = link(bpy.data.objects.new("CamP", camera("CamP")))
cp.location = (7, -7, 5)
cp.rotation_euler = (1.1, 0, 0.8)
co = link(bpy.data.objects.new("CamO", camera("CamO", True)))
co.location = (0, 0, 10)
for kind in ("POINT", "SUN", "SPOT", "AREA"):
lo = link(bpy.data.objects.new("L" + kind.lower(), light("L" + kind.lower(), kind)))
lo.location = ({"POINT": 4, "SUN": 0, "SPOT": -4, "AREA": 2}[kind], 1, 6)
lo.rotation_euler = (0.5, 0.1, 0)
sc.frame_set(1)
update()
save(os.path.join(out, "scene_%s.blend" % TAG))
save(os.path.join(out, "scene_%s_z.blend" % TAG), compress=True)
def rig_file():
reset()
sc = bpy.context.scene
arm_data = bpy.data.armatures.new("RigData")
rig = link(bpy.data.objects.new("Rig", arm_data))
rig.location = (0, 0, 0.5)
rig.rotation_euler = (0, 0, 0.2)
if OLD:
sc.objects.active = rig
else:
bpy.context.view_layer.objects.active = rig
bpy.ops.object.mode_set(mode="EDIT")
eb = arm_data.edit_bones
root = eb.new("root")
root.head, root.tail, root.roll = (0, 0, 0), (0, 0, 1), 0.0
mid = eb.new("mid")
mid.head, mid.tail, mid.roll, mid.parent, mid.use_connect = (0, 0, 1), (0, 0.5, 2), 0.3, root, True
tip = eb.new("tip")
tip.head, tip.tail, tip.roll, tip.parent, tip.use_connect = (0, 0.5, 2), (0.3, 0.5, 2.8), -0.5, mid, True
aux = eb.new("aux")
aux.head, aux.tail, aux.roll, aux.parent = (0.5, 0, 0.5), (1, 0, 0.5), 0.0, root
nodef = eb.new("nodef")
nodef.head, nodef.tail, nodef.parent, nodef.use_deform = (-0.5, 0, 0.5), (-1, 0, 0.7), root, False
bpy.ops.object.mode_set(mode="OBJECT")
ring = [(math.cos(a * math.pi / 4) * 0.3, math.sin(a * math.pi / 4) * 0.3) for a in range(8)]
bv = [(x, y + (0.25 if z == 2 else 0), z) for z in (0, 1, 2) for x, y in ring]
bf = [(r * 8 + a, r * 8 + (a + 1) % 8, (r + 1) * 8 + (a + 1) % 8, (r + 1) * 8 + a) for r in range(2) for a in range(8)]
body_me = mesh("BodyMesh", bv, bf, smooth=True)
body = link(bpy.data.objects.new("Body", body_me))
body.parent = rig
body.location = (0, 0, 0)
mod = body.modifiers.new("Armature", "ARMATURE")
mod.object = rig
groups = {n: body.vertex_groups.new(name=n) for n in ("root", "mid", "tip", "aux", "nodef", "extra")}
for i in range(24):
z = i // 8
groups["root"].add([i], max(0.0, 1.0 - z * 0.6), "REPLACE")
groups["mid"].add([i], 0.3 + 0.2 * (z == 1), "REPLACE")
if z == 2:
groups["tip"].add([i], 0.9, "REPLACE")
if i % 3 == 0:
groups["aux"].add([i], 0.05 + 0.01 * i, "REPLACE")
groups["nodef"].add([i], 0.7, "REPLACE")
groups["extra"].add([i], 0.15, "REPLACE")
body.shape_key_add(name="Basis")
fat = body.shape_key_add(name="Fat")
for i, p in enumerate(fat.data):
p.co = (p.co[0] * 1.5, p.co[1] * 1.5, p.co[2])
thin = body.shape_key_add(name="Thin")
for i, p in enumerate(thin.data):
p.co = (p.co[0] * 0.5, p.co[1] * 0.5, p.co[2] + 0.1)
thin.value = 0.25
key = body_me.shape_keys
for f, v in ((1, 0.0), (10, 1.0), (20, 0.2)):
fat.value = v
fat.keyframe_insert("value", frame=f)
hat_me = mesh("HatMesh", [(-0.2, -0.2, 0), (0.2, -0.2, 0), (0, 0.2, 0), (0, 0, 0.3)], [(0, 1, 2), (0, 1, 3), (1, 2, 3), (2, 0, 3)])
hat = link(bpy.data.objects.new("Hat", hat_me))
hat.parent = rig
hat.parent_type = "BONE"
hat.parent_bone = "tip"
hat.location = (0.1, 0.2, 0.0)
pose = rig.pose.bones
pose["aux"].rotation_mode = "XYZ"
keys = ((1, (0, 0, 0), (1, 0, 0, 0), (1, 1, 1), (0, 0, 0)),
(10, (0.2, 0.1, 0), (0.92, 0.3, 0.2, 0.1), (1.2, 1, 1), (0.4, 0, 0.3)),
(20, (0, 0.3, 0.2), (0.8, -0.2, 0.5, 0.2), (0.8, 1.1, 1), (-0.3, 0.5, 0)))
for f, loc, quat, scl, eul in keys:
pose["root"].location = loc
pose["root"].keyframe_insert("location", frame=f)
n = math.sqrt(sum(c * c for c in quat))
pose["mid"].rotation_quaternion = tuple(c / n for c in quat)
pose["mid"].keyframe_insert("rotation_quaternion", frame=f)
pose["tip"].scale = scl
pose["tip"].keyframe_insert("scale", frame=f)
pose["aux"].rotation_euler = eul
pose["aux"].keyframe_insert("rotation_euler", frame=f)
mover = link(bpy.data.objects.new("Mover", mesh("MoverMesh", [(0, 0, 0), (1, 0, 0), (0, 1, 0)], [(0, 1, 2)])))
for f, loc, rot, scl in ((1, (3, 0, 0), (0, 0, 0), (1, 1, 1)), (8, (3, 2, 1), (0.5, 0, 1), (2, 1, 1)),
(20, (5, 2, 0), (0, 1, -1), (1, 1, 3))):
mover.location, mover.rotation_euler, mover.scale = loc, rot, scl
mover.keyframe_insert("location", frame=f)
mover.keyframe_insert("rotation_euler", frame=f)
mover.keyframe_insert("scale", frame=f)
# easing interpolations (Penner) with explicit and automatic easing
easer = link(bpy.data.objects.new("Easer", None))
eases = (("SINE", "EASE_IN_OUT"), ("BOUNCE", "AUTO"), ("SINE", "EASE_OUT"), ("BACK", "EASE_IN"),
("EXPO", "AUTO"), ("CIRC", "EASE_OUT"), ("QUART", "EASE_IN_OUT"), ("EXPO", "EASE_OUT"), ("EXPO", "EASE_IN_OUT"), ("CUBIC", "EASE_IN"))
for k in range(len(eases) + 1):
easer.location = (k % 2 * 2.0, k * 0.5, 0)
easer.keyframe_insert("location", frame=1 + k * 2.5)
for fc in (easer.animation_data.action.fcurves if hasattr(easer.animation_data.action, "fcurves") else
[c for l in easer.animation_data.action.layers for s in l.strips for b in s.channelbags for c in b.fcurves]):
for kp, (ipo, easing) in zip(fc.keyframe_points, eases):
kp.interpolation = ipo
kp.easing = easing
rig_action = rig.animation_data.action
mover_action = mover.animation_data.action
for act, rules in ((rig_action, {"location": "LINEAR", "scale": "CONSTANT"}),
(mover_action, {"rotation_euler": "LINEAR", "scale": "CONSTANT"})):
curves = act.fcurves if hasattr(act, "fcurves") else [c for l in act.layers for s in l.strips for b in s.channelbags for c in b.fcurves]
for fc in curves:
for k, ipo in rules.items():
if fc.data_path.endswith(k):
for kp in fc.keyframe_points:
kp.interpolation = ipo
if fc.data_path == "location" and fc.array_index == 2:
fc.extrapolation = "LINEAR"
sc.frame_set(1)
update()
save(os.path.join(out, "rig_%s.blend" % TAG))
scene_file()
rig_file()
if OLD:
scene_file()
save(os.path.join(out, "compat_%s.blend" % TAG), compat=True)
print("MADE", TAG)
+219
View File
@@ -0,0 +1,219 @@
# tools/fixtures/_blend_ref: run by tools/fixtures/blend.py inside Blender (blender -b --factory-startup --python
# <this> -- <json list of .blend paths> <out dir>): opens each file (old ones through Blender's versioning) and writes
# <out dir>/<file>.json with the reference values (object world matrices, mesh counts / bounds / attribute sums / corner normals,
# vertex groups, shape keys, materials, images, cameras, lights, bones, f-curve values, posed world matrices per frame),
# and exports a .glb of each file (Z up, no modifiers) whose JSON part is returned as "gltf".
import bpy, sys, os, json, struct, math
args = sys.argv[sys.argv.index("--") + 1:]
paths, outdir = json.loads(args[0]), args[1]
V = bpy.app.version
def mat(m):
return [m[r][c] for c in range(4) for r in range(4)] # column-major
def r6(x):
return round(float(x), 6)
def color_attrs(me):
out = []
attrs = me.color_attributes if hasattr(me, "color_attributes") else []
for a in attrs:
s = [0.0, 0.0, 0.0, 0.0]
for l in me.loops:
d = a.data[l.index if a.domain == "CORNER" else l.vertex_index]
for k in range(4):
s[k] += d.color[k]
out.append({"name": a.name, "domain": a.domain, "type": a.data_type, "count": len(a.data), "cornerSum": [r6(x) for x in s]})
return out
def mesh_info(ob):
me = ob.data
me.calc_loop_triangles()
vs = [v.co for v in me.vertices]
lo = [min(v[k] for v in vs) for k in range(3)] if vs else [0, 0, 0]
hi = [max(v[k] for v in vs) for k in range(3)] if vs else [0, 0, 0]
info = {
"name": me.name, "vertices": len(me.vertices), "corners": len(me.loops), "faces": len(me.polygons),
"triangles": len(me.loop_triangles), "min": [r6(x) for x in lo], "max": [r6(x) for x in hi],
"possum": [r6(sum(v[k] for v in vs)) for k in range(3)],
"uvs": [], "colors": color_attrs(me), "slots": [s.material.name if s.material else "" for s in ob.material_slots],
"facemats": [p.material_index for p in me.polygons],
"smooth": [1 if p.use_smooth else 0 for p in me.polygons],
}
for layer in me.uv_layers:
su = sv = 0.0
for d in layer.data:
su += d.uv[0]
sv += d.uv[1]
info["uvs"].append({"name": layer.name, "sum": [r6(su), r6(sv)], "active_render": bool(layer.active_render)})
if len(me.loops) <= 400:
if hasattr(me, "corner_normals"):
info["normals"] = [[r6(c) for c in n.vector] for n in me.corner_normals]
info["cornerVerts"] = [l.vertex_index for l in me.loops]
info["custom"] = bool(me.has_custom_normals)
groups = {g.index: g.name for g in ob.vertex_groups}
if groups:
info["weights"] = [[[groups.get(g.group, "?"), r6(g.weight)] for g in v.groups] for v in me.vertices]
if me.shape_keys:
k = me.shape_keys
info["shapes"] = [{"name": b.name, "value": r6(b.value), "relative": b.relative_key.name,
"co": [r6(p.co[c]) for p in b.data for c in range(3)]} for b in k.key_blocks]
info["reference"] = k.reference_key.name
info["modifiers"] = [m.type for m in ob.modifiers]
return info
def socket_val(s):
if s is None:
return None
v = s.default_value
try:
return [r6(x) for x in v]
except TypeError:
return r6(v)
def linked_image(s):
if s is None or not s.is_linked:
return None
n = s.links[0].from_node
if n.bl_idname == "ShaderNodeNormalMap":
return linked_image(n.inputs["Color"])
if n.bl_idname == "ShaderNodeTexImage" and n.image:
return n.image.name
return "?" + n.bl_idname
def material_info(m):
info = {"name": m.name, "diffuse": [r6(x) for x in m.diffuse_color], "metallic": r6(m.metallic), "roughness": r6(m.roughness),
"use_nodes": bool(m.use_nodes), "cull": bool(m.use_backface_culling)}
if m.node_tree:
for n in m.node_tree.nodes:
if n.bl_idname == "ShaderNodeBsdfPrincipled":
ins = n.inputs
g = lambda *names: next((ins[x] for x in names if x in ins), None)
info["principled"] = {
"base": socket_val(g("Base Color")), "metallic": socket_val(g("Metallic")), "roughness": socket_val(g("Roughness")),
"emission": socket_val(g("Emission Color", "Emission")), "strength": socket_val(g("Emission Strength")),
"alpha": socket_val(g("Alpha")),
"baseTex": linked_image(g("Base Color")), "normalTex": linked_image(g("Normal")),
"emissionTex": linked_image(g("Emission Color", "Emission")),
}
if n.bl_idname == "ShaderNodeNormalMap":
info["normalStrength"] = r6(n.inputs["Strength"].default_value)
return info
def fcurves(act):
if act is None:
return []
if hasattr(act, "fcurves") and V < (5, 0):
return list(act.fcurves)
out = []
for layer in act.layers:
for strip in layer.strips:
for bag in strip.channelbags:
out.extend(bag.fcurves)
return out
FRAMES = [1 + 0.5 * i for i in range(43)] # 1 .. 22 (past the last key: extrapolation)
def curve_info(act):
out = []
for fc in fcurves(act):
out.append({"path": fc.data_path, "index": fc.array_index, "extrapolation": fc.extrapolation,
"keys": len(fc.keyframe_points), "values": [r6(fc.evaluate(f)) for f in FRAMES]})
return out
def dump(path):
bpy.ops.wm.open_mainfile(filepath=path)
sc = bpy.context.scene
sc.frame_set(sc.frame_current)
obs = list(sc.objects)
ref = {"version": list(bpy.data.version), "fps": sc.render.fps / sc.render.fps_base, "frameStart": sc.frame_start,
"frameCurrent": sc.frame_current, "resolution": [sc.render.resolution_x, sc.render.resolution_y],
"objects": [], "materials": [], "images": [], "cameras": {}, "lights": {}, "armatures": {}, "actions": {}}
for ob in obs:
o = {"name": ob.name, "type": ob.type, "parent": ob.parent.name if ob.parent else "", "parent_type": ob.parent_type,
"parent_bone": ob.parent_bone, "world": [r6(x) for x in mat(ob.matrix_world)],
"collections": [c.name for c in ob.users_collection]}
if ob.type == "MESH":
o["mesh"] = mesh_info(ob)
if ob.animation_data and ob.animation_data.action:
a = ob.animation_data.action
ref["actions"][a.name] = curve_info(a)
o["action"] = a.name
if ob.type == "MESH" and ob.data.shape_keys and ob.data.shape_keys.animation_data and ob.data.shape_keys.animation_data.action:
a = ob.data.shape_keys.animation_data.action
ref["actions"][a.name] = curve_info(a)
o["shapeAction"] = a.name
ref["objects"].append(o)
if ob.type == "CAMERA":
c = ob.data
ref["cameras"][ob.name] = {"type": c.type, "lens": r6(c.lens), "sensor": [r6(c.sensor_width), r6(c.sensor_height)],
"fit": c.sensor_fit, "ortho": r6(c.ortho_scale), "clip": [r6(c.clip_start), r6(c.clip_end)],
"angle": [r6(c.angle_x), r6(c.angle_y)]}
if ob.type == "LIGHT":
l = ob.data
ref["lights"][ob.name] = {"type": l.type, "color": [r6(x) for x in l.color], "energy": r6(l.energy),
"spot": [r6(l.spot_size), r6(l.spot_blend)] if l.type == "SPOT" else [0, 0]}
if ob.type == "ARMATURE":
ref["armatures"][ob.name] = [{"name": b.name, "parent": b.parent.name if b.parent else "", "deform": b.use_deform,
"local": [r6(x) for x in mat(b.matrix_local)], "length": r6(b.length)} for b in ob.data.bones]
for m in bpy.data.materials:
ref["materials"].append(material_info(m))
for im in bpy.data.images:
if im.source in ("FILE", "GENERATED") and im.type == "IMAGE":
ref["images"].append({"name": im.name, "filepath": im.filepath, "packed": im.packed_file.size if im.packed_file else 0,
"source": im.source})
# posed world matrices: objects, pose bones (world), shape key values
poses = []
if ref["actions"]:
for f in FRAMES:
sc.frame_set(int(math.floor(f)), subframe=f - math.floor(f))
p = {"frame": f, "objects": {}, "bones": {}, "shapes": {}}
for ob in obs:
p["objects"][ob.name] = [r6(x) for x in mat(ob.matrix_world)]
if ob.type == "ARMATURE":
for pb in ob.pose.bones:
p["bones"][ob.name + "/" + pb.name] = [r6(x) for x in mat(ob.matrix_world @ pb.matrix)]
if ob.type == "MESH" and ob.data.shape_keys:
p["shapes"][ob.name] = [r6(b.value) for b in ob.data.shape_keys.key_blocks]
if ob.type == "MESH" and any(m.type == "ARMATURE" for m in ob.modifiers) and f == math.floor(f):
ev = ob.evaluated_get(bpy.context.evaluated_depsgraph_get())
em = ev.to_mesh()
w = ob.matrix_world
p.setdefault("skinned", {})[ob.name] = [r6(c) for v in em.vertices for c in (w @ v.co)]
ev.to_mesh_clear()
poses.append(p)
ref["poses"] = poses
# Blender's glTF exporter on the same file (Z up, modifiers not applied)
glb = os.path.join(outdir, os.path.basename(path) + ".glb")
try:
bpy.ops.export_scene.gltf(filepath=glb, export_format="GLB", export_yup=False, export_apply=False,
export_cameras=True, export_lights=True)
with open(glb, "rb") as fh:
data = fh.read()
n = struct.unpack_from("<I", data, 12)[0]
ref["gltf"] = json.loads(data[20:20 + n].decode("utf-8"))
ref["gltf"].pop("buffers", None)
except Exception as e: # noqa: BLE001
ref["gltfError"] = str(e)
return ref
for p in paths:
try:
r = dump(p)
except Exception as e: # noqa: BLE001
r = {"error": str(e)}
with open(os.path.join(outdir, os.path.basename(p) + ".json"), "w") as fh:
json.dump(r, fh)
+141
View File
@@ -0,0 +1,141 @@
# .blend fixtures (tools/fixtures.py): the same test scenes built by Blender 2.79, 2.93, 3.5, 4.1 (old nixpkgs
# releases) and the current nixpkgs Blender (5.x) through tools/fixtures/_blend_make.py, covering every mesh storage
# generation (MFace legacy save, MPoly / MLoop, attribute layers, AttributeStorage), gzip and zstd compression, the
# 5.0 header, layered actions. Reference values come from the current Blender opening each file
# (tools/fixtures/_blend_ref.py: bpy values plus its glTF exporter's output). An old Blender that does not run is
# skipped (its cases are missing; the test notes it). Plus a few Blender 1.6x / 2.0x files from download.blender.org's
# old demos (fetched, never committed; 32-bit pointers, big-endian SGI / PowerPC files among them), with references
# from Blender 4.1 (5.0 dropped big-endian files).
# tests/gen/blend_<ver>.luau { { name, data, ref } } (<ver>: 279, 293, 35, 41, cur, old)
# tests/gen/blend_files.luau sibling files the scenes refer to ({ ["outside.png"] = bytes })
import json, os, shutil, subprocess, tempfile
INPUTS = ["tools/fixtures/_blend_make.py", "tools/fixtures/_blend_ref.py"]
OLD = [
("279", ["--impure", "--expr", '(import (builtins.fetchTarball "https://github.com/NixOS/nixpkgs/archive/nixos-19.03.tar.gz") {}).blender']),
("293", ["github:NixOS/nixpkgs/nixos-21.11#blender"]),
("35", ["github:NixOS/nixpkgs/nixos-23.05#blender"]),
("41", ["github:NixOS/nixpkgs/nixos-24.05#blender"]),
]
OLD_DEMOS = "https://download.blender.org/demo/old_demos/"
OLD_FILES = ["escher.blend", "hairball.blend", "nmesh.blend", "relative.blend", "demo2.04.blend.gz"]
def old_samples(ctx, tmp):
import gzip, urllib.request
out = os.path.join(tmp, "olddemos")
os.makedirs(out)
files = []
for f in OLD_FILES:
try:
with urllib.request.urlopen(OLD_DEMOS + f, timeout=60) as r:
data = r.read()
except OSError as e:
print("blend: could not fetch %s: %s" % (f, e))
continue
if f.endswith(".gz"):
data = gzip.decompress(data)
f = f[:-3].replace("2.04", "204")
with open(os.path.join(out, f), "wb") as fh:
fh.write(data)
files.append(os.path.join(out, f))
if not files:
return []
refdir = os.path.join(tmp, "oldref")
os.makedirs(refdir)
ref = os.path.join(ctx.root, "tools", "fixtures", "_blend_ref.py")
ok, log = run(["nix", "shell"] + OLD[3][1] + ["-c", "blender", "-b", "--factory-startup", "--python", ref, "--", json.dumps(files), refdir])
cases = []
for p in files:
rp = os.path.join(refdir, os.path.basename(p) + ".json")
if not os.path.exists(rp):
continue
r = json.load(open(rp))
if r.get("error"):
continue
g = r.get("gltf")
if g:
for k in ("bufferViews", "asset", "scene", "scenes", "extensionsUsed", "samplers"):
g.pop(k, None)
cases.append({"name": "old/" + os.path.basename(p), "data": open(p, "rb").read(), "ref": clean(r)})
if not cases:
print("blend: Blender 4.1 gave no reference for the old demos: " + log[-400:])
return cases
def env():
e = dict(os.environ)
e.pop("LD_LIBRARY_PATH", None) # the host's alsa / pipewire libraries need a newer glibc than old Blenders have
return e
def current():
exe = shutil.which("blender")
return [exe] if exe else ["nix", "shell", "nixpkgs#blender", "-c", "blender"]
def run(cmd, timeout=1800):
try:
res = subprocess.run(cmd, capture_output=True, timeout=timeout, env=env())
return res.returncode == 0, res.stdout.decode("utf-8", "replace") + res.stderr.decode("utf-8", "replace")
except (subprocess.TimeoutExpired, OSError) as e:
return False, str(e)
def clean(v):
if isinstance(v, dict):
return {k: clean(x) for k, x in v.items() if x is not None}
if isinstance(v, list):
return [False if x is None else clean(x) for x in v]
return v
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="blendfx")
make = os.path.join(ctx.root, "tools", "fixtures", "_blend_make.py")
ref = os.path.join(ctx.root, "tools", "fixtures", "_blend_ref.py")
made = {}
for tag, inst in OLD + [("cur", None)]:
out = os.path.join(tmp, tag)
os.makedirs(out)
if inst is None:
cmd = current()
else:
cmd = ["nix", "shell"] + inst + ["-c", "blender"]
ok, log = run(cmd + ["-b", "--factory-startup", "--python", make, "--", out])
files = sorted(f for f in os.listdir(out) if f.endswith(".blend"))
if not ok or not files:
print("blend: Blender %s did not run (skipped): %s" % (tag, log[-400:]))
continue
made[tag] = (out, files)
paths = [os.path.join(out, f) for out, files in made.values() for f in files]
refdir = os.path.join(tmp, "ref")
os.makedirs(refdir)
ok, log = run(current() + ["-b", "--factory-startup", "--python", ref, "--", json.dumps(paths), refdir], timeout=3600)
if not ok:
raise RuntimeError("blend: the reference Blender failed: " + log[-2000:])
sibling = None
for tag, (out, files) in made.items():
cases = []
for f in files:
p = os.path.join(out, f)
r = json.load(open(os.path.join(refdir, f + ".json")))
g = r.get("gltf")
if g:
for k in ("bufferViews", "asset", "scene", "scenes", "extensionsUsed", "samplers"):
g.pop(k, None)
cases.append({"name": f, "data": open(p, "rb").read(), "ref": clean(r)})
name = "cur" if tag == "cur" else tag
ctx.emit("blend_" + name, cases)
if sibling is None and os.path.exists(os.path.join(out, "outside.png")):
sibling = open(os.path.join(out, "outside.png"), "rb").read()
for tag, _ in OLD + [("cur", None)]:
if tag not in made:
ctx.emit("blend_" + tag, [])
ctx.emit("blend_old", old_samples(ctx, tmp))
ctx.emit("blend_files", {"outside.png": sibling or b""})
ctx.emit("blend_versions", sorted(made.keys()))
shutil.rmtree(tmp, ignore_errors=True)
+73
View File
@@ -0,0 +1,73 @@
# Docs inputs for the .blend section of docs/guide/scene.md (tools/fixtures.py; tools/docs_check.py explains the
# inputs): a small rig saved zstd-compressed by the nixpkgs Blender (a two-bone armature, a skinned cylinder with a
# shape key, a bone action and a Principled material).
# tests/gen/docs_blend.luau { files = { ["rig.blend"] = bytes }, vars = { riggedBlendBytes = "rig.blend" } }
import importlib.util, os, shutil, subprocess, tempfile
INPUTS = ["tools/docs_check.py"]
SCRIPT = r'''
import bpy, sys, math
out = sys.argv[sys.argv.index("--") + 1]
bpy.ops.wm.read_factory_settings(use_empty=True)
arm = bpy.data.armatures.new("RigData")
rig = bpy.data.objects.new("Rig", arm)
bpy.context.scene.collection.objects.link(rig)
bpy.context.view_layer.objects.active = rig
bpy.ops.object.mode_set(mode="EDIT")
a = arm.edit_bones.new("lower")
a.head, a.tail = (0, 0, 0), (0, 0, 1)
b = arm.edit_bones.new("upper")
b.head, b.tail, b.parent, b.use_connect = (0, 0, 1), (0, 0, 2), a, True
bpy.ops.object.mode_set(mode="OBJECT")
ring = [(math.cos(k * math.pi / 3) * 0.3, math.sin(k * math.pi / 3) * 0.3) for k in range(6)]
verts = [(x, y, z) for z in (0, 1, 2) for x, y in ring]
faces = [(r * 6 + k, r * 6 + (k + 1) % 6, (r + 1) * 6 + (k + 1) % 6, (r + 1) * 6 + k) for r in range(2) for k in range(6)]
me = bpy.data.meshes.new("Tube")
me.from_pydata(verts, [], faces)
mat = bpy.data.materials.new("Skin")
mat.use_nodes = True
bsdf = mat.node_tree.nodes["Principled BSDF"]
bsdf.inputs["Base Color"].default_value = (0.9, 0.6, 0.5, 1)
bsdf.inputs["Roughness"].default_value = 0.7
me.materials.append(mat)
tube = bpy.data.objects.new("Tube", me)
bpy.context.scene.collection.objects.link(tube)
tube.parent = rig
tube.modifiers.new("Armature", "ARMATURE").object = rig
lo, up = tube.vertex_groups.new(name="lower"), tube.vertex_groups.new(name="upper")
for i in range(18):
lo.add([i], 1.0 - (i // 6) * 0.5, "REPLACE")
up.add([i], (i // 6) * 0.5, "REPLACE")
tube.shape_key_add(name="Basis")
bulge = tube.shape_key_add(name="Bulge")
for p in bulge.data:
p.co = (p.co[0] * 1.4, p.co[1] * 1.4, p.co[2])
pb = rig.pose.bones["upper"]
for f, angle in ((1, 0.0), (12, 0.8), (24, 0.0)):
pb.rotation_quaternion = (math.cos(angle / 2), math.sin(angle / 2), 0, 0)
pb.keyframe_insert("rotation_quaternion", frame=f)
bpy.context.scene.frame_set(1)
bpy.ops.wm.save_as_mainfile(filepath=out, compress=True)
'''
def generate(ctx):
spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py"))
check = importlib.util.module_from_spec(spec)
spec.loader.exec_module(check)
tmp = tempfile.mkdtemp(prefix="formats-docs-blend-")
try:
script = os.path.join(tmp, "make.py")
with open(script, "w") as f:
f.write(SCRIPT)
out = os.path.join(tmp, "rig.blend")
exe = shutil.which("blender")
cmd = [exe] if exe else ["nix", "shell", "nixpkgs#blender", "-c", "blender"]
env = dict(os.environ)
env.pop("LD_LIBRARY_PATH", None)
subprocess.run(cmd + ["-b", "--factory-startup", "--python", script, "--", out], capture_output=True, check=True, timeout=900, env=env)
files = {"rig.blend": open(out, "rb").read()}
finally:
shutil.rmtree(tmp, ignore_errors=True)
check.emit_inputs(ctx, files, {"riggedBlendBytes": "rig.blend"})