Skip to content

Export drawings to OBJ and GLB through the IOScene scene - #51

Merged
mahach666 merged 34 commits into
feat/scene-adapterfrom
feat/export-obj-glb
Nov 20, 2026
Merged

mahach666 merged 34 commits into
feat/scene-adapterfrom
feat/export-obj-glb

Conversation

@mahach666

Copy link
Copy Markdown
Contributor

What this does

Stacked on #50 (the DwgIO.Scene adapter). Adds the exchange-format exports the reference repos ship (NwcIO: ObjExporter, GlbExporter):

  • DwgSceneExport.SaveObj(document, "drawing.obj", options?) — Wavefront OBJ plus an adjacent MTL library with the effective ACI colours (usemtl/Kd/d). Both files are written as a pair: temporary files first, then moved in, so a failure leaves the previous pair untouched (same discipline as the JSON exporter's atomic replace).
  • DwgSceneExport.SaveGlb(document, "drawing.glb", options?) — binary glTF 2.0 through IOScene.Formats.GlbSceneWriter, which maps line/point topologies onto glTF modes 1/0 and turns instance colours into materials.
  • WriteObj(scene, path) / WriteGlb(scene, path) for callers that already hold a SceneDocument.
  • dwgio drawing.dwg out.obj and dwgio drawing.dwg out.glb dispatch by output extension; .json (and anything else) keeps the existing JSON export.

Both exports go through the same DwgSceneReader conversion, so unit scaling and the conversion report (DwgSceneResult) behave identically to the scene JSON.

Notes

  • IOScene.Formats ships as 0.1.0-preview.1; the IOScene floor moves [0.1.0, …) → [0.1.1, 0.2.0-0.0) because the formats package requires 0.1.1 (NU1605 otherwise).
  • The OBJ records for a lines/points drawing are l/p; the IOScene ObjSceneReader preview currently imports faces only, so the tests assert the OBJ text (65 l records, 1 p record, exact vertices) and round-trip the GLB through GlbSceneReader (element/instance counts and the ACI colours as materials).

Tests

DwgSceneExportTests: OBJ text and MTL pair, atomic replace without leftover temporaries, GLB round trip with colours, unit scaling. Full suite: 113 passed, 7 skipped (private fixtures).

dependabot Bot and others added 4 commits November 18, 2026 01:46
---
updated-dependencies:
- dependency-name: Microsoft.NET.Test.Sdk
  dependency-version: 18.12.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <[email protected]>
---
updated-dependencies:
- dependency-name: Microsoft.SourceLink.GitHub
  dependency-version: 10.0.404
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <[email protected]>
DwgSceneExport writes the IOScene scene of a drawing to Wavefront OBJ
with an adjacent MTL colour library (both files written as a pair and
moved in atomically) and to binary glTF, through the IOScene.Formats
writers. The plain export command dispatches on the output extension,
so dwgio drawing.dwg out.obj and out.glb work like out.json.

IOScene.Formats ships as a preview and needs IOScene 0.1.1 or later,
so the IOScene floor moves from 0.1.0 to 0.1.1.
DwgSvgExporter writes the decoded entities (LINE, CIRCLE, ARC and
POINT) of a drawing as SVG, the first step of #32: the top view with
the drawing's X to the right and Y up, entities in their ACI colours
(BYBLOCK, BYLAYER and 7 render black on the light background), arcs
as SVG arc paths with correct sweep under the y flip, and a viewBox
that covers every drawn entity including the cardinal extremes of an
arc. Skipped non-finite entities are reported in Diagnostics; the
file is written through a temporary file and moved in atomically.

dwgio svg <file.dwg> <out.svg> [--scale n] drives it; --scale sets
pixels per drawing unit, and the stroke width and point markers stay
fixed in pixels while the drawing zooms.
DwgViewerExport.SaveViewer converts the drawing to an IOScene scene
and embeds it with the IOViewer WebGL runtime into one interactive
HTML file (no server, no external scripts); the default viewer title
follows the scene. dwgio drawing.dwg out.html drives it through the
output extension, next to OBJ, GLB and JSON.
…stics

- The DXF 62 colour index takes the low 9 bits of the stored colour
  value (libredwg's common_entity_data split), so BYLAYER (256) is
  reported as 256 and no longer collapses onto BYBLOCK (0); the JSON
  export writes colorIndex for both (#40).
- dwgio formats counts and byte sizes invariantly, so the output does
  not follow the machine's locale (#15).
- dwgio inspect prints the diagnostic total and the first diagnostics
  outside the entities block, so a failed section shows even when no
  entity was decoded (#16); the report is written through a TextWriter
  and covered by CLI tests, including a tr-TR culture run.
The walk used to stop at the first zero run or broken record of
AcDb:AcDbObjects and drop everything past it with no diagnostic.
Now a stop point resynchronises at the next handle-map offset (the
walk is driven by the map), each gap and each unrecoverable stop is
reported in Diagnostics, and a lower inventory-versus-map count is
reported as well. DwgHandleMap.Parse reports truncated blocks and
drops negative-offset entries with a diagnostic instead of casting
them away. Synthetic tests build two records with a zero run between
them, plus a handle map that points at both: both objects are in the
inventory, with a gap diagnostic.

Fixture tests also skip drawings of an unsupported version and count
them in the skip reason, so a single AC1021 drawing in the fixture
folder no longer fails every test (#17).
The encryption check of every optional section reader now runs
through one TryGetReadableSection helper: an encrypted section adds
one diagnostic naming the section instead of the data going missing.
dwgio inspect marks encrypted sections in the section table. A
synthetic section map with encrypted entries is covered by tests;
decrypting such sections stays out of scope.
A drawing without a thumbnail now exits with code 5 instead of the
parse-error code 4, and a requested output extension that does not
match the image kind is reported on standard error while the path is
kept. The preview command writes through a TextWriter and its target
resolution is extracted, both covered by CLI tests. The README and
getting-started exit-code tables document code 5.
dwgio --version/-v prints the package version and --help/-h the
usage, both with exit code 0; an unknown option still exits 1 (#18).

dwgio entities <file.dwg> [--type LINE,CIRCLE] [--json] lists the
decoded entities one line each or as a JSON array; the type filter
is validated against the known type names with a clear error and
exit code 1 (#19). The plain export writes to standard output when
the target is '-', so the same JSON as to a file reaches a pipe
(#19).

The commands run through Run(args, output, error), which the CLI
tests drive directly.
The ProductInformation XML that AppInfoParser stores in ProductXml
carries the product in its name attribute ("AutoCAD", "AutoCAD
LT", "Teigha(R)" per libredwg's appinfo.spec). Both the ANSI and
the UTF-16 layout now extract it into Product, so inspect's
product= and the JSON export name the product. Tests cover the
attribute, its absence, and the existing synthetic Writer case.
- AcDb:RevHistory: layout version pair and the list of save
  references, per libredwg's revhistory.spec.
- AcDb:AuxHeader: the fixed 123-byte layout (intro marker, version
  pair, save counters, Julian-day creation and update times, next
  handle), with AutoCAD's R2018 variant normalised to the ODA order
  before the fields are read, per libredwg's auxheader.spec.
- AcDb:Template: the counted description string and the unit system
  word, per libredwg's template.spec.
- AcDb:AppInfoHistory: walked as a sequence of AppInfo records, one
  per earlier save; the layout is undocumented anywhere, so the walk
  is best effort and stops with a diagnostic where a record does not
  decode.

Each is exposed on DwgDocument, written to the JSON export and
summarised by dwgio inspect. Synthetic tests cover the parsers,
including truncated inputs that produce diagnostics.
A drawing can now come from a stream: a network handle, an archive
entry or an already-open file. The stream is read to memory once, so
the results are identical to Open(path) on the same bytes, and the
unsupported-version message names the source (the path or
"stream"). The same-results gate runs on every available private
drawing through a fixture test.

Reading data pages on demand and the lazy object stream stay open;
this change does not claim them.
…#34, #33)

The build job now runs build+test+pack on windows-latest,
ubuntu-latest and macos-latest for both target frameworks, replacing
the Linux build-only job; the README sentence about Windows-only
tests is updated.

test-files/public is the folder for committed redistributable test
drawings, with the origin and licence recorded next to each file;
TestFiles searches it alongside DWGIO_TEST_FILES and test_files.
The drawings themselves follow (#33 stays open until at least one
drawing per supported release is committed).
#39)

The fixed type codes come from libredwg's include/dwg.h and live in
the public DwgObjectTypes: the name and the entity-or-object flag of
every fixed code 0x01-0x52 plus the proxy codes. Wrong names are
corrected (0x21 is SHAPE, ELLIPSE is 0x23; VERTEX_0B is VERTEX_3D),
the missing ones are added (MINSERT, the seven DIMENSION variants,
POLYLINE_PFACE/MESH, SOLID, TRACE, REGION, BODY, TOLERANCE, the
table and control objects, LWPOLYLINE, PLACEHOLDER, VBA_PROJECT,
LAYOUT, PROXY_ENTITY/OBJECT), OLE2FRAME and LWPOLYLINE count as
entities, and class-defined codes (500+) are reported as Class_502
until the class list is decoded (#21).

DwgObjectInfo.TypeName, the JSON byType keys and the type counts of
dwgio inspect show the names. The README and docs/test-fixtures.md
temper the AC1018 claim: implemented, not yet verified on a real
drawing (#39).
docfx builds only docs/ and reports the file link outside its scope
as an error; the GitHub blob URL works everywhere.
Same as the fix on the CI/fixture PR: docfx builds only docs/ and
reports the out-of-scope file link as an error.
WriteObj replaced the MTL first and the OBJ second, so a failure of
the second move left the old OBJ naming the new MTL. Now the old MTL
is first renamed aside, the new MTL moves in, and the OBJ - which
names that MTL in its mtllib - moves in last; on a failure at either
move the old MTL steps back in (or a failed fresh export leaves no
MTL behind) and the previous pair survives together.

Tests inject both failures: the OBJ destination held open
exclusively (Windows file lock; on Unix the rename would succeed, so
the test skips there) and the old MTL held open, plus a
platform-independent destination-as-directory case for the fresh
export.
@mahach666

Copy link
Copy Markdown
Contributor Author

Подтвердил — баг настоящий: File.Move(mtlTemp, mtlPath) шёл первым, и при сбое второго move старый OBJ оставался с новым MTL. Тест SaveObj_ReplacesExistingFiles действительно покрывал только успешный путь. Спасибо за разбор.

Исправил на ветке PR (ce18d89), со схемой чуть надёжнее предложения с уникальным именем — она закрывает и первый, и второй шаг замены:

  1. Пишутся оба temp-файла (OBJ ссылается на MTL по стабильному имени drawing.mtl, как раньше).
  2. Старый MTL переименовывается в сторону (атомарно; если не вышло — экспорт прерывается до любых изменений).
  3. Новый MTL встаёт на drawing.mtl.
  4. OBJ переносится последним.
  5. Успех → backup удаляется. Сбой на шаге 3 или 4 → backup восстанавливается на место (свежий экспорт, у которого нечего было бэкапить, удаляет созданный MTL) — старый OBJ продолжает ссылаться на свой старый MTL, temp-файлы убираются.

Стабильное имя MTL сохранено (в mtllib всегда drawing.mtl), поэтому вариант с уникальным именем не понадобился: он оставлял бы после каждого успешного экспорта осиротевший MTL от предыдущей записи, либо требовал бы вычищать старый файл по имени из старого OBJ.

Тесты на отказ (как вы и просили — до мержа):

  • SaveObj_SecondMoveFailure_KeepsTheOldPair — OBJ держится открытым с FileShare.None, второй move падает; старая пара побайтово неизменна, temp/backup-файлов не осталось. Помечен Windows-only через SkipException — на Unix переименование поверх открытого файла проходит, инъекция сбоя там не работает (в стеке после Run the tests in CI on all three systems; add the public fixture folder (#34, part of #33) #62 тесты и так пойдут на трёх ОС, где он честно покажется skipped).
  • SaveObj_FirstMoveFailure_KeepsTheOldPair — залочен старый MTL; экспорт прерывается до любых замен, пара нетронута.
  • SaveObj_FailedFreshExport_WritesNothing — платформонезависимая инъекция (путь OBJ — директория): неудачный свежий экспорт не оставляет «половины пары».

Полный набор зелёный: 116 passed / 7 skipped на этой ветке.

mahach666 and others added 9 commits November 20, 2026 04:30
…9c63e180b10a5f232578d9ef96fd62c7c37e' into codex/fix-pr-stack
Complete the fixed object type table and document AC1018 verification (part of #20, closes #39)
Run the tests in CI on all three systems; add the public fixture folder (#34, part of #33)
Add DwgDocument.Open(Stream) (first step of #37)
Read revision history, auxiliary header and template metadata (part of #36)
Fill DwgAppInfo.Product from the product XML (closes #35)
Add --version/--help, an entities command and JSON to stdout (closes #18, closes #19)
Give dwgio preview its own exit code and check the output extension (closes #14)
…tics

Report skipped encrypted sections in Diagnostics and inspect (closes #38)
Resync the object walk at handle-map offsets and report gaps (closes #13, closes #17)
…tics

Fix the 9-bit entity colour index, invariant CLI numbers and inspect diagnostics
Write a standalone interactive HTML viewer of the drawing
Draw model space to SVG (closes #32)
@mahach666
mahach666 merged commit 1205965 into feat/scene-adapter Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant