Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Read FBX models: binary and ASCII FBX into every 3D format and pictures
KnifeLemonfb4677b9e534
diff --git a/README.ko.md b/README.ko.mdindex 727103f7..cab5e6c4 100644--- a/README.ko.md+++ b/README.ko.md@@ -34,7 +34,7 @@<table><tr><td width="33%" valign="top"><b>커서 바로 옆에서</b><br>앱 창을 열 필요가 없어요. 끌고 있는 파일에 맞는 형식만 지금 있는 자리에 나타나요.</td>- <td width="33%" valign="top"><b>244가지 형식, 다른 프로그램 없이</b><br>이미지, PDF, 워드, 엑셀, 파워포인트, HWP, 전자책, 압축 파일, 글꼴, CAD, 3D 모델을 오피스·한컴오피스·LibreOffice 없이 변환해요.</td>+ <td width="33%" valign="top"><b>245가지 형식, 다른 프로그램 없이</b><br>이미지, PDF, 워드, 엑셀, 파워포인트, HWP, 전자책, 압축 파일, 글꼴, CAD, 3D 모델을 오피스·한컴오피스·LibreOffice 없이 변환해요.</td><td width="33%" valign="top"><b>내 컴퓨터 안에서만</b><br>아무것도 업로드하지 않아요. 오프라인으로 동작하고 결과는 원본 옆에 저장해요.</td></tr></table>@@ -102,7 +102,7 @@| **CAD**: DWG, DXF | PDF, SVG, PNG, DWG ↔ DXF || **글꼴**: TTF, OTF, WOFF, WOFF2, EOT | 서로 변환 || **데이터**: JSON, JSON Lines, YAML, TOML, XML · vCard | 서로 변환, CSV·XLSX(표 모양 데이터); vCard ↔ CSV |-| **3D 모델**: GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY | 서로 변환, PNG 미리보기 |+| **3D 모델**: GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY; FBX는 읽기 | 서로 변환, PNG 미리보기 |표시가 없는 형식은 오피스·한컴오피스·LibreOffice 없이 바로 변환돼요.표시가 있는 형식은 추가 엔진이 필요하고, 필요할 때만 내려받아요: ¹ Ghostscript, ² LibreOffice, ³ Pandoc,diff --git a/README.md b/README.mdindex 80df1e70..606bede3 100644--- a/README.md+++ b/README.md@@ -34,7 +34,7 @@<table><tr><td width="33%" valign="top"><b>Right at your cursor</b><br>No app window to open. The formats appear where you already are, only the ones that make sense for the files you drag.</td>- <td width="33%" valign="top"><b>244 formats, no other software</b><br>Images, PDF, Word, Excel, PowerPoint, HWP, e-books, archives, fonts, CAD and 3D models work without Office, Hancom Office or LibreOffice.</td>+ <td width="33%" valign="top"><b>245 formats, no other software</b><br>Images, PDF, Word, Excel, PowerPoint, HWP, e-books, archives, fonts, CAD and 3D models work without Office, Hancom Office or LibreOffice.</td><td width="33%" valign="top"><b>Stays on your computer</b><br>Nothing is uploaded. Filee works offline and saves the result next to the original.</td></tr></table>@@ -102,7 +102,7 @@ Filee shows new releases in its menu and updates itself, keeping your settings a| **CAD**: DWG, DXF | PDF, SVG, PNG, DWG ↔ DXF || **Fonts**: TTF, OTF, WOFF, WOFF2, EOT | each other || **Data**: JSON, JSON Lines, YAML, TOML, XML · vCard | each other, CSV and XLSX (tables); vCard ↔ CSV |-| **3D models**: GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY | each other, PNG preview |+| **3D models**: GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY; FBX read | each other, PNG preview |Unmarked formats work out of the box, without Office, Hancom Office or LibreOffice.Marked ones need an optional engine, downloaded only when needed: ¹ Ghostscript, ² LibreOffice, ³ Pandoc, ⁴ calibre,diff --git a/README.zh-CN.md b/README.zh-CN.mdindex d0d077aa..534ab37f 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -34,7 +34,7 @@<table><tr><td width="33%" valign="top"><b>就在光标旁</b><br>无需打开应用窗口。只显示适合当前拖动文件的格式,就在你所在的位置。</td>- <td width="33%" valign="top"><b>244 种格式,无需其他软件</b><br>图片、PDF、Word、Excel、PowerPoint、HWP、电子书、压缩包、字体、CAD 和 3D 模型,无需 Office、韩文办公软件或 LibreOffice。</td>+ <td width="33%" valign="top"><b>245 种格式,无需其他软件</b><br>图片、PDF、Word、Excel、PowerPoint、HWP、电子书、压缩包、字体、CAD 和 3D 模型,无需 Office、韩文办公软件或 LibreOffice。</td><td width="33%" valign="top"><b>只在你的电脑上</b><br>不上传任何文件。Filee 离线工作,结果保存在原文件旁边。</td></tr></table>@@ -101,7 +101,7 @@| **CAD**:DWG、DXF | PDF、SVG、PNG、DWG ↔ DXF || **字体**:TTF、OTF、WOFF、WOFF2、EOT | 互相转换 || **数据**:JSON、JSON Lines、YAML、TOML、XML · vCard | 互相转换、CSV 和 XLSX(表格数据)、vCard ↔ CSV |-| **3D 模型**:GLB、glTF、STL、OBJ(+ MTL)、3MF、PLY | 互相转换、PNG 预览 |+| **3D 模型**:GLB、glTF、STL、OBJ(+ MTL)、3MF、PLY;FBX 仅读取 | 互相转换、PNG 预览 |未标注的格式装好即用,无需 Office、韩文办公软件或 LibreOffice。标注的格式需要可选引擎,只在需要时下载,分别是 ¹ Ghostscript、² LibreOffice、³ Pandoc、⁴ calibre、⁵ FFmpegdiff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 25901fbe..579a2e17 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -24,7 +24,7 @@ Filee chooses engines automatically. Settings → *Engines* shows their status,| **E-books** | built in | **EPUB, MOBI/AZW/AZW3/PRC, FB2, HTMLZ, TXTZ → EPUB, HWPX (→ PDF), TXT, HTML, Markdown, FB2, HTMLZ, TXTZ**; HTML, Markdown, TXT, DOCX → EPUB/FB2/HTMLZ/TXTZ; HTML → TXT; comics CBZ/CBR/CB7/CBT/CBC → PDF, EPUB, CBZ; PDF → CBZ; AZW4 → PDF; **EPUB ↔ KEPUB** (Kobo) || CAD (ACadSharp + built-in renderer) | built in (library) | **DWG ↔ DXF**; DWG/DXF → **PDF** (vector), **SVG**, PNG, JPG, WEBP, TIFF, BMP, GIF, ICO, AVIF || **Subtitles** | built in | **SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, TTML, MicroDVD, SCC → SRT, ASS, WebVTT, SAMI, LRC, TTML, MicroDVD**, always UTF-8 (Korean CP949 / EUC-KR files read correctly) |-| 3D models (SharpGLTF for glTF) | built in (library) | **GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY ↔ each other**; → PNG, JPG, … (an isometric preview) |+| 3D models (SharpGLTF for glTF) | built in (library) | **GLB, glTF, STL, OBJ (+ MTL), 3MF, PLY ↔ each other**; FBX → each of them; → PNG, JPG, … (an isometric preview) || rhwp | bundled with the installer (`engines/rhwp`) | HWP/HWPX → PDF, **HWP → HWPX, HWPX → HWP** || Archives (7-Zip) | bundled with the installer (`engines/7zip`, ~2.5 MB) + built-in readers | ZIP, 7Z, RAR, TAR (+ GZ/BZ2/XZ/Z/7Z/LZ), CAB, ISO, DMG, … **→ folder, ZIP, 7Z, TAR, TAR.GZ/BZ2/XZ**; ALZ, EGG, lzip read in-process; "Compress into one archive" for any files || LibreOffice + H2Orestart + Java | **optional download** (~420 MB, 1.3 GB on disk) | older and rare formats only: DOC, XLS, PPT, RTF and OpenDocument → PDF and to each other, output as DOCX/ODT/ODS/ODP; HWP/HWPX → DOCX/ODT; read-only formats (see below) → PDF and their kind's editable formats; FODT, OpenDocument templates (OTT, OTS, OTP) and XLT out; SVG → EMF/WMF/ODG, a PDF page → SVG |@@ -631,17 +631,21 @@ and writes the files; Filee's own renderer draws them with SkiaSharp (one drawin## 3D models-`Filee.Engines/Models3D` converts GLB, glTF, STL, OBJ, 3MF and PLY into each other in managed code: every reader+`Filee.Engines/Models3D` converts GLB, glTF, STL, OBJ, 3MF and PLY into each other, and FBX into any of them, in+managed code: every readerfills one in-memory model (`Model3D`: parts with positions, normals, UVs, vertex colours and triangles; materialswith a base colour and a base colour texture) and every writer takes it, so each pair is one step. glTF and GLB are-read and written with [SharpGLTF](https://github.com/vpenades/SharpGLTF) (MIT); STL, OBJ/MTL, PLY and 3MF are Filee's-own code. No native library (Assimp) and no download.+read and written with [SharpGLTF](https://github.com/vpenades/SharpGLTF) (MIT); STL, OBJ/MTL, PLY, 3MF and the FBX+reader are Filee's own code. No native library (Assimp, the FBX SDK) and no download.- **Units**: STL, OBJ and PLY have none; they are read and written as **millimetres**, as slicers and CAD programstreat them. 3MF has a `unit` attribute (micron to metre) and is written in millimetres. glTF is metres. So a 20 mm- STL cube is 0.02 m in GLB and 20 mm again in STL. There is no preset option for another unit.+ STL cube is 0.02 m in GLB and 20 mm again in STL. FBX has `UnitScaleFactor` (centimetres per unit, 1 when+ missing). There is no preset option for another unit.- **Axes** follow Blender's defaults: STL, 3MF and PLY are Z up, OBJ and glTF Y up, so a part standing on a printer's- bed stands upright in a glTF viewer and comes back on its base.+ bed stands upright in a glTF viewer and comes back on its base. FBX says which axis is up (`UpAxis`, `CoordAxis`+ and their signs in GlobalSettings; the front axis follows, as FBX is right-handed), so 3ds Max's Z-up files stand+ up too.- **Structure**: node hierarchies, 3MF components and build items are flattened: every mesh instance becomes a part inworld coordinates (one glTF node / OBJ object / 3MF object per part). Polygons are triangulated (ear clipping, soconcave faces are right). OBJ negative indices, `\` line continuations and 0–255 vertex colours are understood.@@ -661,6 +665,7 @@ What each format keeps:| STL | binary (also with a header starting with "solid") and ASCII (one part per `solid`) | binary, one solid || OBJ + MTL | `o` / `g` / `usemtl` as parts, `v` (+ r g b), `vt`, `vn`, faces of any size; `mtllib` with `Kd`, `d` / `Tr`, `map_Kd` (options skipped) next to the file | **the `.mtl` and the textures are written next to the `.obj`** (`name.obj`, `name.mtl`, `name_texture.png`, named like the output); vertex colours as `v x y z r g b` || 3MF | objects, components (also in other model parts, as Bambu Studio writes them), build transforms, base materials, colour groups (materials extension); `support` / `other` objects skipped | one object per part, base materials from material colours, a colour group from vertex colours |+| FBX (read only) | binary 6.x–7.x (64-bit records from 7.5, zlib-compressed arrays) and ASCII; mesh geometry with polygons of any size, the first normal, UV, colour and material layer (by polygon vertex, control point or polygon, or all the same; direct or indexed); the model hierarchy from the connections with translation, rotation (every Euler order, pre- / post-rotation, pivots and offsets), scaling and geometric transforms; property templates from Definitions; material `DiffuseColor` and `Opacity`; the diffuse texture embedded (Video `Content`) or named next to the file; animation, skins, blend shapes, NURBS, cameras and lights skipped (the rest pose is read) | — (not written) || PLY | ASCII, binary little / big endian; vertex position, normal, UV (`s`/`t`, `u`/`v`, `texture_u`/`texture_v`), colours of any type; face lists with per-corner `texcoord` and face colours; `comment TextureFile`; other elements skipped | binary little endian, one mesh; material colours become vertex colours |Lost on the way (no place in the target): **STL** keeps only the triangles (no colours, UVs, normals or materials);@@ -678,7 +683,10 @@ at 2048 px and scaled down to 1024 px for smooth edges, on a transparent backgroTests (`tests/Filee.Engines.Tests/ModelTests.cs`) build a cube, a sphere and a fan of coloured triangles in code andconvert each through every format pair, checking triangle counts, bounds, signed volume (winding), normals, UVs,colours and materials where both formats keep them; hand-written STL, OBJ, PLY, 3MF and glTF files cover the reading-details, and a generated 1,000,000-triangle STL the speed.+details, and a generated 1,000,000-triangle STL the speed. `FbxTests.cs` writes FBX files in code (`FbxBuilder`:+binary 7.4 and 7.5, plain and compressed arrays, ASCII): a cube under a moved parent, turned and scaled, with a+templated material and an embedded or neighbouring texture, Z-up files in metres, rotation orders, concave polygons and+materials by polygon, and every cut or flipped byte of a file, which must read or fail with a clear message.## HWPX readerdiff --git a/src/Filee.App/Assets/i18n/en.json b/src/Filee.App/Assets/i18n/en.jsonindex 81b656b6..975d8ab1 100644--- a/src/Filee.App/Assets/i18n/en.json+++ b/src/Filee.App/Assets/i18n/en.json@@ -102,7 +102,7 @@"engine.icns.description": "macOS app icons (ICNS) from and to images.","engine.font.description": "Fonts: TTF, OTF, WOFF, WOFF2 and EOT into each other.","engine.cad.description": "AutoCAD drawings: DWG ↔ DXF, and both to PDF, SVG and PNG.",- "engine.model3d.description": "3D models: GLB, glTF, STL, OBJ, 3MF and PLY into each other, and a PNG preview.",+ "engine.model3d.description": "3D models: GLB, glTF, STL, OBJ, 3MF and PLY into each other, FBX into any of them, and a PNG preview.","engine.archive.description": "Extracts ZIP, 7Z, RAR, TAR, ISO and more, and packs ZIP, 7Z or TAR.GZ (7-Zip).","engine.ebook.description": "EPUB, MOBI, AZW3, FB2 and comics (CBZ, CBR) to PDF, EPUB, DOCX and text.\nAlso documents to EPUB, EPUB to KEPUB for Kobo and PDF to CBZ.","engine.subtitle.description": "Subtitles: SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, TTML, MicroDVD and SCC into each other, saved as UTF-8.\nKorean SMI and SRT files in CP949 / EUC-KR read correctly.",diff --git a/src/Filee.App/Assets/i18n/es.json b/src/Filee.App/Assets/i18n/es.jsonindex c72674de..f8763245 100644--- a/src/Filee.App/Assets/i18n/es.json+++ b/src/Filee.App/Assets/i18n/es.json@@ -95,7 +95,7 @@"engine.icns.description": "Iconos de apps de macOS (ICNS) desde y hacia imágenes.","engine.font.description": "Tipografías: TTF, OTF, WOFF, WOFF2 y EOT entre sí.","engine.cad.description": "Planos de AutoCAD: DWG ↔ DXF, y ambos a PDF, SVG y PNG.",- "engine.model3d.description": "Modelos 3D: GLB, glTF, STL, OBJ, 3MF y PLY entre sí, además de una vista previa en PNG.",+ "engine.model3d.description": "Modelos 3D: GLB, glTF, STL, OBJ, 3MF y PLY entre sí, FBX a cualquiera de ellos, además de una vista previa en PNG.","engine.archive.description": "Extrae ZIP, 7Z, RAR, TAR, ISO y más, y empaqueta en ZIP, 7Z o TAR.GZ (7-Zip).","engine.ebook.description": "EPUB, MOBI, AZW3, FB2 y cómics (CBZ, CBR) a PDF, EPUB, DOCX y texto.\nTambién documentos a EPUB, EPUB a KEPUB para Kobo y PDF a CBZ.","engine.subtitle.description": "Subtítulos: SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, TTML, MicroDVD y SCC entre sí, guardados como UTF-8.\nLee correctamente archivos SMI y SRT coreanos en CP949 / EUC-KR.",diff --git a/src/Filee.App/Assets/i18n/ko.json b/src/Filee.App/Assets/i18n/ko.jsonindex 9325caa2..e31c2486 100644--- a/src/Filee.App/Assets/i18n/ko.json+++ b/src/Filee.App/Assets/i18n/ko.json@@ -102,7 +102,7 @@"engine.icns.description": "macOS 앱 아이콘(ICNS)을 이미지로, 이미지를 ICNS로.","engine.font.description": "글꼴: TTF, OTF, WOFF, WOFF2, EOT를 서로 변환해요.","engine.cad.description": "오토캐드 도면: DWG ↔ DXF, 그리고 둘 다 PDF, SVG, PNG로.",- "engine.model3d.description": "3D 모델: GLB, glTF, STL, OBJ, 3MF, PLY를 서로 변환하고 PNG 미리보기도 만들어요.",+ "engine.model3d.description": "3D 모델: GLB, glTF, STL, OBJ, 3MF, PLY를 서로 변환하고, FBX도 이 형식들로 바꾸고, PNG 미리보기도 만들어요.","engine.archive.description": "ZIP, 7Z, RAR, TAR, ISO 등을 풀고, ZIP·7Z·TAR.GZ로 묶어요(7-Zip).","engine.ebook.description": "EPUB, MOBI, AZW3, FB2, 만화책(CBZ, CBR)을 PDF, EPUB, DOCX, 텍스트로 바꿔요.\n문서는 EPUB으로, EPUB은 코보용 KEPUB으로, PDF는 CBZ로도 만들어요.","engine.subtitle.description": "SRT, ASS/SSA, WebVTT, SAMI(SMI), LRC, TTML, MicroDVD, SCC 자막을 서로 바꾸고 UTF-8로 저장해요.\nCP949/EUC-KR로 된 SMI·SRT 파일도 한글이 깨지지 않아요.",diff --git a/src/Filee.App/Assets/i18n/pl.json b/src/Filee.App/Assets/i18n/pl.jsonindex 83c4309e..13633967 100644--- a/src/Filee.App/Assets/i18n/pl.json+++ b/src/Filee.App/Assets/i18n/pl.json@@ -102,7 +102,7 @@"engine.icns.description": "Ikony aplikacji macOS (ICNS) z obrazów i do obrazów.","engine.font.description": "Czcionki: TTF, OTF, WOFF, WOFF2 i EOT między sobą.","engine.cad.description": "Rysunki AutoCAD: DWG ↔ DXF, oba także do PDF, SVG i PNG.",- "engine.model3d.description": "Modele 3D: GLB, glTF, STL, OBJ, 3MF i PLY między sobą oraz podgląd PNG.",+ "engine.model3d.description": "Modele 3D: GLB, glTF, STL, OBJ, 3MF i PLY między sobą, FBX do każdego z nich oraz podgląd PNG.","engine.archive.description": "Rozpakowuje ZIP, 7Z, RAR, TAR, ISO i inne, pakuje do ZIP, 7Z lub TAR.GZ (7-Zip).","engine.ebook.description": "EPUB, MOBI, AZW3, FB2 i komiksy (CBZ, CBR) do PDF, EPUB, DOCX i tekstu.\nTakże dokumenty do EPUB, EPUB do KEPUB dla Kobo i PDF do CBZ.","engine.subtitle.description": "Napisy: SRT, ASS/SSA, WebVTT, SAMI (SMI), LRC, TTML, MicroDVD i SCC między sobą, zapisywane w UTF-8.\nKoreańskie pliki SMI i SRT w CP949 / EUC-KR są odczytywane poprawnie.",diff --git a/src/Filee.App/Assets/i18n/zh-CN.json b/src/Filee.App/Assets/i18n/zh-CN.jsonindex d800805c..90389f7e 100644--- a/src/Filee.App/Assets/i18n/zh-CN.json+++ b/src/Filee.App/Assets/i18n/zh-CN.json@@ -102,7 +102,7 @@"engine.icns.description": "macOS 应用图标(ICNS)与图片互转。","engine.font.description": "字体:TTF、OTF、WOFF、WOFF2 和 EOT 互相转换。","engine.cad.description": "AutoCAD 图纸:DWG ↔ DXF,并可转为 PDF、SVG 和 PNG。",- "engine.model3d.description": "GLB、glTF、STL、OBJ、3MF 和 PLY 3D 模型互相转换,并可生成 PNG 预览。",+ "engine.model3d.description": "GLB、glTF、STL、OBJ、3MF 和 PLY 3D 模型互相转换,FBX 可转换为其中任意格式,并可生成 PNG 预览。","engine.archive.description": "解压 ZIP、7Z、RAR、TAR、ISO 等,并打包为 ZIP、7Z 或 TAR.GZ(7-Zip)。","engine.ebook.description": "EPUB、MOBI、AZW3、FB2 和漫画(CBZ、CBR)转为 PDF、EPUB、DOCX 和文本。\n也能把文档转为 EPUB、把 EPUB 转为 Kobo 用的 KEPUB、把 PDF 转为 CBZ。","engine.subtitle.description": "SRT、ASS/SSA、WebVTT、SAMI(SMI)、LRC、TTML、MicroDVD、SCC 字幕互转,保存为 UTF-8。\n也能正确读取 CP949/EUC-KR 编码的韩文字幕。",diff --git a/src/Filee.Core/Formats/FormatRegistry.cs b/src/Filee.Core/Formats/FormatRegistry.csindex de25f16c..ee186325 100644--- a/src/Filee.Core/Formats/FormatRegistry.cs+++ b/src/Filee.Core/Formats/FormatRegistry.cs@@ -296,6 +296,7 @@ public static class FormatRegistrynew("obj", "OBJ", FormatCategory.Model3D, ["obj"]),new("3mf", "3MF", FormatCategory.Model3D, ["3mf"]),new("ply", "PLY", FormatCategory.Model3D, ["ply"]),+ new("fbx", "FBX", FormatCategory.Model3D, ["fbx"], Writable: false),];private static readonly Dictionary<string, FileFormat> ById =diff --git a/src/Filee.Core/Presets/BuiltInData.cs b/src/Filee.Core/Presets/BuiltInData.csindex 7ec96870..1ad105a2 100644--- a/src/Filee.Core/Presets/BuiltInData.cs+++ b/src/Filee.Core/Presets/BuiltInData.cs@@ -461,7 +461,7 @@ public static class BuiltInDatareturn profiles;}- /// <summary>3D models: GLB, glTF, STL, OBJ, 3MF, PLY (added in settings schema 15, after "data").</summary>+ /// <summary>3D models: GLB, glTF, STL, OBJ, 3MF, PLY (added in settings schema 15, after "data"), FBX (schema 22).</summary>public static ToolbarProfile ModelProfile() => new(){Id = "models",diff --git a/src/Filee.Core/Settings/AppSettings.cs b/src/Filee.Core/Settings/AppSettings.csindex f1fde541..4d06a85d 100644--- a/src/Filee.Core/Settings/AppSettings.cs+++ b/src/Filee.Core/Settings/AppSettings.cs@@ -64,7 +64,7 @@ public sealed class DonutSettingspublic sealed class AppSettings{/// <summary>Current schema version. Increase when the format changes and add a migration.</summary>- public const int CurrentSchemaVersion = 20;+ public const int CurrentSchemaVersion = 22;public int SchemaVersion { get; set; } = CurrentSchemaVersion;diff --git a/src/Filee.Core/Settings/UserDataStore.cs b/src/Filee.Core/Settings/UserDataStore.csindex 44dd6d23..b53f2d38 100644--- a/src/Filee.Core/Settings/UserDataStore.cs+++ b/src/Filee.Core/Settings/UserDataStore.cs@@ -549,6 +549,11 @@ internal static class SettingsMigrationschanged = true;}}+ // v22: FBX models (read only) open from the 3D donut: it learns ".fbx" unless a donut of the user already+ // takes it. Other extensions the user removed from a built-in donut stay removed. (Schema 21 is taken by+ // other open changes; renumber this step if another change lands first.)+ if (from < 22)+ changed |= LearnExtensions(profiles, out _, ["fbx"]);return changed;}@@ -633,7 +638,8 @@ internal static class SettingsMigrations/// Adds the default extensions of the built-in donuts that no donut of the user takes yet./// </summary>/// <param name="claimed">Every extension a donut takes afterwards.</param>- private static bool LearnExtensions(List<ToolbarProfile> profiles, out HashSet<string> claimed)+ /// <param name="only">Learn only these (the ones a version added), not others the user removed from a donut since.</param>+ private static bool LearnExtensions(List<ToolbarProfile> profiles, out HashSet<string> claimed, IReadOnlyCollection<string>? only = null){var changed = false;// Extensions checked on a mixed-selection profile only limit that profile; they don't claim files.@@ -641,7 +647,7 @@ internal static class SettingsMigrationsvar defaults = BuiltInData.CreateProfiles().ToDictionary(p => p.Id);foreach (var profile in profiles.Where(p => !p.IsFallback && defaults.ContainsKey(p.Id))){- foreach (var extension in defaults[profile.Id].Extensions.Where(claimed.Add))+ foreach (var extension in defaults[profile.Id].Extensions.Where(e => only is null || only.Contains(e)).Where(claimed.Add)){profile.Extensions.Add(extension);changed = true;diff --git a/src/Filee.Engines/Models3D/FbxFormat.cs b/src/Filee.Engines/Models3D/FbxFormat.csnew file mode 100644index 00000000..24f1f1b1--- /dev/null+++ b/src/Filee.Engines/Models3D/FbxFormat.cs@@ -0,0 +1,557 @@+// Autodesk FBX, read only: binary (6.x and 7.x) and ASCII files through Filee's own parser (FbxParser), no FBX SDK.+// Read: mesh geometry with polygons triangulated, the first normal, UV, colour and material layer (by polygon+// vertex, by control point, by polygon or all the same; direct or indexed); the model hierarchy from the+// connections, each model's translation, rotation (any Euler order, pre- and post-rotation, pivots and offsets) and+// scaling, and the geometric transform of its mesh; material diffuse colour and opacity; the diffuse texture,+// embedded (Video Content) or a file next to the model. GlobalSettings' axes and UnitScaleFactor (centimetres per+// unit) turn the scene Y up and into millimetres. Animation, skins, blend shapes, NURBS, cameras and lights are+// skipped: the model is read in its rest pose.++using System.Globalization;+using System.Numerics;+using System.Runtime.InteropServices;++namespace Filee.Engines.Models3D;++internal static class FbxFormat+{+ private const float MillimetresPerCentimetre = 10;++ public static Model3D Read(string path, IProgress<double>? progress, CancellationToken cancellationToken)+ {+ var model = Read(File.ReadAllBytes(path), Path.GetDirectoryName(Path.GetFullPath(path))!, cancellationToken);+ progress?.Report(1);+ return model;+ }++ /// <summary>Reads the FBX file <paramref name="data"/>; texture files are looked for in <paramref name="directory"/>.</summary>+ internal static Model3D Read(byte[] data, string directory, CancellationToken cancellationToken)+ {+ FbxNode document;+ try+ {+ document = FbxParser.Parse(data, cancellationToken);+ }+ catch (Exception ex) when (ex is ArgumentException or IndexOutOfRangeException or OverflowException or FormatException)+ {+ throw new InvalidDataException(FbxParser.Damaged, ex);+ }+ try+ {+ return new Scene(document, directory).Build(cancellationToken);+ }+ catch (Exception ex) when (ex is not (OperationCanceledException or OutOfMemoryException or InvalidDataException or IOException or UnauthorizedAccessException))+ {+ throw new InvalidDataException($"The FBX model could not be read: {ex.Message}", ex);+ }+ }++ /// <summary>The objects of the file, their connections and the global settings.</summary>+ private sealed class Scene+ {+ private readonly string _directory;+ private readonly FbxNode? _settings;+ private readonly List<(string Key, FbxNode Node)> _ordered = [];+ private readonly Dictionary<string, FbxNode> _objects = new(StringComparer.Ordinal);+ private readonly Dictionary<string, FbxNode> _templates = new(StringComparer.Ordinal);+ private readonly Dictionary<string, string> _parents = new(StringComparer.Ordinal);+ private readonly Dictionary<string, List<FbxNode>> _geometries = new(StringComparer.Ordinal);+ private readonly Dictionary<string, List<string>> _materials = new(StringComparer.Ordinal);+ private readonly Dictionary<string, (string Texture, bool Exact)> _textures = new(StringComparer.Ordinal);+ private readonly Dictionary<string, string> _videos = new(StringComparer.Ordinal);+ private readonly Dictionary<string, Matrix4x4> _world = new(StringComparer.Ordinal);+ private readonly Dictionary<string, int> _materialIndex = new(StringComparer.Ordinal);+ private readonly Dictionary<string, Texture3D?> _loaded = new(StringComparer.Ordinal);++ public Scene(FbxNode document, string directory)+ {+ _directory = directory;+ _settings = document.Child("GlobalSettings");+ foreach (var node in document.Child("Objects")?.Children ?? [])+ {+ if (node.Properties.Count > 0 && KeyOf(node.Properties[0]) is { } key && _objects.TryAdd(key, node))+ _ordered.Add((key, node));+ }+ // Property templates: what an object of the type has where it does not say (the FBX SDK writes only+ // what differs from them).+ foreach (var type in document.Child("Definitions")?.ChildrenNamed("ObjectType") ?? [])+ {+ if (type.Text(0) is { } name && type.Child("PropertyTemplate") is { } template)+ _templates.TryAdd(name, template);+ }+ foreach (var link in document.Child("Connections")?.Children ?? [])+ {+ if (link.Name is not ("C" or "Connect") || link.Properties.Count < 3+ || KeyOf(link.Properties[1]) is not { } childKey || KeyOf(link.Properties[2]) is not { } parentKey+ || !_objects.TryGetValue(childKey, out var child) || !_objects.TryGetValue(parentKey, out var parent))+ continue;+ var property = link.Text(3);+ switch (child.Name, parent.Name)+ {+ case ("Geometry", "Model"):+ Add(_geometries, parentKey, child);+ break;+ case ("Model", "Model"):+ _parents.TryAdd(childKey, parentKey);+ break;+ case ("Material", "Model"):+ Add(_materials, parentKey, childKey);+ break;+ case ("Texture", "Material") when IsDiffuse(property):+ // "DiffuseColor" wins over the other colour channels a material may have a texture on.+ var exact = property is null or "DiffuseColor";+ if (!_textures.TryGetValue(parentKey, out var existing) || (exact && !existing.Exact))+ _textures[parentKey] = (childKey, exact);+ break;+ case ("Video", "Texture"):+ _videos.TryAdd(parentKey, childKey);+ break;+ }+ }+ }++ private static void Add<T>(Dictionary<string, List<T>> lists, string key, T value)+ {+ if (!lists.TryGetValue(key, out var list))+ lists[key] = list = [];+ list.Add(value);+ }++ private static bool IsDiffuse(string? property) =>+ property is null+ || property.Contains("Diffuse", StringComparison.OrdinalIgnoreCase)+ || property.Contains("BaseColor", StringComparison.OrdinalIgnoreCase)+ || property.Contains("base_color", StringComparison.OrdinalIgnoreCase);++ /// <summary>An object's id (FBX 7) or its full name (FBX 6, "Model::Cube").</summary>+ private static string? KeyOf(object value) => value switch+ {+ long id => id.ToString(CultureInfo.InvariantCulture),+ string name => name,+ _ => null,+ };++ public Model3D Build(CancellationToken cancellationToken)+ {+ var model = new Model3D();+ var scene = AxisConversion() * Matrix4x4.CreateScale(UnitScale() * MillimetresPerCentimetre);+ foreach (var (key, node) in _ordered)+ {+ if (node.Name != "Model")+ continue;+ // FBX 6 keeps the mesh in the model itself.+ var geometries = _geometries.GetValueOrDefault(key)+ ?? (node.Child("PolygonVertexIndex") is not null ? new List<FbxNode> { node } : null);+ if (geometries is null)+ continue;+ var transform = Geometric(node) * World(key, 0) * scene;+ var slots = _materials.GetValueOrDefault(key)?.Select(m => MaterialIndex(model, m)).ToList() ?? [];+ foreach (var geometry in geometries)+ AddMesh(model, geometry, NameOf(node), transform, slots, cancellationToken);+ }+ return model;+ }++ // ───────────────────────── Transforms ─────────────────────────++ /// <summary>The file's axes to Y up (right X, up Y, front Z), right-handed as FBX always is.</summary>+ private Matrix4x4 AxisConversion()+ {+ var up = (int)(Number(_settings, "UpAxis") ?? 1);+ var coord = (int)(Number(_settings, "CoordAxis") ?? 0);+ if (up is < 0 or > 2)+ up = 1;+ if (coord is < 0 or > 2 || coord == up)+ coord = up == 0 ? 1 : 0;+ var front = 3 - up - coord;+ var matrix = Matrix4x4.Identity;+ matrix[0, 0] = matrix[1, 1] = matrix[2, 2] = 0;+ matrix[coord, 0] = Number(_settings, "CoordAxisSign") < 0 ? -1 : 1;+ matrix[up, 1] = Number(_settings, "UpAxisSign") < 0 ? -1 : 1;+ matrix[front, 2] = 1;+ // The front axis follows from the other two: its sign in the file is not always consistent.+ if (matrix.GetDeterminant() < 0)+ matrix[front, 2] = -1;+ return matrix;+ }++ /// <summary>Centimetres per file unit (1 when missing or nonsense).</summary>+ private float UnitScale()+ {+ var scale = Number(_settings, "UnitScaleFactor") ?? 1;+ return scale > 0 && double.IsFinite(scale) ? (float)scale : 1;+ }++ private Matrix4x4 World(string key, int depth)+ {+ if (_world.TryGetValue(key, out var world))+ return world;+ world = Local(_objects[key]);+ // A cycle in the connections stops at a depth no real hierarchy has.+ if (depth < 512 && _parents.TryGetValue(key, out var parent))+ world *= World(parent, depth + 1);+ _world[key] = world;+ return world;+ }++ /// <summary>+ /// The FBX SDK's local transform, T · Roff · Rp · Rpre · R · Rpost⁻¹ · Rp⁻¹ · Soff · Sp · S · Sp⁻¹ for column+ /// vectors, written in reverse for System.Numerics' row vectors.+ /// </summary>+ private Matrix4x4 Local(FbxNode node)+ {+ var translation = Vector(node, "Lcl Translation") ?? Vector3.Zero;+ var rotation = Vector(node, "Lcl Rotation") ?? Vector3.Zero;+ var scaling = Vector(node, "Lcl Scaling") ?? Vector3.One;+ var preRotation = Vector(node, "PreRotation") ?? Vector3.Zero;+ var postRotation = Vector(node, "PostRotation") ?? Vector3.Zero;+ var rotationOffset = Vector(node, "RotationOffset") ?? Vector3.Zero;+ var rotationPivot = Vector(node, "RotationPivot") ?? Vector3.Zero;+ var scalingOffset = Vector(node, "ScalingOffset") ?? Vector3.Zero;+ var scalingPivot = Vector(node, "ScalingPivot") ?? Vector3.Zero;+ var order = (int)(Number(node, "RotationOrder") ?? 0);+ Matrix4x4.Invert(Euler(postRotation, 0), out var inversePost);+ return Matrix4x4.CreateTranslation(-scalingPivot)+ * Matrix4x4.CreateScale(scaling)+ * Matrix4x4.CreateTranslation(scalingPivot + scalingOffset - rotationPivot)+ * inversePost+ * Euler(rotation, order)+ * Euler(preRotation, 0)+ * Matrix4x4.CreateTranslation(rotationPivot + rotationOffset + translation);+ }++ /// <summary>The mesh's own offset from its model, which children do not inherit.</summary>+ private Matrix4x4 Geometric(FbxNode node) =>+ Matrix4x4.CreateScale(Vector(node, "GeometricScaling") ?? Vector3.One)+ * Euler(Vector(node, "GeometricRotation") ?? Vector3.Zero, 0)+ * Matrix4x4.CreateTranslation(Vector(node, "GeometricTranslation") ?? Vector3.Zero);++ /// <summary>Euler angles in degrees; <paramref name="order"/> is FBX's EFbxRotationOrder (0 XYZ: X first).</summary>+ private static Matrix4x4 Euler(Vector3 degrees, int order)+ {+ if (degrees == Vector3.Zero)+ return Matrix4x4.Identity;+ var x = Matrix4x4.CreateRotationX(degrees.X * MathF.PI / 180);+ var y = Matrix4x4.CreateRotationY(degrees.Y * MathF.PI / 180);+ var z = Matrix4x4.CreateRotationZ(degrees.Z * MathF.PI / 180);+ return order switch+ {+ 1 => x * z * y, // XZY+ 2 => y * z * x, // YZX+ 3 => y * x * z, // YXZ+ 4 => z * x * y, // ZXY+ 5 => z * y * x, // ZYX+ _ => x * y * z, // XYZ (and spheric XYZ)+ };+ }++ // ───────────────────────── Properties ─────────────────────────++ /// <summary>The property <paramref name="name"/> of an object (Properties70 or FBX 6's Properties60), else of its type's template.</summary>+ private FbxNode? Property(FbxNode? node, string name)+ {+ if (node is null)+ return null;+ return Find(node) ?? (_templates.TryGetValue(node.Name, out var template) ? Find(template) : null);++ FbxNode? Find(FbxNode owner)+ {+ foreach (var list in owner.Children)+ {+ if (list.Name is not ("Properties70" or "Properties60"))+ continue;+ foreach (var property in list.Children)+ {+ if (property.Name is "P" or "Property" && property.Text(0) == name)+ return property;+ }+ }+ return null;+ }+ }++ /// <summary>The numbers of a property (after its name, type and flags).</summary>+ private List<double> Numbers(FbxNode? node, string name)+ {+ var values = new List<double>();+ if (Property(node, name) is { } property)+ {+ foreach (var value in property.Properties.Skip(1))+ {+ if (AsNumber(value) is { } number)+ values.Add(number);+ }+ }+ return values;+ }++ private double? Number(FbxNode? node, string name) => Numbers(node, name) is [var value, ..] ? value : null;++ private Vector3? Vector(FbxNode? node, string name)+ {+ var values = Numbers(node, name);+ if (values.Count < 3)+ return null;+ var vector = new Vector3((float)values[0], (float)values[1], (float)values[2]);+ return float.IsFinite(vector.X) && float.IsFinite(vector.Y) && float.IsFinite(vector.Z) ? vector : null;+ }++ private static double? AsNumber(object value) => value switch+ {+ long l => l,+ double d => d,+ bool b => b ? 1 : 0,+ _ => null,+ };++ /// <summary>"Cube" of "Model::Cube" (ASCII) or "Cube\0\u0001Model" (binary).</summary>+ private static string NameOf(FbxNode node)+ {+ var name = node.Properties.OfType<string>().FirstOrDefault() ?? "";+ var binary = name.IndexOf("\0\u0001", StringComparison.Ordinal);+ if (binary >= 0)+ return name[..binary];+ var ascii = name.IndexOf("::", StringComparison.Ordinal);+ return ascii >= 0 ? name[(ascii + 2)..] : name;+ }++ // ───────────────────────── Materials ─────────────────────────++ private int MaterialIndex(Model3D model, string key)+ {+ if (_materialIndex.TryGetValue(key, out var index))+ return index;+ var node = _objects[key];+ var color = Vector(node, "DiffuseColor") ?? Vector(node, "Diffuse") ?? new Vector3(0.8f);+ var opacity = Math.Clamp((float)(Number(node, "Opacity") ?? 1), 0, 1);+ var material = new Material3D+ {+ Name = NameOf(node),+ BaseColor = new Vector4(Vector3.Clamp(color, Vector3.Zero, Vector3.One), opacity),+ BaseColorTexture = _textures.TryGetValue(key, out var texture) ? Texture(texture.Texture) : null,+ };+ index = model.Materials.Count;+ model.Materials.Add(material);+ _materialIndex[key] = index;+ return index;+ }++ /// <summary>The picture of a texture: embedded in its video, else the file it names next to the model.</summary>+ private Texture3D? Texture(string key)+ {+ if (_loaded.TryGetValue(key, out var loaded))+ return loaded;+ var texture = _objects[key];+ var video = _videos.TryGetValue(key, out var videoKey) ? _objects[videoKey] : null;+ string[] references =+ [+ .. new[] { texture, video }.OfType<FbxNode>()+ .SelectMany(n => n.Children.Where(c => c.Name is "RelativeFilename" or "FileName" or "Filename"))+ .Select(n => n.Text(0)?.Replace('\\', '/')).OfType<string>().Where(s => s.Length > 0).Distinct(),+ ];+ var name = references.Select(Path.GetFileNameWithoutExtension).FirstOrDefault(n => !string.IsNullOrEmpty(n)) ?? NameOf(texture);+ var extension = references.Select(Path.GetExtension).FirstOrDefault(e => !string.IsNullOrEmpty(e)) ?? "";++ Texture3D? result = null;+ if (video?.Child("Content") is { } content && Embedded(content) is { Length: > 0 } data)+ result = new Texture3D(data, Texture3D.Sniff(data, extension), name);+ else+ {+ foreach (var reference in references)+ {+ if (ObjFormat.Resolve(_directory, reference) is { } file)+ {+ var bytes = File.ReadAllBytes(file);+ result = new Texture3D(bytes, Texture3D.Sniff(bytes, Path.GetExtension(file)), name);+ break;+ }+ }+ }+ _loaded[key] = result;+ return result;+ }++ /// <summary>Video Content: raw bytes (binary) or base64 strings (ASCII).</summary>+ private static byte[]? Embedded(FbxNode content)+ {+ if (content.Properties is [byte[] bytes])+ return bytes;+ var base64 = string.Concat(content.Properties.OfType<string>());+ if (base64.Length == 0)+ return null;+ try+ {+ return Convert.FromBase64String(base64);+ }+ catch (FormatException)+ {+ return null;+ }+ }++ // ───────────────────────── Meshes ─────────────────────────++ private static void AddMesh(Model3D model, FbxNode geometry, string name, Matrix4x4 transform, List<int> slots, CancellationToken cancellationToken)+ {+ var positions = Doubles(geometry.Child("Vertices"));+ var polygons = Ints(geometry.Child("PolygonVertexIndex"));+ if (positions is null || polygons is null)+ return;+ var controlPoints = positions.Length / 3;+ var normals = Layer.Of(geometry, "LayerElementNormal", "Normals", "NormalsIndex", 3);+ var uvs = Layer.Of(geometry, "LayerElementUV", "UV", "UVIndex", 2);+ var colors = Layer.Of(geometry, "LayerElementColor", "Colors", "ColorIndex", 4);+ // The material layer's values are the indices themselves (into the model's materials).+ var materials = Layer.Of(geometry, "LayerElementMaterial", "Materials", null, 1);++ var parts = new Dictionary<int, PartBuilder>();+ var corners = new List<int>();+ for (int i = 0, start = 0, polygon = 0; i < polygons.Length; i++)+ {+ if ((i & 0xFFFF) == 0)+ cancellationToken.ThrowIfCancellationRequested();+ // A negative index ends a polygon (it is the last corner's index, bit-inverted); so does the end.+ if (polygons[i] >= 0 && i + 1 < polygons.Length)+ continue;++ var slot = materials is null ? 0 : (int)(materials.Get1(i, 0, polygon) ?? -1);+ var material = (uint)slot < (uint)slots.Count ? slots[slot] : -1;+ if (!parts.TryGetValue(material, out var builder))+ {+ parts[material] = builder = new PartBuilder(new MeshPart+ {+ Name = name,+ Material = material,+ Normals = normals is null ? null : [],+ TexCoords = uvs is null ? null : [],+ Colors = colors is null ? null : [],+ });+ }++ corners.Clear();+ for (var k = start; k <= i; k++)+ {+ var controlPoint = polygons[k] < 0 ? ~polygons[k] : polygons[k];+ if (controlPoint >= controlPoints)+ throw new InvalidDataException($"A polygon of the FBX model refers to vertex {controlPoint + 1}, but the mesh has only {controlPoints} vertices.");+ corners.Add(builder.Vertex(positions, controlPoint,+ normals?.Get3(k, controlPoint, polygon), uvs?.Get2(k, controlPoint, polygon), colors?.Get4(k, controlPoint, polygon)));+ }+ Triangulator.AddPolygon(builder.Part, CollectionsMarshal.AsSpan(corners));+ start = i + 1;+ polygon++;+ }++ foreach (var builder in parts.Values)+ {+ var part = builder.Part;+ if (builder.MissingNormal)+ part.ComputeNormals();+ part.Transform(transform);+ model.Parts.Add(part);+ }+ }++ /// <summary>An array property as doubles, or the numbers of an FBX 6 ASCII node written inline.</summary>+ private static double[]? Doubles(FbxNode? node) => node?.Properties switch+ {+ null => null,+ [double[] d] => d,+ [float[] f] => [.. f.Select(v => (double)v)],+ [int[] i] => [.. i.Select(v => (double)v)],+ [long[] l] => [.. l.Select(v => (double)v)],+ var values => [.. values.Select(AsNumber).OfType<double>()],+ };++ private static int[]? Ints(FbxNode? node) => node?.Properties switch+ {+ null => null,+ [int[] i] => i,+ [long[] l] => [.. l.Select(v => (int)Math.Clamp(v, int.MinValue, int.MaxValue))],+ _ => Doubles(node) is { } d ? [.. d.Select(v => (int)Math.Clamp(v, int.MinValue, int.MaxValue))] : null,+ };++ /// <summary>One layer element: which value each polygon corner takes.</summary>+ private sealed class Layer(double[] values, int[]? index, Layer.Mapping mapping, int width)+ {+ public enum Mapping { ByPolygonVertex, ByControlPoint, ByPolygon, AllSame }++ /// <summary>The first usable element <paramref name="element"/> of the geometry (layer 0), or null.</summary>+ public static Layer? Of(FbxNode geometry, string element, string data, string? indexName, int width)+ {+ foreach (var node in geometry.ChildrenNamed(element))+ {+ if (Doubles(node.Child(data)) is not { Length: > 0 } values)+ continue;+ Mapping? mapping = node.Child("MappingInformationType")?.Text(0) switch+ {+ "ByPolygonVertex" => Mapping.ByPolygonVertex,+ "ByVertice" or "ByVertex" or "ByControlPoint" => Mapping.ByControlPoint,+ "ByPolygon" => Mapping.ByPolygon,+ "AllSame" => Mapping.AllSame,+ _ => null, // by edge: no corner value+ };+ if (mapping is null)+ continue;+ var indexed = node.Child("ReferenceInformationType")?.Text(0) is "IndexToDirect" or "Index";+ var index = indexed && indexName is not null ? Ints(node.Child(indexName)) : null;+ if (indexed && indexName is not null && index is null)+ continue;+ return new Layer(values, index, mapping.Value, width);+ }+ return null;+ }++ public Vector3? Get3(int corner, int controlPoint, int polygon) =>+ Offset(corner, controlPoint, polygon) is var i and >= 0 ? new((float)values[i], (float)values[i + 1], (float)values[i + 2]) : null;++ public Vector2? Get2(int corner, int controlPoint, int polygon) =>+ Offset(corner, controlPoint, polygon) is var i and >= 0 ? new((float)values[i], (float)values[i + 1]) : null;++ public Vector4? Get4(int corner, int controlPoint, int polygon) =>+ Offset(corner, controlPoint, polygon) is var i and >= 0 ? new((float)values[i], (float)values[i + 1], (float)values[i + 2], (float)values[i + 3]) : null;++ public double? Get1(int corner, int controlPoint, int polygon) =>+ Offset(corner, controlPoint, polygon) is var i and >= 0 ? values[i] : null;++ /// <summary>Where the value of a corner starts in the values, or -1 when the file has none for it.</summary>+ private int Offset(int corner, int controlPoint, int polygon)+ {+ var i = mapping switch+ {+ Mapping.ByPolygonVertex => corner,+ Mapping.ByControlPoint => controlPoint,+ Mapping.ByPolygon => polygon,+ _ => 0,+ };+ if (index is not null)+ i = (uint)i < (uint)index.Length ? index[i] : -1;+ return i >= 0 && (long)(i + 1) * width <= values.Length ? i * width : -1;+ }+ }++ /// <summary>Collects the vertices of one part, one per distinct corner.</summary>+ private sealed class PartBuilder(MeshPart part)+ {+ private readonly Dictionary<(int, Vector3, Vector2, Vector4), int> _vertices = [];++ public MeshPart Part { get; } = part;++ /// <summary>A corner without a normal although the mesh has normals: the part's normals are computed.</summary>+ public bool MissingNormal { get; private set; }++ public int Vertex(double[] positions, int controlPoint, Vector3? normal, Vector2? uv, Vector4? color)+ {+ if (Part.Normals is not null && (normal is null || normal == Vector3.Zero))+ MissingNormal = true;+ var key = (controlPoint, normal ?? default, uv ?? default, color ?? default);+ if (_vertices.TryGetValue(key, out var existing))+ return existing;+ var position = new Vector3((float)positions[controlPoint * 3], (float)positions[controlPoint * 3 + 1], (float)positions[controlPoint * 3 + 2]);+ var vertex = Part.AddVertex(position, normal, uv, color);+ _vertices[key] = vertex;+ return vertex;+ }+ }+ }+}diff --git a/src/Filee.Engines/Models3D/FbxParser.cs b/src/Filee.Engines/Models3D/FbxParser.csnew file mode 100644index 00000000..b15848ea--- /dev/null+++ b/src/Filee.Engines/Models3D/FbxParser.cs@@ -0,0 +1,402 @@+// The node tree of an Autodesk FBX file, binary or ASCII, for FbxFormat. Binary: the "Kaydara FBX Binary" header,+// node records with 32-bit offsets (64-bit from version 7.5), scalar, string, raw and array properties, arrays plain+// or zlib-compressed. ASCII: "Name: value, value { children }" with ";" comments and "*count { a: ... }" arrays.+// Animation curves, poses, deformers and the other parts the reader never looks at are skipped without decoding.++using System.Buffers.Binary;+using System.Globalization;+using System.IO.Compression;+using System.Runtime.InteropServices;+using System.Text;++namespace Filee.Engines.Models3D;++/// <summary>One FBX node: a name, its properties (long, double, string, bool, byte[] or an array) and its children.</summary>+internal sealed class FbxNode(string name)+{+ public string Name { get; } = name;+ public List<object> Properties { get; } = [];+ public List<FbxNode> Children { get; } = [];++ /// <summary>The first child called <paramref name="name"/>, or null.</summary>+ public FbxNode? Child(string name) => Children.Find(c => c.Name == name);++ public IEnumerable<FbxNode> ChildrenNamed(string name) => Children.Where(c => c.Name == name);++ /// <summary>Property <paramref name="index"/> as a string, or null.</summary>+ public string? Text(int index) => index < Properties.Count ? Properties[index] as string : null;+}++internal static class FbxParser+{+ internal const string Damaged = "The FBX file is cut short or damaged.";+ private const int MaxDepth = 64;++ private static ReadOnlySpan<byte> BinaryMagic => "Kaydara FBX Binary \0"u8;++ /// <summary>Nodes no reader needs (by name, at the top level and in Objects): animation can be most of a file.</summary>+ private static readonly HashSet<string> Skipped = new(StringComparer.Ordinal)+ {+ "Takes", "References", "Documents", "Version5",+ "AnimationStack", "AnimationLayer", "AnimationCurveNode", "AnimationCurve", "Pose", "Deformer",+ "NodeAttribute", "CollectionExclusive", "Constraint", "Implementation", "BindingTable",+ };++ /// <summary>Stands for a skipped node while reading.</summary>+ private static readonly FbxNode Skip = new("");++ /// <summary>Reads a whole file; the returned node (no name) has the top-level nodes as children.</summary>+ public static FbxNode Parse(byte[] data, CancellationToken cancellationToken)+ {+ if (data.AsSpan().StartsWith(BinaryMagic))+ return ParseBinary(data, cancellationToken);+ if (LooksLikeAscii(data))+ return new AsciiReader(Encoding.UTF8.GetString(data), cancellationToken).Document();+ throw new InvalidDataException("The file is not an FBX model.");+ }++ private static bool LooksLikeAscii(byte[] data)+ {+ var head = Encoding.UTF8.GetString(data, 0, Math.Min(data.Length, 4096)).TrimStart('', ' ', '\t', '\r', '\n');+ return head.Contains('\0') is false+ && (head.StartsWith("; FBX", StringComparison.Ordinal) || head.Contains("FBXHeaderExtension:", StringComparison.Ordinal));+ }++ // ───────────────────────── Binary ─────────────────────────++ private static FbxNode ParseBinary(byte[] data, CancellationToken cancellationToken)+ {+ if (data.Length < 27)+ throw new InvalidDataException(Damaged);+ var version = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(23));+ var reader = new BinaryRecords(data, Wide: version >= 7500, cancellationToken);+ var root = new FbxNode("");+ long position = 27;+ while (reader.Node(ref position, data.Length, 0) is { } node)+ {+ if (!ReferenceEquals(node, Skip))+ root.Children.Add(node);+ }+ if (root.Children.Count == 0)+ throw new InvalidDataException(Damaged);+ return root;+ }++ private readonly record struct BinaryRecords(byte[] Data, bool Wide, CancellationToken CancellationToken)+ {+ private int HeaderSize => Wide ? 25 : 13;++ /// <summary>The node at <paramref name="position"/>, <see cref="Skip"/>, or null at the end of a list.</summary>+ public FbxNode? Node(ref long position, long limit, int depth)+ {+ if (depth <= 2)+ CancellationToken.ThrowIfCancellationRequested();+ if (position + HeaderSize > limit)+ {+ // The top-level list may end without its null record; a nested one may not.+ if (depth == 0)+ return null;+ throw new InvalidDataException(Damaged);+ }+ var header = Data.AsSpan((int)position, HeaderSize);+ long end, count, listLength;+ if (Wide)+ {+ end = (long)BinaryPrimitives.ReadUInt64LittleEndian(header);+ count = (long)BinaryPrimitives.ReadUInt64LittleEndian(header[8..]);+ listLength = (long)BinaryPrimitives.ReadUInt64LittleEndian(header[16..]);+ }+ else+ {+ end = BinaryPrimitives.ReadUInt32LittleEndian(header);+ count = BinaryPrimitives.ReadUInt32LittleEndian(header[4..]);+ listLength = BinaryPrimitives.ReadUInt32LittleEndian(header[8..]);+ }+ int nameLength = header[^1];+ position += HeaderSize;+ if (end == 0)+ return null; // the null record that ends a list+ var propertiesStart = position + nameLength;+ if (depth > MaxDepth || end > limit || propertiesStart > end || listLength < 0 || listLength > end - propertiesStart+ || count < 0 || count > listLength)+ throw new InvalidDataException(Damaged);++ var name = Encoding.UTF8.GetString(Data, (int)position, nameLength);+ if (depth <= 1 && Skipped.Contains(name))+ {+ position = end;+ return Skip;+ }+ var node = new FbxNode(name);+ position = propertiesStart;+ var propertiesEnd = propertiesStart + listLength;+ for (var i = 0; i < count; i++)+ node.Properties.Add(Property(ref position, propertiesEnd));+ position = propertiesEnd;+ while (position < end && Node(ref position, end, depth + 1) is { } child)+ {+ if (!ReferenceEquals(child, Skip))+ node.Children.Add(child);+ }+ position = end;+ return node;+ }++ private object Property(ref long position, long end)+ {+ Need(position, 1, end);+ var type = (char)Data[position++];+ switch (type)+ {+ case 'C':+ Need(position, 1, end);+ return Data[position++] != 0;+ case 'Y':+ Need(position, 2, end);+ position += 2;+ return (long)BinaryPrimitives.ReadInt16LittleEndian(Data.AsSpan((int)position - 2));+ case 'I':+ Need(position, 4, end);+ position += 4;+ return (long)BinaryPrimitives.ReadInt32LittleEndian(Data.AsSpan((int)position - 4));+ case 'L':+ Need(position, 8, end);+ position += 8;+ return BinaryPrimitives.ReadInt64LittleEndian(Data.AsSpan((int)position - 8));+ case 'F':+ Need(position, 4, end);+ position += 4;+ return (double)BinaryPrimitives.ReadSingleLittleEndian(Data.AsSpan((int)position - 4));+ case 'D':+ Need(position, 8, end);+ position += 8;+ return BinaryPrimitives.ReadDoubleLittleEndian(Data.AsSpan((int)position - 8));+ case 'S' or 'R':+ {+ Need(position, 4, end);+ long length = BinaryPrimitives.ReadUInt32LittleEndian(Data.AsSpan((int)position));+ position += 4;+ Need(position, length, end);+ var start = (int)position;+ position += length;+ return type == 'S'+ ? Encoding.UTF8.GetString(Data, start, (int)length)+ : Data.AsSpan(start, (int)length).ToArray();+ }+ case 'f' or 'd' or 'l' or 'i' or 'b':+ return Array(type, ref position, end);+ default:+ throw new InvalidDataException(Damaged);+ }+ }++ private object Array(char type, ref long position, long end)+ {+ Need(position, 12, end);+ var header = Data.AsSpan((int)position, 12);+ long length = BinaryPrimitives.ReadUInt32LittleEndian(header);+ var encoding = BinaryPrimitives.ReadUInt32LittleEndian(header[4..]);+ long stored = BinaryPrimitives.ReadUInt32LittleEndian(header[8..]);+ position += 12;+ Need(position, stored, end);+ var size = type switch { 'f' or 'i' => 4, 'd' or 'l' => 8, _ => 1 };+ var bytes = length * size;+ // Deflate packs at most about 1032:1, so a larger length is a lie that would only allocate memory.+ if (bytes > int.MaxValue - 64 || (encoding == 0 ? bytes != stored : bytes > stored * 1032 + 64))+ throw new InvalidDataException(Damaged);+ var raw = Data.AsSpan((int)position, (int)stored);+ byte[]? inflated = null;+ if (encoding == 1)+ {+ inflated = new byte[bytes];+ try+ {+ using var zlib = new ZLibStream(new MemoryStream(Data, (int)position, (int)stored, writable: false), CompressionMode.Decompress);+ zlib.ReadExactly(inflated);+ }+ catch (Exception ex) when (ex is InvalidDataException or EndOfStreamException)+ {+ throw new InvalidDataException(Damaged, ex);+ }+ raw = inflated;+ }+ else if (encoding != 0)+ {+ throw new InvalidDataException(Damaged);+ }+ position += stored;+ return type switch+ {+ 'f' => MemoryMarshal.Cast<byte, float>(raw).ToArray(),+ 'd' => MemoryMarshal.Cast<byte, double>(raw).ToArray(),+ 'i' => MemoryMarshal.Cast<byte, int>(raw).ToArray(),+ 'l' => MemoryMarshal.Cast<byte, long>(raw).ToArray(),+ _ => raw.ToArray().Select(b => b != 0).ToArray(),+ };+ }++ private static void Need(long position, long length, long end)+ {+ if (length < 0 || position + length > end)+ throw new InvalidDataException(Damaged);+ }+ }++ // ───────────────────────── ASCII ─────────────────────────++ private sealed class AsciiReader(string text, CancellationToken cancellationToken)+ {+ private int _position;+ private int _nodes;++ public FbxNode Document()+ {+ var root = new FbxNode("");+ while (true)+ {+ SkipSpace(newLines: true);+ if (_position >= text.Length)+ break;+ var node = Node(0);+ if (!Skipped.Contains(node.Name))+ root.Children.Add(node);+ }+ if (root.Children.Count == 0)+ throw new InvalidDataException("The file is not an FBX model.");+ return root;+ }++ private FbxNode Node(int depth)+ {+ if ((++_nodes & 0x3FF) == 0)+ cancellationToken.ThrowIfCancellationRequested();+ if (depth > MaxDepth)+ throw Invalid();+ var start = _position;+ while (_position < text.Length && text[_position] is not (':' or '{' or '}' or ',' or '"') && !char.IsWhiteSpace(text[_position]))+ _position++;+ if (_position == start || _position >= text.Length || text[_position] != ':')+ throw Invalid();+ var node = new FbxNode(text[start.._position]);+ _position++;+ // The values of an array ("a: 1,2,3,...") go straight into one list instead of a boxed property each.+ var numbers = node.Name == "a" ? new List<double>() : null;++ SkipSpace(newLines: false);+ while (_position < text.Length)+ {+ var c = text[_position];+ if (c == '{')+ {+ _position++;+ Children(node, depth);+ break;+ }+ if (c is '\r' or '\n' or ';' or '}')+ break;+ if (c == ',')+ {+ _position++;+ SkipSpace(newLines: true);+ continue;+ }+ Value(node, numbers);+ SkipSpace(newLines: false);+ }+ if (numbers is not null)+ node.Properties.Add(numbers.ToArray());+ return node;+ }++ private void Children(FbxNode node, int depth)+ {+ while (true)+ {+ SkipSpace(newLines: true);+ if (_position >= text.Length)+ throw new InvalidDataException(Damaged);+ if (text[_position] == '}')+ {+ _position++;+ break;+ }+ var child = Node(depth + 1);+ if (depth == 0 && Skipped.Contains(child.Name))+ continue;+ node.Children.Add(child);+ }+ // "Vertices: *24 { a: ... }": the array becomes the node's only property.+ if (node.Children is [{ Name: "a" } array])+ {+ node.Properties.Clear();+ node.Properties.AddRange(array.Properties);+ node.Children.Clear();+ }+ }++ private void Value(FbxNode node, List<double>? numbers)+ {+ var c = text[_position];+ if (c == '"')+ {+ var end = text.IndexOf('"', _position + 1);+ if (end < 0)+ throw new InvalidDataException(Damaged);+ node.Properties.Add(text[(_position + 1)..end].Replace(""", "\"", StringComparison.Ordinal));+ _position = end + 1;+ return;+ }+ var start = _position;+ while (_position < text.Length && text[_position] is not (',' or '{' or '}' or ';') && !char.IsWhiteSpace(text[_position]))+ _position++;+ if (_position == start)+ {+ _position++; // a stray character (another kind of space)+ return;+ }+ var token = text.AsSpan(start, _position - start);+ if (token[0] == '*')+ return; // the element count of an array that follows in braces+ if (numbers is not null)+ {+ if (!double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out var value))+ throw Invalid();+ numbers.Add(value);+ }+ else if (token.IndexOfAny('.', 'e', 'E') < 0 && long.TryParse(token, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var integer))+ node.Properties.Add(integer);+ else if (double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out var real))+ node.Properties.Add(real);+ else+ node.Properties.Add(token.ToString()); // T, Y, W, ...+ }++ private void SkipSpace(bool newLines)+ {+ while (_position < text.Length)+ {+ var c = text[_position];+ if (c == ';' && newLines)+ {+ var end = text.IndexOf('\n', _position);+ _position = end < 0 ? text.Length : end + 1;+ }+ else if (c is ' ' or '\t' or '' || (newLines && c is '\r' or '\n'))+ _position++;+ else+ break;+ }+ }++ private InvalidDataException Invalid()+ {+ var line = 1;+ for (var i = 0; i < _position && i < text.Length; i++)+ {+ if (text[i] == '\n')+ line++;+ }+ return new InvalidDataException($"Line {line} of the FBX file is not valid.");+ }+ }+}diff --git a/src/Filee.Engines/Models3D/ModelConverter.cs b/src/Filee.Engines/Models3D/ModelConverter.csindex 7e6ab5cb..03068c32 100644--- a/src/Filee.Engines/Models3D/ModelConverter.cs+++ b/src/Filee.Engines/Models3D/ModelConverter.cs@@ -1,5 +1,6 @@// 3D models in managed code only (SharpGLTF for glTF, Filee's own readers and writers for the rest): GLB, glTF, STL,-// OBJ, 3MF and PLY into each other through one in-memory model (Model3D), and an isometric preview picture.+// OBJ, 3MF and PLY into each other through one in-memory model (Model3D), FBX (read only) into any of them, and an+// isometric preview picture.// See docs/ENGINES.md, "3D models", for units, axes and what each format keeps.using Filee.Core.Conversion;@@ -12,12 +13,15 @@ using Microsoft.Extensions.Logging.Abstractions;namespace Filee.Engines.Models3D;-/// <summary>Converts 3D models between GLB, glTF, STL, OBJ, 3MF and PLY, and renders them to pictures.</summary>+/// <summary>Converts 3D models between GLB, glTF, STL, OBJ, 3MF and PLY, reads FBX, and renders them to pictures.</summary>public sealed class ModelConverter(ILogger? logger = null) : IConverter, IImageTransformer{/// <summary>The 3D formats, each readable and writable.</summary>public static readonly string[] Formats = ["glb", "gltf", "stl", "obj", "3mf", "ply"];+ /// <summary>Every 3D format that can be read: <see cref="Formats"/> and FBX.</summary>+ public static readonly string[] InputFormats = [.. Formats, "fbx"];+/// <summary>Long edge of the preview picture before the preset's resize.</summary>internal const int PreviewSize = 1024;@@ -34,11 +38,11 @@ public sealed class ModelConverter(ILogger? logger = null) : IConverter, IImageTpublic IReadOnlyList<ConversionEdge> Edges { get; } =[- .. from source in Formats from target in Formats where source != target select new ConversionEdge(source, target),- .. from source in Formats from target in ImageEncoder.Writable select ImageEncoder.Edge(source, target),+ .. from source in InputFormats from target in Formats where source != target select new ConversionEdge(source, target),+ .. from source in InputFormats from target in ImageEncoder.Writable select ImageEncoder.Edge(source, target),];- public EngineStatus GetStatus() => EngineStatus.Available("GLB, glTF, STL, OBJ, 3MF, PLY",+ public EngineStatus GetStatus() => EngineStatus.Available("GLB, glTF, STL, OBJ, 3MF, PLY ↔ each other; FBX → each of them",$"{EngineVersions.BuiltIn} · {EngineVersions.Library("SharpGLTF", typeof(SharpGLTF.Schema2.ModelRoot))}");public Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken) =>@@ -75,6 +79,7 @@ public sealed class ModelConverter(ILogger? logger = null) : IConverter, IImageT"ply" => PlyFormat.Read(path, progress, cancellationToken),"3mf" => ThreeMfFormat.Read(path, progress, cancellationToken),"glb" or "gltf" => GltfFormat.Read(path, progress, cancellationToken),+ "fbx" => FbxFormat.Read(path, progress, cancellationToken),_ => throw new NotSupportedException($"Unknown 3D format '{format}'."),};model.Validate();diff --git a/tests/Filee.Core.Tests/UserDataStoreTests.cs b/tests/Filee.Core.Tests/UserDataStoreTests.csindex 5b3d34fe..8396aa93 100644--- a/tests/Filee.Core.Tests/UserDataStoreTests.cs+++ b/tests/Filee.Core.Tests/UserDataStoreTests.cs@@ -506,7 +506,7 @@ public class UserDataStoreTestsAssert.Equal(ids.IndexOf("data") + 1, ids.IndexOf("models"));Assert.Equal(ids.IndexOf("mixed") - 1, ids.IndexOf("models"));var models = profiles.Single(p => p.Id == "models");- Assert.Equal(["glb", "gltf", "stl", "obj", "3mf", "ply"], models.Extensions);+ Assert.Equal(["glb", "gltf", "stl", "obj", "3mf", "ply", "fbx"], models.Extensions);Assert.Equal(BuiltInData.ModelProfile().PresetIds, models.PresetIds);Assert.False(SettingsMigrations.ApplyToLibrary(14, presets, profiles)); // once only}@@ -520,7 +520,29 @@ public class UserDataStoreTestsAssert.True(SettingsMigrations.ApplyToLibrary(14, presets, profiles));- Assert.Equal(["glb", "gltf", "obj", "ply"], profiles.Single(p => p.Id == "models").Extensions);+ Assert.Equal(["glb", "gltf", "obj", "ply", "fbx"], profiles.Single(p => p.Id == "models").Extensions);+ }++ [Fact]+ public void Version_21_libraries_learn_fbx_on_the_3d_donut_and_nothing_else()+ {+ // As written with schema 21: no FBX, and the user took PLY off the 3D donut.+ var presets = BuiltInData.CreatePresets();+ var profiles = BuiltInData.CreateProfiles();+ var models = profiles.Single(p => p.Id == "models");+ models.Extensions.RemoveAll(e => e is "fbx" or "ply");++ Assert.True(SettingsMigrations.ApplyToLibrary(21, presets, profiles));++ Assert.Equal(["glb", "gltf", "stl", "obj", "3mf", "fbx"], models.Extensions);+ Assert.False(SettingsMigrations.ApplyToLibrary(21, presets, profiles)); // once only++ // A donut of the user that already opens FBX files keeps them.+ profiles = BuiltInData.CreateProfiles();+ profiles.Single(p => p.Id == "models").Extensions.Remove("fbx");+ profiles.Insert(0, new ToolbarProfile { Id = "games", Name = "Games", Extensions = ["fbx"] });+ Assert.False(SettingsMigrations.ApplyToLibrary(21, presets, profiles));+ Assert.DoesNotContain("fbx", profiles.Single(p => p.Id == "models").Extensions);}[Fact]diff --git a/tests/Filee.Engines.Tests/FbxBuilder.cs b/tests/Filee.Engines.Tests/FbxBuilder.csnew file mode 100644index 00000000..fc66dcb8--- /dev/null+++ b/tests/Filee.Engines.Tests/FbxBuilder.cs@@ -0,0 +1,381 @@+// FBX files for the tests, built in code: a node tree (FbxBuilder.Node) and writers for binary FBX 7.4 (32-bit+// record offsets) and 7.5 (64-bit), with arrays plain or zlib-compressed, and for ASCII FBX 7.4. Just the nodes+// Filee's reader looks at: FBXHeaderExtension, GlobalSettings, Definitions, Objects and Connections.++using System.Collections;+using System.Globalization;+using System.IO.Compression;+using System.Numerics;+using System.Runtime.InteropServices;+using System.Text;++namespace Filee.Engines.Tests;++internal static class FbxBuilder+{+ /// <summary>A node: name, properties and children (collection initialiser).</summary>+ public sealed class Node(string name, params object[] properties) : IEnumerable<Node>+ {+ public string Name { get; } = name;+ public object[] Properties { get; } = properties;+ public List<Node> Children { get; } = [];++ public void Add(Node child) => Children.Add(child);++ public void Add(IEnumerable<Node> children) => Children.AddRange(children);++ public IEnumerator<Node> GetEnumerator() => Children.GetEnumerator();++ IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();+ }++ // ───────────────────────── Scenes ─────────────────────────++ /// <summary>The ids of the test scenes' objects.</summary>+ public const long GeometryId = 100, ParentId = 200, CubeId = 300, MaterialId = 400, TextureId = 500, VideoId = 600;++ /// <summary>+ /// A cube from −1 to 1 (quads, normals per corner, UVs by index) in model "Cube" (scaled 1, 2, 3, turned 90° about+ /// Z, moved 5 up) under model "Parent" (moved 10 along X), with the red material "Red" whose opacity 0.5 comes+ /// from the material template. In centimetres and Y up the cube spans (80, 40, −30)–(120, 60, 30) mm.+ /// </summary>+ public static List<Node> CubeScene(int version = 7400, int upAxis = 1, double unitScale = 1, byte[]? texture = null)+ {+ var (positions, polygons) = Cube();+ var objects = new Node("Objects")+ {+ Mesh(GeometryId, "Cube", positions, polygons,+ Normals(positions, polygons),+ new Node("LayerElementUV", 0)+ {+ new Node("Version", 101),+ new Node("Name", "UVMap"),+ new Node("MappingInformationType", "ByPolygonVertex"),+ new Node("ReferenceInformationType", "IndexToDirect"),+ new Node("UV", new double[] { 0, 0, 1, 0, 1, 1, 0, 1 }),+ new Node("UVIndex", Enumerable.Range(0, polygons.Length).Select(i => i % 4).ToArray()),+ },+ MaterialLayer("AllSame", 0)),+ Model(ParentId, "Parent", "Null", ("Lcl Translation", new Vector3(10, 0, 0))),+ Model(CubeId, "Cube", "Mesh",+ ("Lcl Translation", new Vector3(0, 5, 0)),+ ("Lcl Rotation", new Vector3(0, 0, 90)),+ ("Lcl Scaling", new Vector3(1, 2, 3))),+ Material(MaterialId, "Red", new Vector3(1, 0, 0)),+ };+ var connections = new Node("Connections")+ {+ Link(ParentId, 0),+ Link(CubeId, ParentId),+ Link(GeometryId, CubeId),+ Link(MaterialId, CubeId),+ };+ if (texture is not null)+ {+ objects.Add(new Node("Texture", TextureId, "Texture::Checker", "")+ {+ new Node("Type", "TextureVideoClip"),+ new Node("FileName", @"C:\Somewhere\else\checker.png"),+ new Node("RelativeFilename", "checker.png"),+ });+ objects.Add(new Node("Video", VideoId, "Video::Checker", "Clip")+ {+ new Node("Type", "Clip"),+ new Node("RelativeFilename", "checker.png"),+ new Node("Content", texture),+ });+ connections.Add(new Node("C", "OP", TextureId, MaterialId, "DiffuseColor"));+ connections.Add(Link(VideoId, TextureId));+ }+ return Document(version, upAxis, unitScale, objects, connections);+ }++ /// <summary>The header, global settings and material template around <paramref name="objects"/>.</summary>+ public static List<Node> Document(int version, int upAxis, double unitScale, Node objects, Node connections) =>+ [+ new Node("FBXHeaderExtension")+ {+ new Node("FBXHeaderVersion", 1003),+ new Node("FBXVersion", version),+ new Node("Creator", "Filee tests"),+ },+ new Node("GlobalSettings")+ {+ new Node("Version", 1000),+ new Node("Properties70")+ {+ IntProperty("UpAxis", upAxis),+ IntProperty("UpAxisSign", 1),+ // Z up as 3ds Max writes it: front is −Y.+ IntProperty("FrontAxis", upAxis == 2 ? 1 : 2),+ IntProperty("FrontAxisSign", upAxis == 2 ? -1 : 1),+ IntProperty("CoordAxis", 0),+ IntProperty("CoordAxisSign", 1),+ new Node("P", "UnitScaleFactor", "double", "Number", "", unitScale),+ },+ },+ new Node("Definitions")+ {+ new Node("Version", 100),+ new Node("ObjectType", "Material")+ {+ new Node("Count", 1),+ new Node("PropertyTemplate", "FbxSurfacePhong")+ {+ new Node("Properties70")+ {+ ColorProperty("DiffuseColor", new Vector3(0.8f)),+ new Node("P", "Opacity", "double", "Number", "", 0.5),+ },+ },+ },+ },+ objects,+ connections,+ ];++ /// <summary>The 8 corners and 6 outward quads of the cube from −1 to 1 (the last corner of each quad bit-inverted).</summary>+ public static (double[] Positions, int[] Polygons) Cube()+ {+ var positions = new List<double>();+ for (var i = 0; i < 8; i++)+ positions.AddRange([(i & 1) == 0 ? -1 : 1, (i & 2) == 0 ? -1 : 1, (i & 4) == 0 ? -1 : 1]);+ int[][] quads = [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]];+ return ([.. positions], [.. quads.SelectMany(q => new[] { q[0], q[1], q[2], ~q[3] })]);+ }++ public static Node Mesh(long id, string name, double[] positions, int[] polygons, params Node[] layers)+ {+ var node = new Node("Geometry", id, $"Geometry::{name}", "Mesh")+ {+ new Node("Vertices", positions),+ new Node("PolygonVertexIndex", polygons),+ new Node("GeometryVersion", 124),+ };+ node.Add(layers);+ return node;+ }++ /// <summary>Face normals per polygon corner (by polygon vertex, direct).</summary>+ public static Node Normals(double[] positions, int[] polygons)+ {+ var normals = new List<double>();+ var start = 0;+ for (var i = 0; i < polygons.Length; i++)+ {+ if (polygons[i] >= 0)+ continue;+ Vector3 P(int k)+ {+ var v = polygons[k] < 0 ? ~polygons[k] : polygons[k];+ return new Vector3((float)positions[v * 3], (float)positions[v * 3 + 1], (float)positions[v * 3 + 2]);+ }+ var n = Vector3.Normalize(Vector3.Cross(P(start + 1) - P(start), P(start + 2) - P(start)));+ for (var k = start; k <= i; k++)+ normals.AddRange([n.X, n.Y, n.Z]);+ start = i + 1;+ }+ return new Node("LayerElementNormal", 0)+ {+ new Node("Version", 101),+ new Node("MappingInformationType", "ByPolygonVertex"),+ new Node("ReferenceInformationType", "Direct"),+ new Node("Normals", normals.ToArray()),+ };+ }++ public static Node MaterialLayer(string mapping, params int[] materials) => new("LayerElementMaterial", 0)+ {+ new Node("Version", 101),+ new Node("MappingInformationType", mapping),+ new Node("ReferenceInformationType", "IndexToDirect"),+ new Node("Materials", materials),+ };++ public static Node Model(long id, string name, string type, params (string Name, Vector3 Value)[] properties)+ {+ var list = new Node("Properties70");+ foreach (var (property, value) in properties)+ list.Add(new Node("P", property, property, "", "A", (double)value.X, (double)value.Y, (double)value.Z));+ return new Node("Model", id, $"Model::{name}", type) { new Node("Version", 232), list };+ }++ public static Node Material(long id, string name, Vector3 color) => new("Material", id, $"Material::{name}", "")+ {+ new Node("ShadingModel", "phong"),+ new Node("Properties70") { ColorProperty("DiffuseColor", color) },+ };++ public static Node Link(long child, long parent) => new("C", "OO", child, parent);++ public static Node IntProperty(string name, int value) => new("P", name, "int", "Integer", "", value);++ public static Node ColorProperty(string name, Vector3 color) =>+ new("P", name, "Color", "", "A", (double)color.X, (double)color.Y, (double)color.Z);++ // ───────────────────────── Binary ─────────────────────────++ /// <summary>Binary FBX: 64-bit record offsets from version 7500; arrays zlib-compressed when <paramref name="compress"/>.</summary>+ public static void WriteBinary(string path, IEnumerable<Node> nodes, int version = 7400, bool compress = false)+ {+ var wide = version >= 7500;+ using var stream = new MemoryStream();+ var writer = new BinaryWriter(stream);+ writer.Write("Kaydara FBX Binary \0"u8);+ writer.Write((byte)0x1A);+ writer.Write((byte)0);+ writer.Write((uint)version);+ foreach (var node in nodes)+ WriteNode(writer, node, wide, compress);+ writer.Write(new byte[wide ? 25 : 13]);+ writer.Write(new byte[16]); // stands for the footer+ writer.Flush();+ File.WriteAllBytes(path, stream.ToArray());+ }++ private static void WriteNode(BinaryWriter writer, Node node, bool wide, bool compress)+ {+ var stream = writer.BaseStream;+ var start = stream.Position;+ writer.Write(new byte[wide ? 24 : 12]);+ var name = Encoding.ASCII.GetBytes(node.Name);+ writer.Write((byte)name.Length);+ writer.Write(name);+ var propertiesStart = stream.Position;+ foreach (var property in node.Properties)+ WriteProperty(writer, property, compress);+ var propertiesLength = stream.Position - propertiesStart;+ if (node.Children.Count > 0)+ {+ foreach (var child in node.Children)+ WriteNode(writer, child, wide, compress);+ writer.Write(new byte[wide ? 25 : 13]);+ }+ var end = stream.Position;+ stream.Position = start;+ if (wide)+ {+ writer.Write((ulong)end);+ writer.Write((ulong)node.Properties.Length);+ writer.Write((ulong)propertiesLength);+ }+ else+ {+ writer.Write((uint)end);+ writer.Write((uint)node.Properties.Length);+ writer.Write((uint)propertiesLength);+ }+ stream.Position = end;+ }++ private static void WriteProperty(BinaryWriter writer, object property, bool compress)+ {+ switch (property)+ {+ case int i:+ writer.Write((byte)'I');+ writer.Write(i);+ break;+ case long l:+ writer.Write((byte)'L');+ writer.Write(l);+ break;+ case double d:+ writer.Write((byte)'D');+ writer.Write(d);+ break;+ case string s:+ var bytes = Encoding.UTF8.GetBytes(BinaryName(s));+ writer.Write((byte)'S');+ writer.Write((uint)bytes.Length);+ writer.Write(bytes);+ break;+ case byte[] raw:+ writer.Write((byte)'R');+ writer.Write((uint)raw.Length);+ writer.Write(raw);+ break;+ case double[] doubles:+ WriteArray(writer, 'd', doubles.Length, MemoryMarshal.AsBytes(doubles.AsSpan()), compress);+ break;+ case int[] ints:+ WriteArray(writer, 'i', ints.Length, MemoryMarshal.AsBytes(ints.AsSpan()), compress);+ break;+ default:+ throw new ArgumentException($"No FBX property type for {property.GetType()}.");+ }+ }++ private static void WriteArray(BinaryWriter writer, char type, int length, ReadOnlySpan<byte> data, bool compress)+ {+ writer.Write((byte)type);+ writer.Write((uint)length);+ writer.Write(compress ? 1u : 0u);+ if (!compress)+ {+ writer.Write((uint)data.Length);+ writer.Write(data);+ return;+ }+ using var packed = new MemoryStream();+ using (var zlib = new ZLibStream(packed, CompressionLevel.Optimal, leaveOpen: true))+ zlib.Write(data);+ writer.Write((uint)packed.Length);+ writer.Write(packed.ToArray());+ }++ /// <summary>"Model::Cube" as binary FBX writes object names: "Cube\0\u0001Model".</summary>+ private static string BinaryName(string text)+ {+ var separator = text.IndexOf("::", StringComparison.Ordinal);+ return separator > 0 && text[..separator] is "Model" or "Geometry" or "Material" or "Texture" or "Video"+ ? $"{text[(separator + 2)..]}\0\u0001{text[..separator]}"+ : text;+ }++ // ───────────────────────── ASCII ─────────────────────────++ public static void WriteAscii(string path, IEnumerable<Node> nodes)+ {+ var text = new StringBuilder("; FBX 7.4.0 project file\n; Written by the Filee tests\n\n");+ foreach (var node in nodes)+ WriteAscii(text, node, 0);+ File.WriteAllText(path, text.ToString());+ }++ private static void WriteAscii(StringBuilder text, Node node, int depth)+ {+ var indent = new string('\t', depth);+ text.Append(indent).Append(node.Name).Append(':');+ if (node.Properties is [Array array] && array is not byte[])+ {+ var values = array.Cast<object>().Select(Format).ToList();+ text.Append(" *").Append(values.Count).Append(" {\n")+ .Append(indent).Append("\ta: ");+ // Long arrays are wrapped after a comma, as the FBX SDK does.+ for (var i = 0; i < values.Count; i++)+ text.Append(i == 0 ? "" : i % 8 == 0 ? ",\n" + indent + "\t" : ",").Append(values[i]);+ text.Append('\n').Append(indent).Append("} \n");+ return;+ }+ // Embedded files start with an empty value: "Content: , "base64...""+ text.Append(node.Properties is [byte[], ..] ? " , " : " ").AppendJoin(", ", node.Properties.Select(Format));+ if (node.Children.Count > 0)+ {+ text.Append(" {\n");+ foreach (var child in node.Children)+ WriteAscii(text, child, depth + 1);+ text.Append(indent).Append('}');+ }+ text.Append('\n');+ }++ private static string Format(object value) => value switch+ {+ string s => $"\"{s}\"",+ byte[] bytes => $"\"{Convert.ToBase64String(bytes)}\"",+ double d => d.ToString("R", CultureInfo.InvariantCulture),+ IFormattable f => f.ToString(null, CultureInfo.InvariantCulture),+ _ => value.ToString() ?? "",+ };+}diff --git a/tests/Filee.Engines.Tests/FbxTests.cs b/tests/Filee.Engines.Tests/FbxTests.csnew file mode 100644index 00000000..134c4e5f--- /dev/null+++ b/tests/Filee.Engines.Tests/FbxTests.cs@@ -0,0 +1,298 @@+// FBX (read only) into the 3D formats and pictures. The files are written here (FbxBuilder): binary 7.4 and 7.5,+// with plain and compressed arrays, and ASCII; then converted through the job queue or read directly.++using System.Numerics;+using Filee.Core.Conversion;+using Filee.Core.Formats;+using Filee.Core.Presets;+using Filee.Engines.Models3D;+using ImageMagick;+using SharpGLTF.Schema2;+using static Filee.Engines.Tests.FbxBuilder;++namespace Filee.Engines.Tests;++public class FbxTests(EngineFixture fx) : IClassFixture<EngineFixture>+{+ /// <summary>The test cube's bounds in millimetres, Y up (see <see cref="FbxBuilder.CubeScene"/>).</summary>+ private static readonly Vector3 CubeMin = new(80, 40, -30), CubeMax = new(120, 60, 30);++ private async Task<ConversionJob> RunAsync(string input, string target)+ {+ var job = await fx.ConvertAsync([input], new Preset { TargetFormat = target });+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));+ return job;+ }++ private async Task<string> FailAsync(string input, string target)+ {+ var job = await fx.ConvertAsync([input], new Preset { TargetFormat = target });+ Assert.Equal(JobState.Failed, job.State);+ return job.Files.Single().ErrorDetail ?? "";+ }++ private string Binary(List<FbxBuilder.Node> scene, int version = 7400, bool compress = false)+ {+ var path = Path.Combine(fx.NewFolder(), "model.fbx");+ WriteBinary(path, scene, version, compress);+ return path;+ }++ private static void AssertClose(Vector3 expected, Vector3 actual, float tolerance) =>+ Assert.True(Vector3.Distance(expected, actual) <= tolerance, $"Expected {expected}, got {actual}");++ private static void AssertClose(Vector4 expected, Vector4 actual, float tolerance) =>+ Assert.True(Vector4.Distance(expected, actual) <= tolerance, $"Expected {expected}, got {actual}");++ // ───────────────────────── Routes ─────────────────────────++ [Fact]+ public void Fbx_is_read_only_and_one_step_to_every_3d_format_and_picture()+ {+ Assert.False(FormatRegistry.Get("fbx").Writable);+ Assert.Equal(FormatCategory.Model3D, FormatRegistry.FindByExtension(".FBX")?.Category);+ var planner = fx.Catalog.CreatePlanner();+ foreach (var to in ModelConverter.Formats.Concat(["png", "jpg", "webp"]))+ {+ var route = planner.Plan("fbx", to);+ Assert.NotNull(route);+ Assert.Equal("model3d", Assert.Single(route.Steps).Converter.Id);+ }+ Assert.Null(planner.Plan("glb", "fbx"));+ }++ // ───────────────────────── Binary and ASCII ─────────────────────────++ [Theory]+ [InlineData(7400, false)]+ [InlineData(7400, true)]+ [InlineData(7500, false)]+ [InlineData(7500, true)]+ public async Task Binary_fbx_keeps_the_hierarchy_transforms_and_material(int version, bool compress)+ {+ var fbx = Binary(CubeScene(version), version, compress);++ var glb = (await RunAsync(fbx, "glb")).Outputs.Single();+ var model = ModelBuilders.Load(glb, "glb");++ Assert.Equal(12, model.TriangleCount);+ Assert.Equal(24, model.VertexCount); // a corner per face: the normals differ+ var (min, max) = model.Bounds();+ AssertClose(CubeMin, min, 1e-2f);+ AssertClose(CubeMax, max, 1e-2f);+ // 40 × 20 × 60 mm, closed and facing outwards after the turn and the scaling.+ Assert.Equal(40 * 20 * 60, ModelBuilders.SignedVolume(model), 1);+ var part = Assert.Single(model.Parts);+ Assert.NotNull(part.Normals);+ Assert.NotNull(part.TexCoords);+ var center = (min + max) / 2;+ for (var t = 0; t < part.TriangleCount; t++)+ {+ var a = part.Position(part.Indices[t * 3]);+ Assert.True(Vector3.Dot(part.Normal(part.Indices[t * 3]), a - center) > 0, $"Triangle {t} has an inward normal");+ }+ // Red from the material, opacity 0.5 from the material template.+ AssertClose(new Vector4(1, 0, 0, 0.5f), Assert.Single(model.Materials).BaseColor, 1e-4f);+ Assert.Equal("Cube", part.Name);+ }++ [Fact]+ public async Task Ascii_fbx_reads_like_binary_and_becomes_obj_with_its_material()+ {+ var folder = fx.NewFolder();+ var ascii = Path.Combine(folder, "ascii.fbx");+ WriteAscii(ascii, CubeScene());+ var model = ModelBuilders.Load(ascii, "fbx");+ var binary = ModelBuilders.Load(Binary(CubeScene()), "fbx");++ Assert.Equal(binary.TriangleCount, model.TriangleCount);+ Assert.Equal(ModelBuilders.Positions(binary), ModelBuilders.Positions(model));+ var (min, max) = model.Bounds();+ AssertClose(CubeMin, min, 1e-2f);+ AssertClose(CubeMax, max, 1e-2f);++ var job = await RunAsync(ascii, "obj");+ var obj = ModelBuilders.Load(job.Outputs.Single(o => o.EndsWith(".obj", StringComparison.Ordinal)), "obj");+ Assert.Equal(12, obj.TriangleCount);+ AssertClose(new Vector4(1, 0, 0, 0.5f), Assert.Single(obj.Materials).BaseColor, 1e-4f);+ Assert.Contains("Kd 1 0 0", File.ReadAllText(job.Outputs.Single(o => o.EndsWith(".mtl", StringComparison.Ordinal))));+ }++ // ───────────────────────── Axes and units ─────────────────────────++ [Fact]+ public async Task Z_up_fbx_in_metres_stands_up_in_gltf()+ {+ // In metres, the cube spans (8, 4, −3)–(12, 6, 3) with Z up; Y up that is (8, −3, −6)–(12, 3, −4).+ var fbx = Binary(CubeScene(upAxis: 2, unitScale: 100), compress: true);++ var glb = (await RunAsync(fbx, "glb")).Outputs.Single();+ var (min, max) = ModelRoot.Load(glb).LogicalMeshes.Single().Primitives.Single().GetVertexAccessor("POSITION").Bounds;+ AssertClose(new Vector3(8, -3, -6), new Vector3((float)min[0], (float)min[1], (float)min[2]), 1e-4f);+ AssertClose(new Vector3(12, 3, -4), new Vector3((float)max[0], (float)max[1], (float)max[2]), 1e-4f);+ // The axis change is a turn, not a mirror: still closed and outward.+ Assert.Equal(48, ModelBuilders.SignedVolume(ModelBuilders.Load(glb, "glb")) / 1e9, 1e-3); // 4 × 6 × 2 m+ }++ // ───────────────────────── Rotation order, polygons, materials ─────────────────────────++ [Fact]+ public void Rotation_order_pre_rotation_polygons_and_materials_by_polygon_are_read()+ {+ // "Turned": one triangle (0,0,0) (2,0,0) (0,1,0), rotation (90, 90, 0) in ZYX order (Y first, then X), then+ // a pre-rotation of 90° about Z: (2,0,0) → (0,0,−2) → (0,2,0) → (−2,0,0) and (0,1,0) → (0,1,0) → (0,0,1).+ // "Shapes": a triangle (material 0) and a concave pentagon (material 1, area 10 cm²).+ var turned = Model(301, "Turned", "Mesh", ("Lcl Rotation", new Vector3(90, 90, 0)), ("PreRotation", new Vector3(0, 0, 90)));+ turned.Children[1].Add(IntProperty("RotationOrder", 5));+ var objects = new FbxBuilder.Node("Objects")+ {+ Mesh(101, "Triangle", [0, 0, 0, 2, 0, 0, 0, 1, 0], [0, 1, ~2]),+ turned,+ Mesh(102, "Shapes",+ [10, 0, 0, 11, 0, 0, 10, 1, 0, /* pentagon */ 0, 0, 0, 4, 0, 0, 4, 4, 0, 2, 1, 0, 0, 4, 0],+ [0, 1, ~2, 3, 4, 5, 6, ~7],+ MaterialLayer("ByPolygon", 0, 1)),+ Model(302, "Shapes", "Mesh"),+ Material(401, "Red", new Vector3(1, 0, 0)),+ Material(402, "Blue", new Vector3(0, 0, 1)),+ };+ var connections = new FbxBuilder.Node("Connections")+ {+ Link(301, 0), Link(101, 301), Link(302, 0), Link(102, 302), Link(401, 302), Link(402, 302),+ };+ var path = Binary(Document(7400, 1, 1, objects, connections));++ var model = ModelBuilders.Load(path, "fbx");++ var triangle = model.Parts.Single(p => p.Name == "Turned");+ var bounds = new Model3D { Parts = { triangle } }.Bounds();+ AssertClose(new Vector3(-20, 0, 0), bounds.Min, 1e-3f);+ AssertClose(new Vector3(0, 0, 10), bounds.Max, 1e-3f);++ var shapes = model.Parts.Where(p => p.Name == "Shapes").ToList();+ Assert.Equal(2, shapes.Count);+ var red = shapes.Single(p => model.MaterialOf(p)?.Name == "Red");+ var blue = shapes.Single(p => model.MaterialOf(p)?.Name == "Blue");+ Assert.Equal(1, red.TriangleCount);+ Assert.Equal(3, blue.TriangleCount);+ AssertClose(new Vector4(0, 0, 1, 0.5f), model.MaterialOf(blue)!.BaseColor, 1e-4f);+ // Ear clipping keeps the notch: 4 × 4 − 6 = 10 cm² = 1000 mm².+ Assert.Equal(1000, ModelBuilders.Area(new Model3D { Parts = { blue } }), 1e-2);+ }++ // ───────────────────────── Textures and pictures ─────────────────────────++ [Fact]+ public async Task An_embedded_texture_goes_into_the_glb()+ {+ var checker = ModelBuilders.Checker();+ var fbx = Binary(CubeScene(texture: checker), compress: true);++ var glb = (await RunAsync(fbx, "glb")).Outputs.Single();+ Assert.Equal(checker, ModelBuilders.Load(glb, "glb").Materials.Single().BaseColorTexture?.Data);++ // ASCII files embed it as base64.+ var ascii = Path.Combine(fx.NewFolder(), "textured.fbx");+ WriteAscii(ascii, CubeScene(texture: checker));+ var texture = ModelBuilders.Load(ascii, "fbx").Materials.Single().BaseColorTexture;+ Assert.Equal(checker, texture?.Data);+ Assert.Equal(("png", "checker"), (texture!.Extension, texture.Name));+ }++ [Fact]+ public async Task A_texture_file_next_to_the_fbx_is_found_by_its_relative_name()+ {+ var checker = ModelBuilders.Checker();+ var fbx = Binary(CubeScene(texture: []));+ File.WriteAllBytes(Path.Combine(Path.GetDirectoryName(fbx)!, "checker.png"), checker);++ var glb = (await RunAsync(fbx, "glb")).Outputs.Single();+ Assert.Equal(checker, ModelBuilders.Load(glb, "glb").Materials.Single().BaseColorTexture?.Data);+ }++ [Fact]+ public async Task Fbx_renders_a_png_preview_in_the_material_colour()+ {+ var png = (await RunAsync(Binary(CubeScene()), "png")).Outputs.Single();++ using var image = new MagickImage(png);+ Assert.Equal(MagickFormat.Png, image.Format);+ var rgba = image.ToByteArray(MagickFormat.Rgba);+ var opaque = 0;+ var reddish = 0;+ for (var i = 0; i + 3 < rgba.Length; i += 4)+ {+ if (rgba[i + 3] < 128)+ continue;+ opaque++;+ if (rgba[i] > rgba[i + 1] * 2 && rgba[i] > rgba[i + 2] * 2)+ reddish++;+ }+ Assert.True(opaque > 1000, $"{opaque} opaque pixels");+ Assert.True(reddish > opaque / 2, $"{reddish} of {opaque} pixels are red");+ }++ // ───────────────────────── Bad input ─────────────────────────++ [Fact]+ public async Task Broken_fbx_files_fail_with_a_clear_message()+ {+ var folder = fx.NewFolder();++ var text = Path.Combine(folder, "text.fbx");+ File.WriteAllText(text, "hello");+ Assert.Contains("not an FBX model", await FailAsync(text, "glb"));++ var whole = File.ReadAllBytes(Binary(CubeScene(), compress: true));+ var cut = Path.Combine(folder, "cut.fbx");+ File.WriteAllBytes(cut, whole[..(whole.Length / 2)]);+ Assert.Contains("cut short or damaged", await FailAsync(cut, "glb"));++ var bad = Path.Combine(folder, "bad.fbx");+ var (positions, polygons) = Cube();+ polygons[5] = 42;+ WriteBinary(bad, Document(7400, 1, 1,+ new FbxBuilder.Node("Objects") { Mesh(100, "Cube", positions, polygons), Model(300, "Cube", "Mesh") },+ new FbxBuilder.Node("Connections") { Link(300, 0), Link(100, 300) }));+ Assert.Contains("refers to vertex 43", await FailAsync(bad, "stl"));++ var empty = Path.Combine(folder, "empty.fbx");+ WriteBinary(empty, Document(7400, 1, 1, new FbxBuilder.Node("Objects"), new FbxBuilder.Node("Connections")));+ Assert.Contains("contains no triangles", await FailAsync(empty, "stl"));+ }++ [Theory]+ [InlineData(7400, false)]+ [InlineData(7500, true)]+ public void Every_cut_or_flipped_byte_reads_or_fails_cleanly(int version, bool compress)+ {+ // A damaged file must end in a model or an InvalidDataException: no other exception, no hang.+ var whole = File.ReadAllBytes(Binary(CubeScene(version, texture: ModelBuilders.Checker()), version, compress));+ var folder = fx.NewFolder();+ var watch = System.Diagnostics.Stopwatch.StartNew();+ for (var length = 0; length < whole.Length; length++)+ ReadsOrFailsCleanly(whole[..length], folder);+ for (var i = 23; i < whole.Length; i++)+ {+ var copy = (byte[])whole.Clone();+ copy[i] ^= (byte)(i % 3 == 0 ? 0x80 : 0xFF);+ ReadsOrFailsCleanly(copy, folder);+ }++ var ascii = Path.Combine(fx.NewFolder(), "ascii.fbx");+ WriteAscii(ascii, CubeScene());+ var text = File.ReadAllBytes(ascii);+ for (var length = 0; length < text.Length; length++)+ ReadsOrFailsCleanly(text[..length], folder);+ Assert.True(watch.Elapsed < TimeSpan.FromSeconds(30), $"took {watch.Elapsed}");+ }++ private static void ReadsOrFailsCleanly(byte[] data, string folder)+ {+ try+ {+ FbxFormat.Read(data, folder, CancellationToken.None).Validate();+ }+ catch (InvalidDataException) { }+ }+}