ws-3d3-d: model/ldraw (LDR / DAT / MPD read: parts as shared meshes per colour, sub-models as nodes, BFC, LDConfig colours, library paths through files / resolve)

Built-in colour table from LDConfig.ldr (CC BY 2.0 / 4.0, licenses/LDRAW_COLOURS.txt + NOTICE.md row).
Tests: independent Python expansion + LeoCAD OBJ export of library parts / car.ldr / pyramid.ldr (read from the nix store).
This commit is contained in:
4DBug committed 2026-10-31 14:28:56 -05:00
1 parent 07dc6f7e84
commit e3ac2f8b36
10 files changed
+1737

No files matched your search

+1
View File
@@ -39,6 +39,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` |
| model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` |
| model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` |
| model | ldraw | .ldr .mpd .dat | yes | - | materials: true, lines: true, instancing: true | `tests/model/ldraw.luau` |
| model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` |
| model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` |
| model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` |
+60
View File
@@ -391,6 +391,65 @@ Blitz3D is **left-handed**: the reader mirrors z (and turns the triangle winding
is glTF's right-handed Y-up with the model looking as it did in Blitz3D. `meta.source.handedness = "left"` records
the origin, `meta.source.fps` / `frames` the `ANIM` chunk.
## LDraw
LDraw files (`.ldr` models, `.dat` parts, `.mpd` multi-part files) load read-only. Every reference to a **part**
becomes a node with the reference's matrix, and each part is baked once per colour into a mesh those nodes share;
**sub-models** (`.ldr` / `.mpd` files, MPD sections that are not parts) become nodes with children. Colour 16 takes the
colour of the reference above it, 24 its edge colour; codes come from the LDConfig.ldr table built in (one material per
colour, `extras.ldraw.code` / `name`), `0x2RRGGBB` is a direct colour. BFC (`CERTIFY`, `CW` / `CCW`, `INVERTNEXT`,
`NOCLIP`) turns every face counter-clockwise; faces of uncertified parts get double-sided materials. Edge lines (type 2)
are `"lines"` primitives (`lines = false` drops them); optional lines only on request (`optionalLines = true`).
```luau
local mpd = [[
0 FILE house.ldr
1 4 0 0 0 1 0 0 0 1 0 0 0 1 wall.dat
1 4 50 0 0 1 0 0 0 1 0 0 0 1 wall.dat
1 1 0 -30 0 1 0 0 0 1 0 0 0 1 roof.dat
0 FILE wall.dat
0 !LDRAW_ORG Unofficial_Part
0 BFC CERTIFY CCW
4 16 -10 0 -10 10 0 -10 10 0 10 -10 0 10
2 24 -10 0 -10 10 0 -10
0 FILE roof.dat
0 BFC CERTIFY CCW
3 16 0 -10 0 10 0 0 -10 0 0
]]
local scene = assert(F.model.load(mpd, { format = "ldraw" }))
print(#scene.meshes) -- 2: wall.dat in red (both walls share it), roof.dat in blue
local root = scene.nodes[scene.roots[1]] -- "LDraw": turns LDraw's -Y up into Y up
local a, b = scene.nodes[root.children[1]], scene.nodes[root.children[2]]
assert(a.mesh == b.mesh and b.matrix[13] == 50)
local red = scene.materials[scene.meshes[a.mesh].primitives[1].material]
print(red.name, red.extras.ldraw.code) -- Red 4
assert(scene.meta.up == "y" and scene.meta.unit == 0.0004) -- 1 LDU = 0.4 mm
```
Parts and primitives that are not in the file come through `files` or `resolve`, asked for by their LDraw library
path: the name as written (backslashes turned into slashes), then in lower case, under `""`, `parts/`, `p/`,
`parts/s/` and `models/`. Point `resolve` at an LDraw library folder to load real models; missing files are skipped and
listed in `meta.source.missing`:
```luau
local library = {
["p/box.dat"] = "0 BFC CERTIFY CCW\n4 16 -1 -1 -1 1 -1 -1 1 -1 1 -1 -1 1\n4 16 -1 1 -1 -1 1 1 1 1 1 1 1 -1\n",
["parts/plate.dat"] = "0 !LDRAW_ORG Part\n1 16 0 4 0 20 0 0 0 4 0 0 0 10 box.dat\n",
}
local model = "0 two plates\n1 14 0 0 0 1 0 0 0 1 0 0 0 1 plate.dat\n1 0x2FF8000 0 -8 0 1 0 0 0 1 0 0 0 1 plate.dat\n"
.. "1 4 0 -16 0 1 0 0 0 1 0 0 0 1 3001.dat\n"
local scene = assert(F.model.load(model, { format = "ldraw", files = library }))
assert(#scene.meshes == 2 and scene.meta.source.missing[1] == "3001.dat")
local same = assert(F.model.load(model, { format = "ldraw", resolve = function(path)
return library[path] -- or: read ldrawFolder .. "/" .. path
end }))
local flat = assert(F.model.load(model, { format = "ldraw", files = library, flatten = true }))
assert(#flat.meshes == 1) -- one mesh, one primitive per colour
```
`upright = false` leaves out the root node (LDraw's axes as stored, `meta.source.up = "-y"`); `ldconfig` takes the
text of another LDConfig.ldr, and `color` the colour of code 16 at the top (default 16, "Main_Colour").
## Formats
| Format | Read | Write | Notes |
@@ -406,6 +465,7 @@ the origin, `meta.source.fps` / `frames` the `ANIM` chunk.
| USDA (+ USDZ read) | yes | yes | |
| VOX | yes | yes | voxel grids, scene graph, materials |
| B3D (Blitz3D) | yes | | brushes, textures, skins, keyframe animation; left-handed source mirrored to glTF's frame |
| LDraw (LDR / DAT / MPD) | yes | | parts as shared meshes per colour, sub-models as nodes, BFC, LDConfig colours, `files` / `resolve` for the library |
| STEP | via the CAD plug-in | | see [cad.md](cad.md) |
Capabilities per format: [FORMATS.md](../FORMATS.md).
+15
View File
@@ -0,0 +1,15 @@
LDraw colour table (src/Formats/model/ldraw/Colors.luau)
The built-in colour list of model/ldraw is the list of !COLOUR definitions of LDConfig.ldr from the LDraw.org Parts
Library ("0 !LDRAW_ORG Configuration UPDATE 2025-05-20", Author: LDraw.org), reformatted (one line per colour, the
"0 !COLOUR" prefix dropped, MATERIAL parameters cut after the material type). Modified from the original.
Creator: LDraw.org (https://www.ldraw.org/)
Work: LDConfig.ldr, LDraw.org Parts Library, https://library.ldraw.org/library/updates/complete.zip
Licence: Creative Commons Attribution 2.0 (CC BY 2.0) and Creative Commons Attribution 4.0 International (CC BY 4.0),
as specified by the LDraw Contributor Agreement (see the library's CAreadme.txt):
https://creativecommons.org/licenses/by/2.0/
https://creativecommons.org/licenses/by/4.0/
LDraw is a trademark of the Estate of James Jessiman. LEGO is a trademark of the LEGO Group, which does not sponsor,
authorize or endorse this software.
+2
View File
@@ -38,6 +38,8 @@
| `tests/fixtures/vp8video/vp80-*.ivf` | the VP8 test vectors of the libvpx test data (vp80-00-comprehensive-001..018 and others) | WebM Project, BSD-3-Clause + patent grant: [libvpx-LICENSE.txt](libvpx-LICENSE.txt) |
| `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) |
| `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data |
| `src/Formats/model/ldraw/Colors.luau` (the built-in colour table) | the !COLOUR list of LDConfig.ldr (LDraw.org Parts Library, UPDATE 2025-05-20), reformatted | CC BY 2.0 / CC BY 4.0: [LDRAW_COLOURS.txt](LDRAW_COLOURS.txt) |
| `tests/gen/ldraw_*` (read at fixture time from the nix store, not committed) | LDraw.org Parts Library parts and sample models (complete.zip, as packaged for nixpkgs' LeoCAD) | CC BY 2.0 / CC BY 4.0, test data |
Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this
folder (see docs/STYLE.md, "Absorbing an existing repo").
+12
View File
@@ -422,6 +422,18 @@ local list: { Entry } = {
return require("@formats/model/gltf")
end,
},
{
name = "ldraw",
category = "model",
path = "model/ldraw",
extensions = { "ldr", "mpd", "dat" },
mime = { "application/x-ldraw", "application/x-multi-part-ldraw" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
caps = { decode = true, encode = false, materials = true, lines = true, instancing = true },
load = function()
return require("@formats/model/ldraw")
end,
},
{
name = "obj",
category = "model",
+319
View File
@@ -0,0 +1,319 @@
--!strict
-- model/ldraw/Colors: the LDraw colour table: code -> { name, rgb, edge, alpha, luminance, finish }, parsed from
-- !COLOUR lines. The built-in table is the colour list of LDraw.org's LDConfig.ldr (UPDATE 2025-05-20; CC BY 2.0, see
-- licenses/LDRAW_COLOURS.txt), one line per colour without the "0 !COLOUR " prefix and with the MATERIAL parameters cut
-- after the material's type. Colours are 0xRRGGBB (sRGB); an edge is a colour code or a direct colour 0x2RRGGBB.
local Colors = {}
export type Colour = { name: string, rgb: number, edge: number, alpha: number, luminance: number, finish: string? }
export type Table = { [number]: Colour }
local FINISHES = { CHROME = true, PEARLESCENT = true, RUBBER = true, MATTE_METALLIC = true, METAL = true }
-- entry(rest) -> code, Colour | nil: one "Name CODE n VALUE #RRGGBB EDGE #RRGGBB|code [ALPHA a] [LUMINANCE l] ..."
function Colors.entry(rest: string): (number?, Colour?)
local words: { string } = {}
for w in string.gmatch(rest, "%S+") do
table.insert(words, w)
end
local name = words[1]
local code, rgb, edge: number?, alpha, lum, finish = nil, nil, nil, 255, 0, nil
local i = 2
while i <= #words do
local k, v = words[i], words[i + 1]
if k == "CODE" and v then
code = tonumber(v)
i += 1
elseif k == "VALUE" and v and rgb == nil then
rgb = tonumber(string.match(v, "^#(%x%x%x%x%x%x)$") or "", 16)
i += 1
elseif k == "EDGE" and v then
local hex = string.match(v, "^#(%x%x%x%x%x%x)$")
edge = if hex then 0x2000000 + (tonumber(hex, 16) :: number) else tonumber(v)
i += 1
elseif k == "ALPHA" and v then
alpha = math.clamp(tonumber(v) or 255, 0, 255)
i += 1
elseif k == "LUMINANCE" and v then
lum = math.clamp(tonumber(v) or 0, 0, 255)
i += 1
elseif FINISHES[k] then
finish = k
elseif k == "MATERIAL" and v then
finish = v
break
end
i += 1
end
if not name or not code or not rgb or code % 1 ~= 0 then
return nil, nil
end
return code, { name = name, rgb = rgb :: number, edge = edge or 0x2333333, alpha = alpha, luminance = lum, finish = finish }
end
-- parse(text, into?) -> into (a new table by default) with every "0 !COLOUR" line of text added
function Colors.parse(text: string, into: Table?): Table
local t: Table = into or {}
for line in string.gmatch(text, "[^\n]+") do
local rest = string.match(line, "^%s*0%s+!COLOUR%s+(.-)%s*$")
if rest then
local code, c = Colors.entry(rest)
if code and c then
t[code] = c
end
end
end
return t
end
local BUILTIN = [[
Black CODE 0 VALUE #1B2A34 EDGE #808080
Blue CODE 1 VALUE #1E5AA8 EDGE #333333
Green CODE 2 VALUE #00852B EDGE #333333
Dark_Turquoise CODE 3 VALUE #069D9F EDGE #333333
Red CODE 4 VALUE #B40000 EDGE #333333
Dark_Pink CODE 5 VALUE #D3359D EDGE #333333
Brown CODE 6 VALUE #543324 EDGE #1E1E1E
Light_Grey CODE 7 VALUE #8A928D EDGE #333333
Dark_Grey CODE 8 VALUE #545955 EDGE #333333
Light_Blue CODE 9 VALUE #97CBD9 EDGE #333333
Bright_Green CODE 10 VALUE #58AB41 EDGE #333333
Light_Turquoise CODE 11 VALUE #00AAA4 EDGE #333333
Salmon CODE 12 VALUE #F06D61 EDGE #333333
Pink CODE 13 VALUE #F6A9BB EDGE #333333
Yellow CODE 14 VALUE #FAC80A EDGE #333333
White CODE 15 VALUE #F4F4F4 EDGE #333333
Light_Green CODE 17 VALUE #ADD9A8 EDGE #333333
Light_Yellow CODE 18 VALUE #FFD67F EDGE #333333
Tan CODE 19 VALUE #D7BA8C EDGE #333333
Light_Violet CODE 20 VALUE #AFBED6 EDGE #333333
Purple CODE 22 VALUE #671F81 EDGE #333333
Dark_Blue_Violet CODE 23 VALUE #0E3E9A EDGE #333333
Orange CODE 25 VALUE #D67923 EDGE #333333
Magenta CODE 26 VALUE #901F76 EDGE #333333
Lime CODE 27 VALUE #A5CA18 EDGE #333333
Dark_Tan CODE 28 VALUE #897D62 EDGE #333333
Bright_Pink CODE 29 VALUE #FF9ECD EDGE #333333
Medium_Lavender CODE 30 VALUE #A06EB9 EDGE #333333
Lavender CODE 31 VALUE #CDA4DE EDGE #333333
Very_Light_Orange CODE 68 VALUE #FDC383 EDGE #333333
Bright_Reddish_Lilac CODE 69 VALUE #8A12A8 EDGE #333333
Reddish_Brown CODE 70 VALUE #5F3109 EDGE #808080
Light_Bluish_Grey CODE 71 VALUE #969696 EDGE #333333
Dark_Bluish_Grey CODE 72 VALUE #646464 EDGE #333333
Medium_Blue CODE 73 VALUE #7396C8 EDGE #333333
Medium_Green CODE 74 VALUE #7FC475 EDGE #333333
Light_Pink CODE 77 VALUE #FECCCF EDGE #333333
Light_Nougat CODE 78 VALUE #FFC995 EDGE #333333
Medium_Nougat CODE 84 VALUE #AA7D55 EDGE #333333
Medium_Lilac CODE 85 VALUE #441A91 EDGE #333333
Light_Brown CODE 86 VALUE #7B5D41 EDGE #333333
Blue_Violet CODE 89 VALUE #1C58A7 EDGE #333333
Nougat CODE 92 VALUE #BB805A EDGE #333333
Light_Salmon CODE 100 VALUE #F9B7A5 EDGE #333333
Violet CODE 110 VALUE #26469A EDGE #333333
Medium_Violet CODE 112 VALUE #4861AC EDGE #333333
Medium_Lime CODE 115 VALUE #B7D425 EDGE #333333
Aqua CODE 118 VALUE #9CD6CC EDGE #333333
Light_Lime CODE 120 VALUE #DEEA92 EDGE #333333
Light_Orange CODE 125 VALUE #F9A777 EDGE #333333
Dark_Nougat CODE 128 VALUE #AD6140 EDGE #333333
Very_Light_Bluish_Grey CODE 151 VALUE #C8C8C8 EDGE #333333
Bright_Light_Orange CODE 191 VALUE #FCAC00 EDGE #333333
Bright_Light_Blue CODE 212 VALUE #9DC3F7 EDGE #333333
Rust CODE 216 VALUE #872B17 EDGE #333333
Reddish_Lilac CODE 218 VALUE #8E5597 EDGE #333333
Lilac CODE 219 VALUE #564E9D EDGE #333333
Bright_Light_Yellow CODE 226 VALUE #FFEC6C EDGE #333333
Sky_Blue CODE 232 VALUE #77C9D8 EDGE #333333
Dark_Blue CODE 272 VALUE #19325A EDGE #333333
Dark_Green CODE 288 VALUE #00451A EDGE #808080
Flamingo_Pink CODE 295 VALUE #FF94C2 EDGE #333333
Dark_Brown CODE 308 VALUE #352100 EDGE #808080
Maersk_Blue CODE 313 VALUE #ABD9FF EDGE #333333
Dark_Red CODE 320 VALUE #720012 EDGE #333333
Dark_Azure CODE 321 VALUE #469BC3 EDGE #333333
Medium_Azure CODE 322 VALUE #68C3E2 EDGE #333333
Light_Aqua CODE 323 VALUE #D3F2EA EDGE #333333
Yellowish_Green CODE 326 VALUE #E2F99A EDGE #333333
Olive_Green CODE 330 VALUE #77774E EDGE #333333
Sand_Red CODE 335 VALUE #88605E EDGE #333333
Medium_Dark_Pink CODE 351 VALUE #F785B1 EDGE #333333
Coral CODE 353 VALUE #FF6D77 EDGE #333333
Earth_Orange CODE 366 VALUE #D86D2C EDGE #333333
Neon_Yellow CODE 368 VALUE #EDFF21 EDGE #333333
Medium_Brown CODE 370 VALUE #755945 EDGE #333333
Medium_Tan CODE 371 VALUE #CCA373 EDGE #333333
Sand_Purple CODE 373 VALUE #75657D EDGE #333333
Sand_Green CODE 378 VALUE #708E7C EDGE #333333
Sand_Blue CODE 379 VALUE #70819A EDGE #333333
Reddish_Orange CODE 402 VALUE #CA4C0B EDGE #333333
Sienna_Brown CODE 422 VALUE #915C3C EDGE #333333
Umber_Brown CODE 423 VALUE #543F33 EDGE #333333
Fabuland_Brown CODE 450 VALUE #D27744 EDGE #333333
Medium_Orange CODE 462 VALUE #F58624 EDGE #333333
Dark_Orange CODE 484 VALUE #91501C EDGE #333333
Very_Light_Grey CODE 503 VALUE #BCB4A5 EDGE #333333
Light_Orange_Brown CODE 507 VALUE #FA9C1C EDGE #333333
Fabuland_Red CODE 508 VALUE #C65127 EDGE #333333
Fabuland_Orange CODE 509 VALUE #CF8A47 EDGE #333333
Fabuland_Lime CODE 510 VALUE #78FC78 EDGE #333333
Trans_Dark_Blue CODE 33 VALUE #0020A0 EDGE #000B38 ALPHA 128
Trans_Green CODE 34 VALUE #237841 EDGE #174F2B ALPHA 128
Trans_Bright_Green CODE 35 VALUE #56E646 EDGE #27AF18 ALPHA 128
Trans_Red CODE 36 VALUE #C91A09 EDGE #660D05 ALPHA 128
Trans_Dark_Pink CODE 37 VALUE #DF6695 EDGE #B9275F ALPHA 128
Trans_Neon_Orange CODE 38 VALUE #FF800D EDGE #A85100 ALPHA 128
Trans_Very_Light_Blue CODE 39 VALUE #C1DFF0 EDGE #6FB4DC ALPHA 128
Trans_Brown CODE 40 VALUE #635F52 EDGE #2A2823 ALPHA 128
Trans_Medium_Blue CODE 41 VALUE #559AB7 EDGE #326276 ALPHA 128
Trans_Neon_Green CODE 42 VALUE #C0FF00 EDGE #739900 ALPHA 128
Trans_Light_Blue CODE 43 VALUE #AEE9EF EDGE #59D1DE ALPHA 128
Trans_Bright_Reddish_Lilac CODE 44 VALUE #96709F EDGE #5F4365 ALPHA 128
Trans_Pink CODE 45 VALUE #FC97AC EDGE #F9345B ALPHA 128
Trans_Yellow CODE 46 VALUE #F5CD2F EDGE #B49208 ALPHA 128
Trans_Clear CODE 47 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 128
Trans_Purple CODE 52 VALUE #A5A5CB EDGE #6464A6 ALPHA 128
Trans_Neon_Yellow CODE 54 VALUE #DAB000 EDGE #755E00 ALPHA 128
Trans_Orange CODE 57 VALUE #F08F1C EDGE #9E5C0A ALPHA 128
Trans_Black_IR_Lens CODE 32 VALUE #000000 EDGE #333333 ALPHA 210
Trans_Neon_Red CODE 158 VALUE #F18EBB EDGE #E63384 ALPHA 128
Trans_Bright_Light_Green CODE 227 VALUE #B5D96C EDGE #86B22E ALPHA 128
Trans_Bright_Light_Orange CODE 231 VALUE #FCB76D EDGE #FA860A ALPHA 128
Trans_Fire_Yellow CODE 234 VALUE #FBE890 EDGE #F7D22B ALPHA 128
Trans_Reddish_Lilac CODE 284 VALUE #C281A5 EDGE #944771 ALPHA 128
Trans_Light_Green CODE 285 VALUE #7DC291 EDGE #46955D ALPHA 128
Trans_Light_Blue_Violet CODE 293 VALUE #6BABE4 EDGE #247BC6 ALPHA 128
Trans_Black CODE 10375 VALUE #212121 EDGE #545454 ALPHA 128
Chrome_Antique_Brass CODE 60 VALUE #645A4C EDGE #665B4D CHROME
Chrome_Blue CODE 61 VALUE #6C96BF EDGE #3D638A CHROME
Chrome_Green CODE 62 VALUE #3CB371 EDGE #226741 CHROME
Chrome_Pink CODE 63 VALUE #AA4D8E EDGE #632C52 CHROME
Chrome_Black CODE 64 VALUE #1B2A34 EDGE #3D5F76 CHROME
Chrome_Gold CODE 334 VALUE #DFC176 EDGE #C2982E CHROME
Chrome_Silver CODE 383 VALUE #CECECE EDGE #9C9C9C CHROME
Pearl_Black CODE 83 VALUE #0A1327 EDGE #333333 PEARLESCENT
Copper CODE 134 VALUE #764D3B EDGE #333333 PEARLESCENT
Pearl_Light_Grey CODE 135 VALUE #A0A0A0 EDGE #333333 PEARLESCENT
Metallic_Blue CODE 137 VALUE #5B7590 EDGE #333333 PEARLESCENT
Pearl_Light_Gold CODE 142 VALUE #DEAC66 EDGE #333333 PEARLESCENT
Pearl_Dark_Gold CODE 147 VALUE #83724F EDGE #333333 PEARLESCENT
Pearl_Dark_Grey CODE 148 VALUE #484D48 EDGE #333333 PEARLESCENT
Pearl_Very_Light_Grey CODE 150 VALUE #989B99 EDGE #333333 PEARLESCENT
Pearl_Red CODE 176 VALUE #945148 EDGE #333333 PEARLESCENT
Pearl_Yellow CODE 178 VALUE #AB673A EDGE #333333 PEARLESCENT
Pearl_Silver CODE 179 VALUE #898788 EDGE #333333 PEARLESCENT
Pearl_White CODE 183 VALUE #F6F2DF EDGE #333333 PEARLESCENT
Metallic_Bright_Red CODE 184 VALUE #D60026 EDGE #333333 PEARLESCENT
Metallic_Bright_Blue CODE 185 VALUE #0059A3 EDGE #333333 PEARLESCENT
Metallic_Dark_Green CODE 186 VALUE #008E3C EDGE #333333 PEARLESCENT
Pearl_Brown CODE 187 VALUE #57392C EDGE #333333 PEARLESCENT
Reddish_Gold CODE 189 VALUE #AC8247 EDGE #333333 PEARLESCENT
Lemon_Metallic CODE 200 VALUE #708224 EDGE #333333 PEARLESCENT
Pearl_Gold CODE 297 VALUE #AA7F2E EDGE #333333 PEARLESCENT
Metallic_Silver CODE 80 VALUE #767676 EDGE #333333 METAL
Metallic_Green CODE 81 VALUE #C2C06F EDGE #333333 METAL
Metallic_Gold CODE 82 VALUE #DBAC34 EDGE #333333 METAL
Metallic_Dark_Grey CODE 87 VALUE #3E3C39 EDGE #333333 METAL
Metallic_Copper CODE 300 VALUE #C27F53 EDGE #333333 METAL
Metallic_Light_Blue CODE 10045 VALUE #97CBD9 EDGE #333333 METAL
Metallic_Pink CODE 10046 VALUE #AD659A EDGE #333333 METAL
Metallic_Light_Pink CODE 10049 VALUE #FECCCF EDGE #333333 METAL
Milky_White CODE 79 VALUE #EEEEEE EDGE #BABABA ALPHA 240
Glow_In_Dark_Opaque CODE 21 VALUE #E0FFB0 EDGE #B8FF4D ALPHA 240 LUMINANCE 15
Glow_In_Dark_Trans CODE 294 VALUE #BDC6AD EDGE #8D9D72 ALPHA 240 LUMINANCE 15
Glow_In_Dark_White CODE 329 VALUE #F5F3D7 EDGE #E0DA85 ALPHA 240 LUMINANCE 15
Glitter_Trans_Dark_Pink CODE 114 VALUE #DF6695 EDGE #B9275F ALPHA 128 MATERIAL GLITTER
Glitter_Trans_Clear CODE 117 VALUE #EEEEEE EDGE #BABABA ALPHA 128 MATERIAL GLITTER
Glitter_Trans_Purple CODE 129 VALUE #640061 EDGE #000000 ALPHA 128 MATERIAL GLITTER
Glitter_Trans_Light_Blue CODE 302 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 MATERIAL GLITTER
Glitter_Trans_Neon_Green CODE 339 VALUE #C0FF00 EDGE #739900 ALPHA 128 MATERIAL GLITTER
Glitter_Trans_Orange CODE 341 VALUE #F08F1C EDGE #9E5C0A ALPHA 128 MATERIAL GLITTER
Opal_Trans_Clear CODE 360 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 240 LUMINANCE 5 MATERIAL GLITTER
Opal_Trans_Light_Blue CODE 362 VALUE #AEE9EF EDGE #59D1DE ALPHA 200 LUMINANCE 5 MATERIAL GLITTER
Opal_Trans_Black CODE 363 VALUE #635F52 EDGE #2A2823 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER
Opal_Trans_Dark_Pink CODE 364 VALUE #DF6695 EDGE #B9275F ALPHA 200 LUMINANCE 5 MATERIAL GLITTER
Opal_Trans_Purple CODE 365 VALUE #671F81 EDGE #441456 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER
Opal_Trans_Green CODE 367 VALUE #237841 EDGE #174F2B ALPHA 200 LUMINANCE 5 MATERIAL GLITTER
Glitter_Trans_Bright_Green CODE 10351 VALUE #56E646 EDGE #27AF18 ALPHA 128 MATERIAL GLITTER
Opal_Trans_Dark_Blue CODE 10366 VALUE #0020A0 EDGE #000B38 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER
Speckle_Black_Copper CODE 75 VALUE #000000 EDGE #AB6038 MATERIAL SPECKLE
Speckle_Dark_Bluish_Grey_Silver CODE 76 VALUE #635F61 EDGE #898788 MATERIAL SPECKLE
Speckle_Black_Silver CODE 132 VALUE #000000 EDGE #898788 MATERIAL SPECKLE
Speckle_Black_Gold CODE 133 VALUE #000000 EDGE #DBAC34 MATERIAL SPECKLE
Rubber_Yellow CODE 65 VALUE #FAC80A EDGE #333333 RUBBER
Rubber_Black CODE 256 VALUE #1B2A34 EDGE #808080 RUBBER
Rubber_Blue CODE 273 VALUE #1E5AA8 EDGE #333333 RUBBER
Rubber_Red CODE 324 VALUE #B40000 EDGE #333333 RUBBER
Rubber_Orange CODE 350 VALUE #D67923 EDGE #333333 RUBBER
Rubber_Light_Grey CODE 375 VALUE #8A928D EDGE #333333 RUBBER
Rubber_Dark_Blue CODE 406 VALUE #19325A EDGE #333333 RUBBER
Rubber_Purple CODE 449 VALUE #671F81 EDGE #333333 RUBBER
Rubber_Lime CODE 490 VALUE #A5CA18 EDGE #333333 RUBBER
Rubber_Light_Bluish_Grey CODE 496 VALUE #969696 EDGE #333333 RUBBER
Rubber_Flat_Silver CODE 504 VALUE #898788 EDGE #333333 RUBBER
Rubber_White CODE 511 VALUE #F4F4F4 EDGE #333333 RUBBER
Rubber_Green CODE 10002 VALUE #00852B EDGE #333333 RUBBER
Rubber_Bright_Green CODE 10010 VALUE #58AB41 EDGE #333333 RUBBER
Rubber_Tan CODE 10019 VALUE #D7BA8C EDGE #333333 RUBBER
Rubber_Magenta CODE 10026 VALUE #901F76 EDGE #333333 RUBBER
Rubber_Bright_Pink CODE 10029 VALUE #FF9ECD EDGE #333333 RUBBER
Rubber_Medium_Lavender CODE 10030 VALUE #A06EB9 EDGE #333333 RUBBER
Rubber_Lavender CODE 10031 VALUE #CDA4DE EDGE #333333 RUBBER
Rubber_Reddish_Brown CODE 10070 VALUE #5F3109 EDGE #808080 RUBBER
Rubber_Dark_Bluish_Grey CODE 10072 VALUE #646464 EDGE #333333 RUBBER
Rubber_Medium_Blue CODE 10073 VALUE #7396C8 EDGE #333333 RUBBER
Rubber_Light_Nougat CODE 10078 VALUE #FFC995 EDGE #333333 RUBBER
Rubber_Bright_Light_Yellow CODE 10226 VALUE #FFEC6C EDGE #333333 RUBBER
Rubber_Dark_Brown CODE 10308 VALUE #352100 EDGE #808080 RUBBER
Rubber_Dark_Red CODE 10320 VALUE #720012 EDGE #333333 RUBBER
Rubber_Dark_Azure CODE 10321 VALUE #469BC3 EDGE #333333 RUBBER
Rubber_Medium_Azure CODE 10322 VALUE #68C3E2 EDGE #333333 RUBBER
Rubber_Light_Aqua CODE 10323 VALUE #D3F2EA EDGE #333333 RUBBER
Rubber_Sand_Green CODE 10378 VALUE #708E7C EDGE #333333 RUBBER
Rubber_Dark_Orange CODE 10484 VALUE #91501C EDGE #333333 RUBBER
Rubber_Trans_Yellow CODE 66 VALUE #F5CD2F EDGE #B49208 ALPHA 128 RUBBER
Rubber_Trans_Clear CODE 67 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 128 RUBBER
Rubber_Trans_Bright_Green CODE 10035 VALUE #56E646 EDGE #27AF18 ALPHA 128 RUBBER
Rubber_Trans_Red CODE 10036 VALUE #C91A09 EDGE #660D05 ALPHA 128 RUBBER
Rubber_Trans_Light_Blue CODE 10043 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 RUBBER
Canvas_Black CODE 20000 VALUE #1B2A34 EDGE #808080 MATERIAL FABRIC
Canvas_Blue CODE 20001 VALUE #1E5AA8 EDGE #333333 MATERIAL FABRIC
Canvas_Green CODE 20002 VALUE #00852B EDGE #333333 MATERIAL FABRIC
Canvas_Red CODE 20004 VALUE #B40000 EDGE #333333 MATERIAL FABRIC
Canvas_Bright_Green CODE 20010 VALUE #58AB41 EDGE #333333 MATERIAL FABRIC
Canvas_Yellow CODE 20014 VALUE #FAC80A EDGE #333333 MATERIAL FABRIC
Canvas_White CODE 20015 VALUE #F4F4F4 EDGE #333333 MATERIAL FABRIC
Canvas_Reddish_Brown CODE 20070 VALUE #5F3109 EDGE #808080 MATERIAL FABRIC
Canvas_Light_Brown CODE 20086 VALUE #7B5D41 EDGE #333333 MATERIAL FABRIC
Canvas_Dark_Green CODE 20288 VALUE #00451A EDGE #808080 MATERIAL FABRIC
Canvas_Cream CODE 20500 VALUE #F8F3E4 EDGE #333333 MATERIAL FABRIC
Main_Colour CODE 16 VALUE #FFFF80 EDGE #333333
Edge_Colour CODE 24 VALUE #7F7F7F EDGE #333333
Magnet CODE 493 VALUE #656761 EDGE #333333 METAL
Electric_Contact_Alloy CODE 494 VALUE #D0D0D0 EDGE #333333 METAL
Electric_Contact_Copper CODE 495 VALUE #AE7A59 EDGE #333333 METAL
Trans_Sticker CODE 10047 VALUE #FFFFFF EDGE #FFFFFF ALPHA 16
]]
local cache: Table? = nil
-- builtin() -> a fresh copy of the LDConfig.ldr table (callers may add to it)
function Colors.builtin(): Table
if not cache then
local t: Table = {}
for line in string.gmatch(BUILTIN, "[^\n]+") do
local code, c = Colors.entry(line)
if code and c then
t[code] = c
end
end
cache = t
end
local copy: Table = {}
for k, v in cache :: Table do
copy[k] = v
end
return copy
end
return Colors
+580
View File
@@ -0,0 +1,580 @@
--!strict
-- model/ldraw/Read: LDraw text -> Types.Scene (see model/ldraw for the mapping). Files are parsed once into command
-- lists (MPD sections, then sub-files through opts.files / opts.resolve with the library paths); parts are baked into
-- one mesh per (part, colour, inversion), with the BFC rules applied inside the part; model files become nodes.
-- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from).
local Types = require("@formats/Types")
local Colors = require("@formats/model/ldraw/Colors")
local Read = {}
export type Options = {
resolve: ((uri: string) -> any)?,
files: { [string]: any }?,
ldconfig: string?,
color: number?,
upright: boolean?,
flatten: boolean?,
lines: boolean?,
optionalLines: boolean?,
maxDepth: number?,
maxTriangles: number?,
maxNodes: number?,
}
-- a parsed line: k = 0 (a BFC state change: cw / clip), 1 (a reference: v = x y z a b c d e f g h i), 2..5
type Cmd = { k: number, c: number, v: { number }, name: string?, inv: boolean?, step: number?, cw: boolean?, clip: boolean? }
type File = {
name: string,
key: string,
cmds: { Cmd },
certified: boolean,
org: string?,
refs: number,
library: boolean,
main: boolean,
title: string?,
author: string?,
model: boolean?,
}
type Group = { mode: string, colour: number, ds: boolean, pos: { number }, ctrl: { number }? }
local PREFIXES = { "", "parts/", "p/", "parts/s/", "models/" }
local LIBRARY = { ["parts/"] = true, ["p/"] = true, ["parts/s/"] = true }
local FLIP = { 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1 }
local IDENTITY12 = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 }
local function norm(name: string): string
return string.lower((string.gsub(string.match(name, "^%s*(.-)%s*$") or name, "\\", "/")))
end
local function srgbToLinear(v: number): number
return if v <= 0.04045 then v / 12.92 else ((v + 0.055) / 1.055) ^ 2.4
end
-- parse(text, name) -> File (colour definitions go into colours as they are met)
local function parse(text: string, name: string, colours: Colors.Table, stats: { bad: number, lines: number }): File
local f: File = { name = name, key = norm(name), cmds = {}, certified = false, refs = 0, library = false, main = false }
local cmds = f.cmds
local invert, step, first = false, 1, true
for line in string.gmatch(text, "[^\n]+") do
local t = string.match(line, "^%s*(%d)%s")
if t then
stats.lines += 1
end
if t == "0" then
local w1, rest = string.match(line, "^%s*0%s+(%S+)%s*(.-)%s*$")
if w1 == "BFC" and rest then
local u = string.upper(rest)
local cmd: Cmd? = nil
for word in string.gmatch(u, "%S+") do
if word == "CERTIFY" then
f.certified = true
elseif word == "NOCERTIFY" then
f.certified = false
elseif word == "INVERTNEXT" then
invert = true
elseif word == "CW" or word == "CCW" or word == "CLIP" or word == "NOCLIP" then
local c: Cmd = cmd or { k = 0, c = 0, v = IDENTITY12 }
cmd = c
if word == "CW" or word == "CCW" then
c.cw = word == "CW"
else
c.clip = word == "CLIP"
end
end
end
if cmd then
table.insert(cmds, cmd)
end
elseif w1 == "!COLOUR" then
Colors.parse(line, colours)
elseif w1 == "!LDRAW_ORG" and rest then
f.org = string.match(rest, "^(%S+)")
elseif w1 == "STEP" then
step += 1
elseif w1 == "Author:" then
f.author = rest
elseif w1 == "Name:" or w1 == "FILE" or w1 == "NOFILE" or w1 == "!HISTORY" or w1 == "!LICENSE" then
-- (headers)
elseif first and w1 and string.sub(w1, 1, 1) ~= "!" and w1 ~= "//" then
f.title = (string.match(line, "^%s*0%s+(.-)%s*$"))
end
first = false
elseif t then
first = false
local k = tonumber(t) :: number
local inv = invert
invert = false
if k == 1 then
local c, x, y, z, a, b, cc, d, e, ff, g, h, i, file = string.match(line, "^%s*1%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(.-)%s*$")
local v = { tonumber(a), tonumber(b), tonumber(cc), tonumber(x), tonumber(d), tonumber(e), tonumber(ff), tonumber(y), tonumber(g), tonumber(h), tonumber(i), tonumber(z) }
local code = tonumber(c)
local complete = true
for j = 1, 12 do
if v[j] == nil then
complete = false
end
end
if file and file ~= "" and complete and code and code >= 0 and code % 1 == 0 then
table.insert(cmds, { k = 1, c = code, v = v :: { number }, name = file, inv = inv, step = step })
f.refs += 1
else
stats.bad += 1
end
elseif k >= 2 and k <= 5 then
local need = if k == 2 then 6 elseif k == 3 then 9 else 12
local v: { number } = {}
local code: number? = nil
local n = 0
for w in string.gmatch(line, "%S+") do
n += 1
if n == 2 then
code = tonumber(w)
elseif n > 2 and n <= need + 2 then
local num = tonumber(w)
if not num then
break
end
v[n - 2] = num
end
end
if code and code >= 0 and code % 1 == 0 and #v == need then
table.insert(cmds, { k = k, c = code, v = v })
else
stats.bad += 1
end
elseif k ~= 0 then
stats.bad += 1
end
end
end
return f
end
-- scene(text, opts) -> Scene | nil, message, kind
function Read.scene(text: string, opts: Options?): (Types.Scene?, string?, string?)
local o: Options = opts or {}
local colours = Colors.builtin()
if type(o.ldconfig) == "string" then
Colors.parse(o.ldconfig, colours)
end
local maxDepth = o.maxDepth or 64
local maxTriangles = o.maxTriangles or 2 ^ 24
local maxNodes = o.maxNodes or 2 ^ 20
local withLines = o.lines ~= false
local withOptional = o.optionalLines == true
local stats = { bad = 0, lines = 0 }
-- ------------------------------------------------------------------------------------------ MPD sections
text = string.gsub(text, "\r", "")
local sections: { [string]: string } = {}
local mainName: string? = nil
local mpd = string.find(text, "^%s*0%s+FILE%s") ~= nil or string.find(text, "\n%s*0%s+FILE%s") ~= nil
local mainText = text
if mpd then
local cur: string? = nil
local buf: { string } = {}
local function close()
if cur and sections[cur] == nil then
sections[cur] = table.concat(buf, "\n")
end
cur, buf = nil, {}
end
for line in string.gmatch(text, "[^\n]+") do
local fname = string.match(line, "^%s*0%s+FILE%s+(.-)%s*$")
if fname then
close()
cur = norm(fname)
if not mainName then
mainName = fname
end
elseif string.find(line, "^%s*0%s+NOFILE%f[%W]") then
close()
elseif cur then
table.insert(buf, line)
end
end
close()
mainText = sections[norm(mainName or "")] or ""
end
-- ------------------------------------------------------------------------------------------ files
local cache: { [string]: File | false } = {}
local missing: { [string]: boolean } = {}
local fetchFiles = o.files
local resolve = o.resolve
local function fetch(uri: string): string?
local v: any = if type(fetchFiles) == "table" then fetchFiles[uri] else nil
if v == nil and type(resolve) == "function" then
local ok, res = pcall(resolve, uri)
v = if ok then res else nil
end
return if type(v) == "buffer" then buffer.tostring(v) elseif type(v) == "string" then v else nil
end
local function lookup(name: string): File?
local key = norm(name)
local have = cache[key]
if have ~= nil then
return have or nil
end
local sec = sections[key]
if sec then
local f = parse(sec, name, colours, stats)
cache[key] = f
return f
end
local slash = string.gsub(string.match(name, "^%s*(.-)%s*$") or name, "\\", "/")
for _, prefix in PREFIXES do
for _, cand in { prefix .. slash, prefix .. key } do
local data = fetch(cand)
if data then
local f = parse((string.gsub(data, "\r", "")), name, colours, stats)
f.library = LIBRARY[prefix] == true
cache[key] = f
return f
end
end
end
missing[key] = true
cache[key] = false
return nil
end
local function isModel(f: File): boolean
local m = f.model
if m == nil then
local org = string.lower(f.org or "")
local orgPart = org ~= "" and not string.find(org, "model", 1, true)
if f.main then
m = not orgPart and f.refs > 0
else
local ext = string.match(f.key, "%.(%w+)$")
m = not orgPart and not f.library and (ext == "ldr" or ext == "mpd")
end
f.model = m
end
return m :: boolean
end
-- ------------------------------------------------------------------------------------------ colours, materials
local scene = Types.Scene.new()
local function edgeOf(c: number): number
local e = colours[c]
if e then
return e.edge
end
return if c >= 0x2000000 then 0x2000000 else 0x2333333
end
local function resolveColour(code: number, cur: number): number
if code == 16 then
return cur
elseif code == 24 then
return edgeOf(cur)
end
return code
end
local materialOf: { [string]: number } = {}
local function material(col: number, ds: boolean): number
local key = col .. (if ds then "d" else "")
local have = materialOf[key]
if have then
return have
end
local entry = colours[col]
local rgb, alpha, name, finish = 0x7F7F7F, 255, "Unknown_" .. col, nil
if entry then
rgb, alpha, name, finish = entry.rgb, entry.alpha, entry.name, entry.finish
elseif col >= 0x2000000 and col < 0x4000000 then
rgb = col % 0x1000000
alpha = if col >= 0x3000000 then 128 else 255
name = string.format("#%06X", rgb)
elseif col >= 0x4000000 and col < 0x8000000 then
-- dithered: two 12-bit colours, shown as their mean
local lo, hi = col % 0x1000, (col // 0x1000) % 0x1000
local function ch(v: number, s: number): number
return ((v // s) % 16) * 17
end
rgb = ((ch(lo, 256) + ch(hi, 256)) // 2) * 65536 + ((ch(lo, 16) + ch(hi, 16)) // 2) * 256 + (ch(lo, 1) + ch(hi, 1)) // 2
alpha = if col >= 0x7000000 then 0 elseif col >= 0x5000000 then 128 else 255
name = string.format("Dither_%X", col)
end
local m = Types.Scene.material(name)
m.baseColor = { srgbToLinear((rgb // 65536) / 255), srgbToLinear(((rgb // 256) % 256) / 255), srgbToLinear((rgb % 256) / 255), alpha / 255 }
if alpha < 255 then
m.alphaMode = "blend"
end
m.doubleSided = ds
m.metallic = 0
m.roughness = 0.35
if finish == "CHROME" or finish == "METAL" then
m.metallic, m.roughness = 1, if finish == "CHROME" then 0.15 else 0.4
elseif finish == "PEARLESCENT" or finish == "MATTE_METALLIC" then
m.metallic, m.roughness = 0.6, 0.45
elseif finish == "RUBBER" then
m.roughness = 0.9
end
m.extras = { ldraw = { code = col, name = name, edge = edgeOf(col), finish = finish, luminance = if entry and entry.luminance > 0 then entry.luminance else nil } }
table.insert(scene.materials, m)
materialOf[key] = #scene.materials
return #scene.materials
end
-- ------------------------------------------------------------------------------------------ baking
local failure: string?, failKind: string? = nil, nil
local triangles = 0
local cycles = 0
local function fail(msg: string, kind: string?)
if not failure then
failure, failKind = msg, kind
end
end
-- bake(file, m (3x4 row-major), colour, inv, certified, depth, stack, groups, order, direct)
local function bake(f: File, m: { number }, colour: number, inv: boolean, certified: boolean, depth: number, stack: { [File]: boolean }, groups: { [string]: Group }, order: { Group }, direct: boolean)
if failure then
return
end
if depth > maxDepth then
return fail("limit: sub-files nested deeper than " .. maxDepth, "limit")
end
stack[f] = true
local model = isModel(f)
local m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12 = table.unpack(m)
local det = m1 * (m6 * m11 - m7 * m10) - m2 * (m5 * m11 - m7 * m9) + m3 * (m5 * m10 - m6 * m9)
local cw, clip = false, true
local function group(mode: string, col: number, ds: boolean): Group
local key = mode .. col .. (if ds then "d" else "")
local g = groups[key]
if not g then
g = { mode = mode, colour = col, ds = ds, pos = {}, ctrl = if mode == "optional" then {} else nil }
groups[key] = g
table.insert(order, g)
end
return g
end
local function put(list: { number }, x: number, y: number, z: number)
local n = #list
list[n + 1] = m1 * x + m2 * y + m3 * z + m4
list[n + 2] = m5 * x + m6 * y + m7 * z + m8
list[n + 3] = m9 * x + m10 * y + m11 * z + m12
end
for _, cmd in f.cmds do
if failure then
break
end
local k = cmd.k
local v = cmd.v
if k == 0 then
if cmd.cw ~= nil then
cw = cmd.cw :: boolean
end
if cmd.clip ~= nil then
clip = cmd.clip :: boolean
end
elseif k == 1 then
if not direct then
local sub = lookup(cmd.name :: string)
if sub and stack[sub] then
cycles += 1
elseif sub then
local a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12 = table.unpack(v)
local child = {
m1 * a1 + m2 * a5 + m3 * a9, m1 * a2 + m2 * a6 + m3 * a10, m1 * a3 + m2 * a7 + m3 * a11, m1 * a4 + m2 * a8 + m3 * a12 + m4,
m5 * a1 + m6 * a5 + m7 * a9, m5 * a2 + m6 * a6 + m7 * a10, m5 * a3 + m6 * a7 + m7 * a11, m5 * a4 + m6 * a8 + m7 * a12 + m8,
m9 * a1 + m10 * a5 + m11 * a9, m9 * a2 + m10 * a6 + m11 * a10, m9 * a3 + m10 * a7 + m11 * a11, m9 * a4 + m10 * a8 + m11 * a12 + m12,
}
local childCert = if model then true else certified and f.certified and clip
bake(sub, child, resolveColour(cmd.c, colour), inv ~= (cmd.inv == true), childCert, depth + 1, stack, groups, order, false)
end
end
elseif k == 3 or k == 4 then
local col = resolveColour(cmd.c, colour)
local one = certified and f.certified and clip
local g = group("triangles", col, not one)
local rev = cw ~= inv ~= (det < 0)
local p = g.pos
local nt = if k == 3 then 1 else 2
triangles += nt
if triangles > maxTriangles then
return fail(string.format("limit: more than %d triangles", maxTriangles), "limit")
end
local function tri(a: number, b: number, c: number)
if rev then
a, c = c, a
end
put(p, v[a * 3 + 1], v[a * 3 + 2], v[a * 3 + 3])
put(p, v[b * 3 + 1], v[b * 3 + 2], v[b * 3 + 3])
put(p, v[c * 3 + 1], v[c * 3 + 2], v[c * 3 + 3])
end
tri(0, 1, 2)
if k == 4 then
tri(0, 2, 3)
end
elseif k == 2 and withLines then
local g = group("lines", resolveColour(cmd.c, colour), false)
put(g.pos, v[1], v[2], v[3])
put(g.pos, v[4], v[5], v[6])
elseif k == 5 and withOptional then
local g = group("optional", resolveColour(cmd.c, colour), false)
put(g.pos, v[1], v[2], v[3])
put(g.pos, v[4], v[5], v[6])
local ctrl = g.ctrl :: { number }
for _ = 1, 2 do
put(ctrl, v[7], v[8], v[9])
put(ctrl, v[10], v[11], v[12])
end
end
end
stack[f] = nil
end
local function f32(list: { number }, from: number, step: number, count: number): Types.Accessor
local b = buffer.create(count * 12)
for i = 0, count - 1 do
local s = from + i * step
buffer.writef32(b, i * 12, list[s])
buffer.writef32(b, i * 12 + 4, list[s + 1])
buffer.writef32(b, i * 12 + 8, list[s + 2])
end
return Types.Scene.accessor(b, "f32", 3, count)
end
-- the mesh of a file baked at the identity (nil when it has no geometry)
local meshOf: { [string]: number | false } = {}
local function meshFor(f: File, colour: number, inv: boolean, direct: boolean): number?
local key = f.key .. "|" .. colour .. "|" .. (if inv then "i" else "") .. (if direct then "d" else "")
local have = meshOf[key]
if have ~= nil then
return have or nil
end
local groups: { [string]: Group } = {}
local order: { Group } = {}
bake(f, IDENTITY12, colour, inv, true, 0, {}, groups, order, direct)
local mesh: Types.Mesh = { name = f.name, primitives = {} }
for _, g in order do
local count = #g.pos // 3
if count > 0 then
local prim: Types.Primitive = { attributes = { POSITION = f32(g.pos, 1, 3, count) }, mode = if g.mode == "triangles" then "triangles" else "lines" }
prim.material = material(g.colour, g.ds)
if g.mode == "optional" then
local ctrl = g.ctrl :: { number }
prim.attributes._CONTROL_0 = f32(ctrl, 1, 6, count)
prim.attributes._CONTROL_1 = f32(ctrl, 4, 6, count)
prim.extras = { ldraw = { optional = true } }
end
table.insert(mesh.primitives, prim)
end
end
if #mesh.primitives == 0 then
meshOf[key] = false
return nil
end
table.insert(scene.meshes, mesh)
meshOf[key] = #scene.meshes
return #scene.meshes
end
-- ------------------------------------------------------------------------------------------ the node tree
local mainFile = parse(mainText, mainName or "main", colours, stats)
mainFile.main = true
if stats.lines == 0 then
return nil, "no LDraw lines", nil
end
if mainName then
cache[norm(mainName)] = mainFile
end
local mainColour = o.color or 16
local function newNode(node: Types.Node): number
table.insert(scene.nodes, node)
if #scene.nodes > maxNodes then
fail(string.format("limit: more than %d nodes", maxNodes), "limit")
end
return #scene.nodes
end
local function expand(f: File, colour: number, inv: boolean, out: { number }, depth: number, stack: { [File]: boolean })
if failure then
return
end
if depth > maxDepth then
return fail("limit: sub-models nested deeper than " .. maxDepth, "limit")
end
stack[f] = true
local direct = meshFor(f, colour, inv, true)
if direct then
table.insert(out, newNode({ name = f.name, children = {}, mesh = direct }))
end
for _, cmd in f.cmds do
if failure then
break
end
if cmd.k == 1 then
local sub = lookup(cmd.name :: string)
if sub and stack[sub] then
cycles += 1
elseif sub then
local v = cmd.v
local c = resolveColour(cmd.c, colour)
local subInv = inv ~= (cmd.inv == true)
local node: Types.Node = {
name = cmd.name,
children = {},
matrix = { v[1], v[5], v[9], 0, v[2], v[6], v[10], 0, v[3], v[7], v[11], 0, v[4], v[8], v[12], 1 },
extras = { ldraw = { file = sub.name, color = c, step = cmd.step, invert = if subInv then true else nil } },
}
local index = newNode(node)
if isModel(sub) then
expand(sub, c, subInv, node.children, depth + 1, stack)
else
node.mesh = meshFor(sub, c, subInv, false)
end
table.insert(out, index)
end
end
end
stack[f] = nil
end
local top: { number } = {}
if o.flatten or not isModel(mainFile) then
local mesh = meshFor(mainFile, mainColour, false, false)
table.insert(top, newNode({ name = mainFile.name, children = {}, mesh = mesh }))
else
expand(mainFile, mainColour, false, top, 0, {})
end
if failure then
return nil, failure, failKind
end
if o.upright == false then
scene.roots = top
else
table.insert(scene.nodes, { name = "LDraw", children = top, matrix = table.clone(FLIP) })
scene.roots = { #scene.nodes }
scene.meta.up = "y"
end
scene.meta.unit = 0.0004
local missingList: { string } = {}
for k in missing do
table.insert(missingList, k)
end
table.sort(missingList)
local nfiles = 0
for _, f in cache do
if f then
nfiles += 1
end
end
scene.meta.source = {
format = "ldraw",
mpd = mpd,
name = mainName,
title = mainFile.title,
author = mainFile.author,
files = nfiles,
missing = missingList,
cycles = cycles,
badLines = stats.bad,
up = if o.upright == false then "-y" else nil,
}
return scene, nil, nil
end
return Read
+105
View File
@@ -0,0 +1,105 @@
--!strict
-- model/ldraw: LDraw (.ldr / .dat / .mpd), read. Written from the LDraw File Format specification 1.0.2, the MPD and
-- BFC (back face culling) language extensions and the colour definition (!COLOUR) extension (ldraw.org); checked
-- against an independent expansion in the fixture generator and LeoCAD's OBJ export of library parts and models.
-- Reads: line types 0 (meta: Name / Author / !LDRAW_ORG / STEP / !COLOUR / BFC), 1 (sub-file references: colour +
-- 3x4 matrix), 2 (lines), 3 (triangles), 4 (quads, split in two), 5 (optional lines: skipped, or opts.optionalLines
-- -> "lines" primitives with _CONTROL_0 / _CONTROL_1 attributes and prim.extras.ldraw.optional). MPD files split at
-- `0 FILE` / `0 NOFILE` (the first file is the model); other sub-files come through opts.files / opts.resolve, tried
-- as written (backslashes as slashes), then lower case, under "", "parts/", "p/", "parts/s/" and "models/". Missing
-- sub-files are skipped and listed (meta.source.missing); a file that places itself is skipped (meta.source.cycles).
-- Scene: parts (files whose !LDRAW_ORG type is not a model, library files, .dat sub-files, a main file without
-- references) are baked into one mesh per (part, colour, INVERTNEXT), shared by every placement; models (the main
-- file, .ldr / .mpd sub-models) become nodes: one node per reference with the reference's matrix (node.extras.ldraw =
-- { file, color, step, invert? }), a model's own geometry on an extra node. opts.flatten bakes the whole model into one
-- mesh. Primitives: one "triangles" primitive per colour (and per one- / double-sided), "lines" for type 2 (opts.lines
-- = false drops them); no normals, no indices (each triangle has its own three vertices).
-- BFC, inside a part: CERTIFY / NOCERTIFY, CW / CCW, CLIP / NOCLIP and INVERTNEXT; faces are written counter-clockwise
-- (glTF's front faces) after the reference matrices' mirroring; faces of uncertified files (and their sub-files) or
-- under NOCLIP get double-sided materials. Model files do not limit the certification of the parts they place.
-- Colours: 16 (the parent's colour; opts.color at the top, default 16 "Main_Colour"), 24 (the parent colour's edge
-- colour), codes from the built-in LDConfig.ldr table (model/ldraw/Colors; !COLOUR lines in the files and opts.ldconfig
-- text add or replace entries), direct colours 0x2RRGGBB (opaque) / 0x3RRGGBB (transparent) and the old dithered
-- 0x4-0x7 codes. One material per colour (baseColor linear, ALPHA -> blend, CHROME / METAL / PEARLESCENT / RUBBER ->
-- metallic / roughness; extras.ldraw = { code, name, edge, finish?, luminance? }).
-- Axes: LDraw is right-handed with -Y up, 1 LDU = 0.4 mm. The vertices and matrices keep LDraw's values; a root node
-- "LDraw" turns the model 180 degrees about X so the scene is Y up (meta.up = "y", meta.unit = 0.0004); opts.upright =
-- false leaves it out (meta.up = nil, meta.source.up = "-y").
-- meta.source = { format, mpd, name?, title?, author?, files, missing, cycles, badLines, up? }.
-- Not supported: writing; !TEXMAP and !DATA (texture mapping, embedded images: ignored); the LDCad / MLCad / LPub meta
-- commands (ignored); BFC in model files' references (models place parts as certified).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Sniff = require("@formats/core/Sniff")
local Types = require("@formats/Types")
local Read = require("@formats/model/ldraw/Read")
local Colors = require("@formats/model/ldraw/Colors")
-- ------------------------------------------------------------------------------------------------ contract
local Ldraw = {
name = "ldraw",
category = "model",
extensions = { "ldr", "mpd", "dat" },
mime = { "application/x-ldraw", "application/x-multi-part-ldraw" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
caps = { decode = true, encode = false, materials = true, lines = true, instancing = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
resolve: ((uri: string) -> any)?, -- sub-files (parts, primitives) by library path (the api sets it for paths)
files: { [string]: any }?, -- or: the files by library path ("parts/3001.dat", "p/stud.dat", ...)
ldconfig: string?, -- LDConfig.ldr text: its !COLOUR lines add to / replace the built-in colours
color: number?, -- the colour of code 16 at the top (default 16, "Main_Colour")
upright: boolean?, -- add the root node turning -Y up into Y up (default true)
flatten: boolean?, -- one mesh for the whole model instead of a node per reference (default false)
lines: boolean?, -- type 2 edge lines as "lines" primitives (default true)
optionalLines: boolean?, -- type 5 optional lines too (default false)
maxDepth: number?, -- sub-file nesting (default 64)
maxTriangles: number?, -- default 2^24
maxNodes: number?, -- default 2^20
}
-- ------------------------------------------------------------------------------------------------ sniff
function Ldraw.sniff(r: Bytes.Reader): number
local head = Sniff.text(r, 2048, true)
if string.find(head, "^0%s+FILE%s") then
return 0.9
end
if string.find(head, "\n%s*1%s+%S+" .. string.rep("%s+[-+%deE.]+", 12) .. "%s+[^\n]+%.[dDlL][aAdD][tTrR]%s*\r?\n") then
return 0.8
end
if string.find(head, "^0[ \t]+%a") and string.find(head, "\n%s*[1-5]%s+%S+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]") then
return 0.4
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Ldraw.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local text = Sniff.dropBom(buffer.readstring(r.buf, r.base, r.limit - r.base))
-- the scene builder is plain (not native) code: a bug there must not escape as an error
local ok, scene, msg, kind = pcall(Read.scene, text, opts)
if not ok then
return nil, Err.new(Err.CORRUPT, "bad model: " .. tostring(scene))
end
if not scene then
return nil, Err.from(msg, nil, kind)
end
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- colors(ldconfig?) -> { [code] = { name, rgb (0xRRGGBB sRGB), edge (a code or 0x2RRGGBB), alpha (0..255), luminance,
-- finish? } }: the built-in LDConfig.ldr table, with the !COLOUR lines of ldconfig added
function Ldraw.colors(ldconfig: string?): { [number]: any }
local t = Colors.builtin()
if ldconfig then
Colors.parse(ldconfig, t)
end
return t
end
return Ldraw
+226
View File
@@ -0,0 +1,226 @@
-- model/ldraw tests: hand-written LDraw files (a brick of primitives found through library paths, an MPD with
-- embedded parts and sub-models, BFC CW / CCW / INVERTNEXT / NOCLIP / uncertified files, mirrored references, colours
-- 16 / 24 / direct / local !COLOUR, optional lines, a missing part, a self-reference, bad lines, CRLF) and real library
-- parts and models (3001, 3062b, 4073, 3626c, car.ldr, pyramid.ldr) against an independent expansion in the generator
-- (world triangles per colour, double-sided faces, lines, area, signed volume of the one-sided faces, bounds, missing
-- files) and LeoCAD's OBJ export (bounds, area); node / flattened / un-flipped scenes agree; mesh sharing; the
-- built-in colour table against LDConfig.ldr; resolve; error codes; the fuzz no-throw pass. Fixtures:
-- tools/fixtures/ldraw.py.
local T = require("@tests/T")
local Ldraw = require("@formats/model/ldraw")
local MeshOps = require("@formats/ops/MeshOps")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Cases = require("@tests/gen/ldraw_cases")
local Config = require("@tests/gen/ldraw_config")
local t = T.suite("ldraw")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Ldraw.decode(Bytes.reader(b), 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
t:eq(Ldraw.name, "ldraw", "name")
t:eq(Ldraw.category, "model", "category")
t:check(Ldraw.caps.decode and not Ldraw.caps.encode, "caps")
t:check(Ldraw.sniff(Bytes.reader(buffer.fromstring("0 FILE main.ldr\n1 16 0 0 0 1 0 0 0 1 0 0 0 1 a.dat\n"))) >= 0.9, "sniff MPD")
t:check(Ldraw.sniff(Bytes.reader(buffer.fromstring("0 x\n1 16 0 0 0 1 0 0 0 1 0 0 0 1 3001.dat\n"))) >= 0.8, "sniff LDR")
t:eq(Ldraw.sniff(Bytes.reader(buffer.fromstring("solid cube\n facet normal 0 0 1\n"))), 0, "sniff other")
-- ------------------------------------------------------------------------------------------------ colour table
do
local tbl = Ldraw.colors()
local bad = 0
for _, c in Config.colours do
local e = tbl[c[1]]
if not e or e.rgb ~= c[2] or e.edge ~= c[3] or e.alpha ~= c[4] then
bad += 1
end
end
t:eq(bad, 0, "built-in colours = LDConfig.ldr (" .. #Config.colours .. " colours)")
local over = Ldraw.colors("0 !COLOUR Mine CODE 4 VALUE #010203 EDGE 0\n")
t:check(over[4].rgb == 0x010203 and over[4].edge == 0 and over[4].name == "Mine", "ldconfig overrides")
end
-- ------------------------------------------------------------------------------------------------ measuring
type Stats = { triangles: number, lines: number, optional: number, ds: number, area: number, volume: number, colours: { [number]: number } }
local function det3(m: { number }): number
return m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3])
end
local function measure(scene: any): Stats
local s: Stats = { triangles = 0, lines = 0, optional = 0, ds = 0, area = 0, volume = 0, colours = {} }
for _, pl in Types.Scene.flatten(scene) do
local p = pl.primitive
local n = p.attributes.POSITION.count
if p.mode == "lines" then
if p.extras and p.extras.ldraw and p.extras.ldraw.optional then
s.optional += n // 2
else
s.lines += n // 2
end
else
local mat = scene.materials[p.material]
local code = mat.extras.ldraw.code
s.colours[code] = (s.colours[code] or 0) + n // 3
s.triangles += n // 3
if mat.doubleSided then
s.ds += n // 3
end
local m = pl.matrix
local flip = det3(m) < 0
local get = assert(Types.Scene.reader(p.attributes.POSITION))
for tri = 0, n // 3 - 1 do
local q = {}
for k = 0, 2 do
local x, y, z = get(tri * 3 + k, 0), get(tri * 3 + k, 1), get(tri * 3 + k, 2)
q[k + 1] = { m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] }
end
local a, b, c = q[1], q[2], q[3]
if flip then
a, c = c, a
end
local ux, uy, uz, vx, vy, vz = b[1] - a[1], b[2] - a[2], b[3] - a[3], c[1] - a[1], c[2] - a[2], c[3] - a[3]
local x, y, z = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
s.area += math.sqrt(x * x + y * y + z * z) / 2
if not mat.doubleSided then
s.volume += (a[1] * (b[2] * c[3] - b[3] * c[2]) - a[2] * (b[1] * c[3] - b[3] * c[1]) + a[3] * (b[1] * c[2] - b[2] * c[1])) / 6
end
end
end
end
return s
end
local function compare(label: string, s: Stats, w: any)
t:eq(s.triangles, w.triangles, label .. ": triangles")
t:eq(s.ds, w.doubleSided, label .. ": double-sided triangles")
t:eq(s.lines, w.lines, label .. ": lines")
local bad = {}
for _, pair in w.colours do
if s.colours[pair[1]] ~= pair[2] then
table.insert(bad, string.format("%d: %s / %d", pair[1], tostring(s.colours[pair[1]]), pair[2]))
end
end
t:check(#bad == 0 and #w.colours == #(function()
local keys = {}
for k in s.colours do
table.insert(keys, k)
end
return keys
end)(), label .. ": triangles per colour " .. table.concat(bad, ", "))
t:check(near(s.area, w.area, 1e-5), string.format("%s: area %.6f / %.6f", label, s.area, w.area))
t:check(near(s.volume, w.volume, 1e-5), string.format("%s: signed volume %.6f / %.6f", label, s.volume, w.volume))
end
-- ------------------------------------------------------------------------------------------------ cases
local samples = {}
local lib: any = nil
for _, c in Cases do
local opts = table.clone(c.opts or {})
opts.files = c.files
local scene, err = decode(c.data, opts)
t:check(scene, c.name .. ": decode: " .. tostring(err))
local w = c.want
compare(c.name, measure(scene), w)
local lo, hi = MeshOps.bounds(assert(MeshOps.merge(scene)))
local ok = lo ~= nil and w.min ~= nil
for k = 1, 3 do
ok = ok and near((lo :: any)[k], w.min[k], 1e-5) and near((hi :: any)[k], w.max[k], 1e-5)
end
t:check(ok, string.format("%s: bounds %s / %s", c.name, table.concat(lo or {}, " "), table.concat(hi or {}, " ")))
t:eq(table.concat(scene.meta.source.missing, ","), table.concat(w.missing, ","), c.name .. ": missing files")
t:check(scene.meta.up == "y" and scene.meta.unit == 0.0004, c.name .. ": meta.up / unit")
-- LeoCAD: its axes are (x, -z, y) of ours, 2 decimals
local lc = c.leocad
if lc then
local lmin = { lo[1], -hi[3], lo[2] }
local lmax = { hi[1], -lo[3], hi[2] }
local good = true
for k = 1, 3 do
good = good and math.abs(lmin[k] - lc.min[k]) < 0.02 and math.abs(lmax[k] - lc.max[k]) < 0.02
end
t:check(good, c.name .. ": bounds (LeoCAD)")
local s = measure(scene)
t:check(near(s.area, lc.area, 2e-4), string.format("%s: area %.3f (LeoCAD %.3f)", c.name, s.area, lc.area))
end
-- the same model flattened into one mesh, and without the root flip
local flat = assert(decode(c.data, { files = c.files, flatten = true }))
t:eq(#flat.meshes <= 1, true, c.name .. ": flatten: one mesh")
compare(c.name .. " (flatten)", measure(flat), w)
local raw = assert(decode(c.data, { files = c.files, upright = false }))
local rlo, rhi = MeshOps.bounds(assert(MeshOps.merge(raw)))
t:check(rlo and near(rlo[2], -hi[2], 1e-6) and near(rhi[3], -lo[3], 1e-6) and raw.meta.source.up == "-y", c.name .. ": upright = false")
if #c.data < 4000 then
table.insert(samples, c.data)
end
if c.name == "two.ldr" then
lib = c.files
-- one mesh per (part, colour): four colours, the missing part has no node
t:eq(#scene.meshes, 4, "two.ldr: meshes per colour")
local root = scene.nodes[scene.roots[1]]
t:eq(#root.children, 4, "two.ldr: one node per placed part")
local steps = {}
for _, ci in root.children do
table.insert(steps, scene.nodes[ci].extras.ldraw.step)
end
t:eq(table.concat(steps, ","), "1,1,1,2", "two.ldr: steps")
-- through resolve instead of files
local viaResolve = assert(decode(c.data, { resolve = function(uri: string): any
return c.files[uri]
end }))
t:eq(measure(viaResolve).triangles, w.triangles, "two.ldr: resolve")
-- optional lines on request
local withOpt = assert(decode(c.data, { files = c.files, optionalLines = true, lines = false }))
local so = measure(withOpt)
t:check(so.optional == w.optional and so.lines == 0, "two.ldr: optional lines only")
elseif c.name == "model.mpd" then
t:check(scene.meta.source.mpd, "model.mpd: mpd")
local meshNodes = 0
for _, n in scene.nodes do
if n.mesh then
meshNodes += 1
end
end
t:check(#scene.meshes < meshNodes, string.format("model.mpd: meshes shared (%d meshes, %d mesh nodes)", #scene.meshes, meshNodes))
local purple
for _, m in scene.materials do
if m.extras.ldraw.code == 1000 then
purple = m
end
end
t:check(purple and purple.name == "Test_Purple" and purple.alphaMode == "blend", "model.mpd: local !COLOUR")
elseif c.name == "badrefs.ldr" then
t:check(scene.meta.source.cycles > 0 and scene.meta.source.badLines == 2, "badrefs.ldr: cycle and bad lines counted")
end
end
-- ------------------------------------------------------------------------------------------------ errors
do
local _, e = decode("")
t:check(e and e.code == Err.CORRUPT, "empty: CORRUPT")
_, e = decode("hello world\nthis is not ldraw\n")
t:check(e and e.code == Err.CORRUPT, "text: CORRUPT")
_, e = decode(Cases[1].data, { files = Cases[1].files, maxTriangles = 10 })
t:check(e and e.code == Err.LIMIT, "maxTriangles: LIMIT")
_, e = decode(Cases[1].data, { files = Cases[1].files, maxDepth = 0 })
t:check(e and e.code == Err.LIMIT, "maxDepth: LIMIT")
end
-- ------------------------------------------------------------------------------------------------ fuzz
t:fuzz("decode", function(b: buffer)
local s = Ldraw.decode(Bytes.reader(b), { files = lib, optionalLines = true })
if s then
MeshOps.merge(s)
end
return s
end, samples, { mutations = 24 })
t:done()
+417
View File
@@ -0,0 +1,417 @@
# LDraw fixtures (tools/fixtures.py): hand-written LDraw files (a brick built from primitives that come through
# `files` with library paths, an MPD with embedded sub-files and sub-models, BFC CERTIFY CW / CCW, INVERTNEXT,
# mirrored references, NOCERTIFY / NOCLIP, colour inheritance 16 / 24, direct colours, local !COLOUR definitions,
# optional lines, a missing part) and real parts and the sample models car.ldr / pyramid.ldr from the LDraw parts
# library (complete.zip, CC BY 2.0 / 4.0, the copy nixpkgs' LeoCAD package uses; read from the nix store, never
# committed: each case carries the files it needs). References: an independent expansion written here (world
# triangles after the decoder's root flip, per colour, lines, area, bounds, signed volume of the one-sided faces) and
# LeoCAD's OBJ export (`leocad -obj`: bounds and area of the real models), plus LDConfig.ldr itself for the built-in
# colour table.
# tests/gen/ldraw_cases.luau { name, data, files = { path -> text }, opts?, want = {...}, leocad? = {...} }
# tests/gen/ldraw_config.luau { text = LDConfig.ldr, colours = { { code, rgb, edge, alpha } } }
import math, os, re, subprocess, zipfile
INPUTS = []
def nix_out(attr):
out = subprocess.run(["nix", "build", attr, "--no-link", "--print-out-paths"], capture_output=True, check=True)
return out.stdout.decode().strip().split("\n")[-1]
def library_zip(leocad):
# LeoCAD's wrapper points LEOCAD_LIB at the parts library zip
wrapper = open(os.path.join(leocad, "bin", "leocad"), "rb").read().decode("latin-1")
m = re.search(r"(/nix/store/[^'\" ]*complete\.zip)", wrapper)
return m.group(1) if m else None
# ---------------------------------------------------------------------------------------------------- reference
def norm(name):
return name.strip().replace("\\", "/").lower()
class Ref:
"""an independent LDraw expansion: every triangle in world space (after the root flip y -> -y, z -> -z)"""
PREFIXES = ("", "parts/", "p/", "parts/s/", "models/")
def __init__(self, main, files, colours):
self.files = {norm(k): v for k, v in files.items()}
self.colours = colours # code -> (rgb, edge)
self.mpd = {}
self.missing = set()
self.tris = [] # (colour, ds, (v0, v1, v2))
self.lines = 0
self.optional = 0
text = main
if re.search(r"^\s*0\s+FILE\s", text, re.M):
cur = None
first = None
for line in text.splitlines():
m = re.match(r"^\s*0\s+FILE\s+(.*?)\s*$", line)
if m:
cur = norm(m.group(1))
first = first or cur
self.mpd[cur] = []
continue
if re.match(r"^\s*0\s+NOFILE\b", line):
cur = None
continue
if cur:
self.mpd[cur].append(line)
self.main = "\n".join(self.mpd[first])
else:
self.main = text
org = re.search(r"^\s*0\s+!LDRAW_ORG\s+(\S+)", self.main, re.M)
refs = re.search(r"^\s*1\s", self.main, re.M)
self.main_part = bool(org and "model" not in org.group(1).lower()) or not refs
def lookup(self, name):
n = norm(name)
if n in self.mpd:
return "\n".join(self.mpd[n])
for p in self.PREFIXES:
if p + n in self.files:
return self.files[p + n]
self.missing.add(n)
return None
def colour(self, code, cur):
if code == 16:
return cur
if code == 24:
return self.edge(cur)
return code
def edge(self, c):
if c in self.colours:
e = self.colours[c][1]
return e
return 0x2333333 if c < 0x2000000 else 0x2000000
def walk(self, text, m, colour, inv, certified, depth, model, stack=()):
# model files (the main file, .ldr / .mpd sub-models) do not limit the certification of what they place
if depth > 64:
return
st = {"cw": False, "cert": None, "clip": True, "invert": False}
for raw in text.splitlines():
t = raw.split()
if not t:
continue
if t[0] == "0":
if len(t) >= 3 and t[1] == "!COLOUR":
self.colours.update({k: (v[0], v[1]) for k, v in parse_ldconfig(raw).items()})
if len(t) >= 3 and t[1] == "BFC":
words = [w.upper() for w in t[2:]]
if "NOCERTIFY" in words:
st["cert"] = False
elif "CERTIFY" in words:
st["cert"] = True
if "CW" in words:
st["cw"] = True
if "CCW" in words:
st["cw"] = False
if "NOCLIP" in words:
st["clip"] = False
elif "CLIP" in words:
st["clip"] = True
if "INVERTNEXT" in words:
st["invert"] = True
continue
invert_next = st["invert"]
st["invert"] = False
try:
kind = int(t[0])
code = int(t[1], 0)
cert = certified and st["cert"] is True and st["clip"]
if kind == 1 and len(t) >= 15:
x, y, z, a, b, c, d, e, f, g, h, i = [float(v) for v in t[2:14]]
loc = [[a, b, c, x], [d, e, f, y], [g, h, i, z]]
name = raw.split(None, 14)[14].strip()
if norm(name) in stack:
continue # a file that (indirectly) places itself
sub = self.lookup(name)
if sub is None:
continue
sub_model = norm(name).endswith((".ldr", ".mpd"))
self.walk(sub, mul(m, loc), self.colour(code, colour), inv ^ invert_next,
(True if model else cert), depth + 1, sub_model, stack + (norm(name),))
elif kind in (3, 4) and len(t) >= 2 + 3 * kind:
pts = [apply(m, [float(v) for v in t[2 + 3 * k:5 + 3 * k]]) for k in range(kind)]
if st["cw"] ^ inv ^ (det(m) < 0):
pts = pts[::-1]
col = self.colour(code, colour)
one = cert and not model or (model and st["cert"] is True and st["clip"])
self.tris.append((col, not one, (pts[0], pts[1], pts[2])))
if kind == 4:
self.tris.append((col, not one, (pts[0], pts[2], pts[3])))
elif kind == 2 and len(t) >= 8:
[float(v) for v in t[2:8]]
self.lines += 1
elif kind == 5 and len(t) >= 14:
[float(v) for v in t[2:14]]
self.optional += 1
except ValueError:
pass
def run(self, main_colour=16):
flip = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0]]
self.walk(self.main, flip, main_colour, False, True, 0, not self.main_part)
return self
def summary(self):
per = {}
area, vol = 0.0, 0.0
lo, hi = [1e30] * 3, [-1e30] * 3
for col, ds, (a, b, c) in self.tris:
per[col] = per.get(col, 0) + 1
for p in (a, b, c):
lo = [min(u, v) for u, v in zip(lo, p)]
hi = [max(u, v) for u, v in zip(hi, p)]
area += tri_area(a, b, c)
if not ds:
vol += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6
out = {"triangles": len(self.tris), "lines": self.lines, "optional": self.optional, "area": area, "volume": vol,
"doubleSided": sum(1 for x in self.tris if x[1]),
"colours": [[k, v] for k, v in sorted(per.items())], "missing": sorted(self.missing)}
if self.tris:
out["min"], out["max"] = lo, hi
return out
def mul(m, l):
# 3x4 affine product m * l
r = [[0.0] * 4 for _ in range(3)]
for i in range(3):
for j in range(4):
s = sum(m[i][k] * l[k][j] for k in range(3))
r[i][j] = s + (m[i][3] if j == 3 else 0)
return r
def apply(m, p):
return [m[i][0] * p[0] + m[i][1] * p[1] + m[i][2] * p[2] + m[i][3] for i in range(3)]
def det(m):
return (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
+ m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]))
def tri_area(a, b, c):
e1 = [b[i] - a[i] for i in range(3)]
e2 = [c[i] - a[i] for i in range(3)]
x = e1[1] * e2[2] - e1[2] * e2[1]
y = e1[2] * e2[0] - e1[0] * e2[2]
z = e1[0] * e2[1] - e1[1] * e2[0]
return math.sqrt(x * x + y * y + z * z) / 2
def parse_ldconfig(text):
out = {}
for line in text.splitlines():
m = re.match(r"^\s*0\s+!COLOUR\s+(\S+)\s+(.*)$", line)
if not m:
continue
t = m.group(2).split()
kv = {}
for i in range(0, len(t) - 1):
if t[i] in ("CODE", "VALUE", "EDGE", "ALPHA") and t[i] not in kv:
kv[t[i]] = t[i + 1]
code = int(kv["CODE"])
rgb = int(kv["VALUE"][1:], 16)
e = kv["EDGE"]
edge = (0x2000000 | int(e[1:], 16)) if e.startswith("#") else int(e)
out[code] = (rgb, edge, int(kv.get("ALPHA", "255")), m.group(1))
return out
# ---------------------------------------------------------------------------------------------------- hand-written
BOX = """0 a unit box primitive (faces outward, CCW)
0 BFC CERTIFY CCW
4 16 -1 -1 -1 1 -1 -1 1 -1 1 -1 -1 1
4 16 -1 1 -1 -1 1 1 1 1 1 1 1 -1
4 16 -1 -1 -1 -1 -1 1 -1 1 1 -1 1 -1
4 16 1 -1 -1 1 1 -1 1 1 1 1 -1 1
4 16 -1 -1 -1 -1 1 -1 1 1 -1 1 -1 -1
4 16 -1 -1 1 1 -1 1 1 1 1 -1 1 1
2 24 -1 -1 -1 1 -1 -1
2 24 -1 -1 -1 -1 1 -1
5 24 -1 -1 -1 -1 1 -1 1 -1 -1 -1 -1 1
"""
BOX_CW = """0 the same box written clockwise
0 BFC CERTIFY CW
4 16 -1 -1 1 1 -1 1 1 -1 -1 -1 -1 -1
4 16 1 1 -1 1 1 1 -1 1 1 -1 1 -1
4 16 -1 1 -1 -1 1 1 -1 -1 1 -1 -1 -1
4 16 1 -1 1 1 1 1 1 1 -1 1 -1 -1
4 16 1 -1 -1 1 1 -1 -1 1 -1 -1 -1 -1
4 16 -1 1 1 1 1 1 1 -1 1 -1 -1 1
"""
TRI = """0 an uncertified triangle
3 16 0 0 0 1 0 0 0 0 1
"""
# a brick: an outer box, an inner box turned inside out (INVERTNEXT), a mirrored stud box, an uncertified triangle
BRICK = """0 Test Brick 1 x 2
0 Name: testbrick.dat
0 Author: formats-luau
0 !LDRAW_ORG Unofficial_Part
0 BFC CERTIFY CCW
1 16 0 12 0 20 0 0 0 12 0 0 0 10 box.dat
0 BFC INVERTNEXT
1 16 0 14 0 18 0 0 0 10 0 0 0 8 box.dat
1 4 10 -2 0 -6 0 0 0 2 0 0 0 6 s\\stud box.dat
1 16 0 -4 0 1 0 0 0 1 0 0 0 1 48\\cwbox.dat
1 16 0 30 0 5 0 0 0 5 0 0 0 5 tri.dat
"""
PLAIN_LDR = """0 Two bricks
0 Name: two.ldr
1 1 0 0 0 1 0 0 0 1 0 0 0 1 testbrick.dat
1 14 60 -24 0 0 0 1 0 1 0 -1 0 0 testbrick.dat
1 16 -60 0 0 -1 0 0 0 1 0 0 0 1 testbrick.dat
0 STEP
1 0x2FF8000 0 -60 0 1 0 0 0 1 0 0 0 1 testbrick.dat
1 4 0 -90 0 1 0 0 0 1 0 0 0 1 nosuchpart.dat
"""
MPD = """0 FILE main.ldr
0 MPD main
0 Name: main.ldr
0 !COLOUR Test_Purple CODE 1000 VALUE #8000FF EDGE #200040 ALPHA 200
1 16 0 0 0 1 0 0 0 1 0 0 0 1 sub.ldr
1 1000 0 -100 0 1 0 0 0 1 0 0 0 1 sub.ldr
1 2 0 50 50 1 0 0 0 -1 0 0 0 1 Embedded Part.dat
3 24 0 0 0 10 0 0 0 10 0
0 NOFILE
0 FILE sub.ldr
0 a sub-model: two parts and a nested sub-model
1 16 0 0 0 1 0 0 0 1 0 0 0 1 embedded part.dat
1 4 30 0 0 1 0 0 0 1 0 0 0 1 embedded part.dat
1 16 0 0 40 1 0 0 0 1 0 0 0 1 inner.ldr
0 NOFILE
0 FILE inner.ldr
1 0x3FF0000 0 0 0 2 0 0 0 2 0 0 0 2 embedded part.dat
0 FILE Embedded Part.dat
0 !LDRAW_ORG Unofficial_Part
0 BFC CERTIFY CCW
1 16 0 0 0 5 0 0 0 5 0 0 0 5 box.dat
0 BFC NOCLIP
3 24 0 -5 0 5 -5 0 0 -5 5
0 BFC CLIP
4 16 -5 -6 -5 5 -6 -5 5 -6 5 -5 -6 5
"""
BAD_REFS = """0 cycles and bad lines are survived
1 16 0 0 0 1 0 0 0 1 0 0 0 1 loop.dat
1 16 0 0 0 1 0 0 0 1
3 16 0 0 0 1 x 0 0 0 1
4 16 0 0 0 1 0 0 1 1 0 0 1 0
"""
LOOP = "0 a file that calls itself\n3 16 0 0 0 1 0 0 0 1 0\n1 16 0 0 0 1 0 0 0 1 0 0 0 1 loop.dat\n"
LIB = {"parts/box.dat": BOX, "p/s/stud box.dat": BOX, "p/48/cwbox.dat": BOX_CW, "p/tri.dat": TRI,
"parts/testbrick.dat": BRICK, "loop.dat": LOOP}
def hand_cases(colours):
cases = []
def add(name, text, files, opts=None):
ref = Ref(text, files, colours).run()
c = {"name": name, "data": text, "files": files, "want": ref.summary()}
if opts:
c["opts"] = opts
cases.append(c)
add("brick.dat", BRICK, {k: v for k, v in LIB.items() if k != "parts/testbrick.dat"})
add("two.ldr", PLAIN_LDR, dict(LIB))
add("model.mpd", MPD, {"parts/box.dat": BOX})
add("badrefs.ldr", BAD_REFS, {"loop.dat": LOOP})
add("crlf.ldr", PLAIN_LDR.replace("\n", "\r\n"), dict(LIB))
return cases
# ---------------------------------------------------------------------------------------------------- real parts
def closure(z, names, text_of):
"""the library files a set of references needs: { library path -> text }"""
have = {}
index = {}
for n in z.namelist():
if n.startswith("ldraw/") and n.lower().endswith(".dat"):
index[n[6:].lower()] = n
todo = list(names)
while todo:
n = norm(todo.pop())
for p in Ref.PREFIXES:
key = p + n
if key in index:
if key not in have:
t = z.read(index[key]).decode("utf-8", "replace")
have[key] = t
for line in t.splitlines():
parts = line.split(None, 14)
if len(parts) == 15 and parts[0] == "1":
todo.append(parts[14].strip())
break
return have
def leocad_obj(leocad, libzip, path, tmp):
out = os.path.join(tmp, "leocad.obj")
env = dict(os.environ, QT_QPA_PLATFORM="offscreen")
subprocess.run([os.path.join(leocad, "bin", "leocad"), "-l", libzip, path, "-obj", out], env=env, capture_output=True, timeout=300, check=True)
vs, area = [], 0.0
lo, hi = [1e30] * 3, [-1e30] * 3
with open(out) as f:
for line in f:
p = line.split()
if not p:
continue
if p[0] == "v":
v = [float(x) for x in p[1:4]]
vs.append(v)
lo = [min(a, b) for a, b in zip(lo, v)]
hi = [max(a, b) for a, b in zip(hi, v)]
elif p[0] == "f":
idx = [int(x.split("/")[0]) - 1 for x in p[1:]]
for k in range(1, len(idx) - 1):
area += tri_area(vs[idx[0]], vs[idx[k]], vs[idx[k + 1]])
return {"min": lo, "max": hi, "area": area}
def generate(ctx):
import tempfile
tmp = tempfile.mkdtemp(prefix="formats-ldraw-")
leocad = nix_out("nixpkgs#leocad")
libzip = library_zip(leocad)
z = zipfile.ZipFile(libzip)
config = z.read("ldraw/LDConfig.ldr").decode("utf-8")
colours = {k: (v[0], v[1]) for k, v in parse_ldconfig(config).items()}
ctx.emit("ldraw_config", {"text": config, "colours": [[k, v[0], v[1], v[2]] for k, v in sorted(parse_ldconfig(config).items())]})
cases = hand_cases(colours)
# real parts and the library's sample models, with LeoCAD's export
reals = [("3001.dat", None), ("3062b.dat", None), ("4073.dat", None), ("3626c.dat", None), ("car.ldr", "ldraw/models/car.ldr"),
("pyramid.ldr", "ldraw/models/pyramid.ldr")]
for name, member in reals:
if member:
text = z.read(member).decode("utf-8", "replace")
else:
text = "0 one part\n1 4 0 0 0 1 0 0 0 1 0 0 0 1 %s\n" % name
files = closure(z, [l.split(None, 14)[14].strip() for l in text.splitlines() if l.split(None, 14)[:1] == ["1"]], None)
ref = Ref(text, files, colours).run()
c = {"name": "library/" + name, "data": text, "files": files, "want": ref.summary()}
p = os.path.join(tmp, "model.ldr")
with open(p, "w") as f:
f.write(text)
try:
c["leocad"] = leocad_obj(leocad, libzip, p, tmp)
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError):
pass
cases.append(c)
ctx.emit("ldraw_cases", cases)