Skip to content

Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.

GoZ interoperability with ZBrush, plus STL

islandmed14cd52aaeb81
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 4e439795..f1a38649 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -48,6 +48,9 @@ add_library(sculptforge_core STATIC
src/io/PlyIO.cpp
src/io/UsdIO.cpp
src/io/Zip.cpp
+ src/io/GozIO.cpp
+ src/io/GozCommands.cpp
+ src/io/StlIO.cpp
)
target_include_directories(sculptforge_core PUBLIC src PRIVATE third_party/stb third_party/ufbx)
# Third-party C code: compile quietly.
@@ -103,6 +106,7 @@ if(SCULPTFORGE_BUILD_APP)
src/app/main.cpp
src/app/App.cpp
src/app/Demo.cpp
+ src/app/PanelGoz.cpp
src/render/GL.cpp
src/render/Camera.cpp
src/render/Renderer.cpp
diff --git a/docs/goz.md b/docs/goz.md
new file mode 100644
index 00000000..92cd8d13
--- /dev/null
+++ b/docs/goz.md
@@ -0,0 +1,110 @@
+# ZBrush interoperability (GoZ) and STL
+
+SculptForge reads and writes ZBrush's **GoZ** bridge format and can send meshes to and receive them
+from a running ZBrush the way GoZ-enabled apps do. The format notes below come from reading
+[GoB](https://github.com/JoseConseco/GoB), the open-source (GPL) Blender GoZ add-on by Daniel Grauer,
+JoseConseco and contributors. Its `gob_import.py`, `gob_export.py` and `paths.py` are the
+reference for this implementation. Many thanks to them.
+
+ZBrush's own **.ZTL** (tool) and **.ZPR** (project) files are proprietary and undocumented, so SculptForge
+cannot open them. Opening one gives an error that suggests sending the model with GoZ or exporting OBJ/FBX
+from ZBrush.
+
+Code: `src/io/GozIO.h/.cpp` (format + bridge), `src/io/StlIO.h/.cpp`, `src/io/GozCommands.cpp`
+(commands), `src/app/PanelGoz.cpp` (File > ZBrush (GoZ) menu). Tests: `tests/test_goz.cpp`.
+
+## Commands
+
+| Command | What it does |
+|---------|--------------|
+| `goz_import path=` | Open a `.GoZ` file (`open` does the same for `.GoZ`) |
+| `goz_export path= [name=] [quads=true]` | Write a `.GoZ` file |
+| `goz_send [name=] [folder=] [launch=true] [zbrush=]` | Send the mesh to ZBrush through the bridge |
+| `goz_receive [folder=]` | Load what ZBrush last sent (undoable; several SubTools are merged) |
+| `export_stl path=` | Binary STL (`open` reads binary and ASCII `.stl`) |
+
+All of them are available in `sculptforge-cli`, the MCP server and Python, like every other command.
+
+## The .GoZ file
+
+Everything is little-endian. After the header comes a list of sections. Each section is a `uint32` tag
+and a `uint32` length. The length counts the tag and length fields too, so `length - 8` bytes follow.
+Element sections (vertices, faces...) then hold a `uint64` count and `length - 16` payload bytes.
+
+| Offset / tag | Contents |
+|--------------|----------|
+| 0 | `"GoZb 1.0 ZBrush GoZ Binary"` (26 bytes) + six `'.'` (0x2E) |
+| 32 | `uint32 1`, the tag of the object-name record |
+| 36 | `uint32 length` (= name length + 24), `uint64 1`, `"GoZMesh_"` + ASCII name |
+| `0x1389` | mesh name record: length 20, `uint64 1`, `uint32 0` (skipped) |
+| `0x138A` | subdivision level records, 4 × `uint32` each (read for information only) |
+| `0x2711` | vertices: count, then `float32 x, y, z` each |
+| `0x4E21` | faces: count, then 4 × `uint32` indices; the 4th is `0xFFFFFFFF` for triangles |
+| `0x61A9` | UVs: face count, then 4 corners × `float32 u, v` per face (triangles pad with (0, 1)) |
+| `0x88B9` | polypaint: vertex count (GoB writes it as `uint32` + `float32 0`), then `B, G, R, 0` bytes per vertex, sRGB |
+| `0x7532` | mask: count, then `uint16` per vertex, **65535 = unmasked, 0 = fully masked** |
+| `0x9C41` | polygroups: face count, then a `uint16` id per face (GoB uses 65504 for "no group") |
+| `0xAFC9` / `0xD6D9` / `0xC351` | diffuse / displacement / normal map path (`uint64 1` + bytes); kept in `GozInfo`, not loaded |
+| `0x0000` | end of file: GoB writes 16 zero bytes |
+
+Unknown tags are skipped using their length. Section lengths are checked against the file size, and
+faces with out-of-range indices are dropped, so a broken file cannot read past its end.
+
+### Conventions and mapping to `sf::Mesh`
+
+- **Axes.** ZBrush is Y-down. GoB maps GoZ `(x, y, z)` to Blender `(x, z, -y)` (Z-up). In SculptForge's
+ Y-up space that is `(x, -y, -z)`, a 180° turn about X, which keeps the triangle winding. It is applied
+ on import and undone on export. GoB's default scale factor is 1, so no unit scaling is applied.
+- **Faces.** A quad `(a, b, c, d)` becomes two consecutive triangles, `(a, b, c)` and `(a, c, d)`.
+ On export, consecutive triangles with exactly that pattern are written back as one quad, provided the
+ pair shares a polygroup and its UVs agree on the shared corners (`quads=false` turns this off). A mesh
+ imported from ZBrush therefore goes back with its original quads, and other meshes are written mostly
+ as triangles. Degenerate triangles (e.g. a quad with a repeated index) are dropped.
+- **UVs.** GoZ stores V downwards, and GoB flips V both ways by default. `Mesh::uvs` uses V up
+ (OpenGL/OBJ), so V is flipped on the way in and out. There are 3 corners per triangle, in triangle order.
+- **Polypaint.** The bytes are sRGB. `Mesh::colors` is linear, so they are converted with
+ `srgbToLinear`/`linearToSrgb`.
+- **Mask.** `Mesh::mask = 1 - value / 65535`. A section that masks nothing is dropped, so no memory is used.
+- **Polygroups.** The 16-bit ids are stored as they are in `Mesh::polygroups`. On export, ids above 65535
+ keep only their low 16 bits.
+- **Hidden faces.** GoZ has no hidden flag, so hidden triangles are exported like any others.
+- The object name (`GozInfo::name`) is remembered in `Document::gozName`, so `goz_send` updates the
+ SubTool the mesh came from.
+
+## The bridge (Windows, macOS)
+
+GoZ apps exchange files through a shared folder:
+
+- Windows: `%PUBLIC%\Pixologic` (usually `C:\Users\Public\Pixologic`)
+- macOS: `/Users/Shared/Pixologic`
+- Linux: ZBrush doesn't run there, so there is no default. The bridge commands explain this, and GoZ
+ files can still be imported and exported. Setting a custom folder (the `folder=` argument, or the
+ field in File > ZBrush (GoZ)), such as a Wine prefix's `drive_c/users/Public/Pixologic`, makes the
+ bridge work anyway.
+
+**Send** (`goz_send`), following GoB's `GoB_OT_export.execute`:
+
+1. Write `GoZProjects/Default/<Name>.GoZ`, plus `<Name>.ztn`, which holds the object path without its extension.
+2. Write that path (forward slashes, no extension) as the only line of `GoZBrush/GoZ_ObjectList.txt`.
+3. Write `GoZBrush/GoZ_Application.txt` = `SculptForge` and `GoZBrush/GoZ_ProjectPath.txt`.
+4. Register SculptForge as a GoZ application: `GoZApps/SculptForge/GoZ_Info.txt` (same keys as GoB's
+ `Blender/GoZ_Info.txt`) and `GoZ_Config.txt` (`PATH = "<sculptforge executable>"`, written by the app).
+5. Tell ZBrush. If `GoZBrush/GoZBrushFromApp(.exe|.app)` (installed by ZBrush's GoZ setup) exists, it is
+ started. That is how official GoZ plug-ins make a running ZBrush import the object list. Otherwise
+ the newest ZBrush in the default install folders, or `zbrush=`, is started, like GoB's
+ `find_zbrush`. GoB also starts its own compiled ZScript at that point. SculptForge does not ship a
+ ZScript, so after a fresh start you press GoZ in ZBrush.
+
+**Receive** (`goz_receive`), following GoB's `GoB_OT_import.execute`: read `GoZ_ObjectList.txt`, append
+`.GoZ` to each line and load every object. The objects are merged into one mesh, and the result replaces the
+current mesh as an undoable step.
+
+In the app, **Receive automatically** checks the object list's modification time once a second and
+receives when ZBrush rewrites it, which is what GoB's auto-import timer does. Sending turns it on and
+remembers the file time of SculptForge's own write, so a send is never received back.
+
+## STL
+
+`open` reads binary STL and ASCII STL. A file is binary when its size is exactly `84 + 50 × count`,
+otherwise it must start with `solid`. Coincident corners are welded with `weldImported`. `export_stl`
+writes binary STL with facet normals. Positions are kept as stored, with no axis or unit conversion.
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 2125f4ba..07a85640 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -42,7 +42,7 @@ namespace {
const SDL_DialogFileFilter kObjFilters[] = {{"Wavefront OBJ", "obj"}, {"All files", "*"}};
const SDL_DialogFileFilter kGlbFilters[] = {{"glTF binary", "glb"}, {"All files", "*"}};
const SDL_DialogFileFilter kBrushFilters[] = {{"SculptForge brush", "sfbrush"}, {"All files", "*"}};
-const SDL_DialogFileFilter kModelFilters[] = {{"Models and splats", "obj;fbx;glb;gltf;ply;splat;usda;usd;usdz"}, {"All files", "*"}};
+const SDL_DialogFileFilter kModelFilters[] = {{"Models and splats", "obj;fbx;glb;gltf;ply;stl;GoZ;goz;splat;usda;usd;usdz"}, {"All files", "*"}};
const SDL_DialogFileFilter kFbxFilters[] = {{"FBX", "fbx"}, {"All files", "*"}};
const SDL_DialogFileFilter kUsdFilters[] = {{"USDZ package", "usdz"}, {"USD text", "usda"}};
const SDL_DialogFileFilter kSplatFilters[] = {{"Gaussian splats (PLY)", "ply"}, {"glTF splats", "glb"}, {"OpenUSD", "usda;usdz"}};
@@ -365,6 +365,7 @@ int App::run() {
pollBrushRequest();
pollGenerator();
pollUnreal();
+ pollGoz();
int fbW = 0, fbH = 0, winW = 0, winH = 0;
SDL_GetWindowSizeInPixels(window_, &fbW, &fbH);
@@ -902,6 +903,8 @@ void App::drawMenuBar() {
if (ImGui::MenuItem("Send to Unreal", "Ctrl+U", false, !pendingUnreal_.valid())) sendToUnreal();
if (ImGui::MenuItem("Save Splats...", nullptr, false, !doc_.splats.empty())) saveFileDialog(FileAction::SaveSplats);
ImGui::Separator();
+ drawGozMenu();
+ ImGui::Separator();
if (ImGui::MenuItem("Quit")) running_ = false;
ImGui::EndMenu();
}
diff --git a/src/app/App.h b/src/app/App.h
index e6de675a..0f717a17 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -229,6 +229,24 @@ private:
const Mesh* lastDisplayed_ = nullptr;
std::mutex pendingMutex_;
std::vector<PendingFile> pendingFiles_;
+
+ // ZBrush GoZ bridge and GoZ/STL files (PanelGoz.cpp).
+ void drawGozMenu();
+ void pollGoz();
+ void runGozCommand(const std::string& name, const Args& args = {});
+ static void SDLCALL onGozFileChosen(void* userdata, const char* const* files, int filter);
+ enum class GozFile { Import, Export, ExportStl, Count };
+ struct GozDialog {
+ App* app;
+ GozFile kind;
+ };
+ GozDialog gozDialogs_[int(GozFile::Count)];
+ std::vector<std::pair<GozFile, std::string>> gozPendingFiles_; // guarded by pendingMutex_
+ char gozFolder_[512] = ""; // custom GoZ root (empty = the platform default)
+ bool gozAutoReceive_ = false; // import whenever ZBrush rewrites GoZ_ObjectList.txt
+ long long gozListTime_ = 0; // last seen modification time of the object list
+ Uint64 gozLastPollNs_ = 0;
+ bool gozInitialised_ = false;
};
} // namespace sf
diff --git a/src/app/PanelGoz.cpp b/src/app/PanelGoz.cpp
new file mode 100644
index 00000000..8d074236
--- /dev/null
+++ b/src/app/PanelGoz.cpp
@@ -0,0 +1,112 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// File > ZBrush (GoZ): send/receive through the GoZ bridge, GoZ and STL files.
+#include "app/App.h"
+
+#include "io/GozIO.h"
+
+#include <filesystem>
+
+namespace sf {
+
+namespace {
+
+const SDL_DialogFileFilter kGozFilters[] = {{"ZBrush GoZ", "GoZ;goz"}, {"All files", "*"}};
+const SDL_DialogFileFilter kStlFilters[] = {{"STL", "stl"}, {"All files", "*"}};
+
+long long fileTime(const std::string& path) {
+ if (path.empty()) return 0;
+ std::error_code ec;
+ auto t = std::filesystem::last_write_time(std::filesystem::path(std::u8string(path.begin(), path.end())), ec);
+ return ec ? 0 : static_cast<long long>(t.time_since_epoch().count());
+}
+
+} // namespace
+
+void SDLCALL App::onGozFileChosen(void* userdata, const char* const* files, int) {
+ if (!files || !files[0]) return;
+ auto* req = static_cast<GozDialog*>(userdata);
+ std::string path = files[0];
+ if (req->kind != GozFile::Import &&
+ std::filesystem::path(std::u8string(path.begin(), path.end())).extension().empty())
+ path += req->kind == GozFile::ExportStl ? ".stl" : ".GoZ";
+ std::lock_guard lock(req->app->pendingMutex_);
+ req->app->gozPendingFiles_.push_back({req->kind, std::move(path)});
+}
+
+void App::runGozCommand(const std::string& name, const Args& args) {
+ Args a = args;
+ if (gozFolder_[0] && (name == "goz_send" || name == "goz_receive")) a["folder"] = std::string(gozFolder_);
+ runCommand(name, a);
+ // A new mesh arrived: frame it (runCommand does this for "open").
+ if ((name == "goz_receive" || name == "goz_import") &&
+ (status_.rfind("Received", 0) == 0 || status_.rfind("Opened", 0) == 0))
+ camera_.frame(sceneBounds());
+ if (name == "goz_send") gozListTime_ = fileTime(gozObjectListPath(gozFolder_[0] ? gozFolder_ : gozDefaultRoot()));
+}
+
+void App::drawGozMenu() {
+ if (!gozInitialised_) pollGoz(); // sets up the dialogs
+ if (!ImGui::BeginMenu("ZBrush (GoZ)")) return;
+ const std::string root = gozFolder_[0] ? std::string(gozFolder_) : gozDefaultRoot();
+ const bool bridge = !root.empty();
+ if (ImGui::MenuItem("Send to ZBrush")) {
+ runGozCommand("goz_send");
+ if (bridge) gozAutoReceive_ = true; // a round trip comes back the same way
+ }
+ if (!bridge && ImGui::IsItemHovered()) ImGui::SetTooltip("%s", gozUnavailableMessage().c_str());
+ if (ImGui::MenuItem("Receive from ZBrush")) runGozCommand("goz_receive");
+ if (!bridge && ImGui::IsItemHovered()) ImGui::SetTooltip("%s", gozUnavailableMessage().c_str());
+ if (ImGui::MenuItem("Receive automatically", nullptr, &gozAutoReceive_, bridge) && gozAutoReceive_)
+ gozListTime_ = fileTime(gozObjectListPath(root));
+ if (bridge) ImGui::TextDisabled("GoZ folder: %s", root.c_str());
+ else ImGui::TextDisabled("ZBrush runs on Windows and macOS only;\nGoZ files still import and export.");
+ ImGui::SetNextItemWidth(260.0f * uiScale_);
+ ImGui::InputTextWithHint("##gozfolder", "Custom GoZ folder (optional)", gozFolder_, sizeof(gozFolder_));
+ ImGui::Separator();
+ if (ImGui::MenuItem("Import GoZ..."))
+ SDL_ShowOpenFileDialog(onGozFileChosen, &gozDialogs_[int(GozFile::Import)], window_, kGozFilters, 2, nullptr, false);
+ if (ImGui::MenuItem("Export GoZ..."))
+ SDL_ShowSaveFileDialog(onGozFileChosen, &gozDialogs_[int(GozFile::Export)], window_, kGozFilters, 2, nullptr);
+ if (ImGui::MenuItem("Export STL..."))
+ SDL_ShowSaveFileDialog(onGozFileChosen, &gozDialogs_[int(GozFile::ExportStl)], window_, kStlFilters, 2, nullptr);
+ ImGui::EndMenu();
+}
+
+void App::pollGoz() {
+ if (!gozInitialised_) {
+ gozInitialised_ = true;
+ for (int i = 0; i < int(GozFile::Count); ++i) gozDialogs_[i] = {this, GozFile(i)};
+ // Register this executable as ZBrush's GoZ target (GoZApps/SculptForge/GoZ_Config.txt).
+ if (const char* base = SDL_GetBasePath()) {
+#ifdef _WIN32
+ setGozApplicationPath(std::string(base) + "sculptforge.exe");
+#else
+ setGozApplicationPath(std::string(base) + "sculptforge");
+#endif
+ }
+ }
+ std::vector<std::pair<GozFile, std::string>> files;
+ {
+ std::lock_guard lock(pendingMutex_);
+ files.swap(gozPendingFiles_);
+ }
+ for (const auto& [kind, path] : files) {
+ if (kind == GozFile::Import) runGozCommand("goz_import", {{"path", path}});
+ else runGozCommand(kind == GozFile::Export ? "goz_export" : "export_stl", {{"path", path}});
+ }
+
+ // Auto-receive: ZBrush rewrites GoZ_ObjectList.txt on every GoZ send. Check once a second.
+ if (!gozAutoReceive_ || doc_.sculptor.strokeActive()) return;
+ const Uint64 now = SDL_GetTicksNS();
+ if (now - gozLastPollNs_ < 1'000'000'000ull) return;
+ gozLastPollNs_ = now;
+ const std::string list = gozObjectListPath(gozFolder_[0] ? std::string(gozFolder_) : gozDefaultRoot());
+ const long long t = fileTime(list);
+ if (t == 0 || t == gozListTime_) return;
+ gozListTime_ = t;
+ runGozCommand("goz_receive");
+}
+
+} // namespace sf
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index 22da76d6..5fbe391a 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -10,8 +10,11 @@
#include "core/Voxel.h"
#include "io/FbxIO.h"
#include "io/GltfIO.h"
+#include "io/GozCommands.h"
+#include "io/GozIO.h"
#include "io/ObjIO.h"
#include "io/PlyIO.h"
+#include "io/StlIO.h"
#include "io/UsdIO.h"
#include <algorithm>
@@ -106,7 +109,7 @@ CommandRegistry::CommandRegistry() {
}});
add({"open",
- "Open a file: models (.obj, .fbx, .glb, .gltf, .ply, .usda, .usdz) replace the scene; Gaussian splats "
+ "Open a file: models (.obj, .fbx, .glb, .gltf, .ply, .stl, .usda, .usdz, ZBrush .GoZ) replace the scene; Gaussian splats "
"(.ply/.splat captures, KHR_gaussian_splatting .glb, USD ParticleField) load as a reference next to the sculpt. "
"glTF morph targets and FBX/USD blend shapes become sculpt layers.",
{{"path", T::String, "File path (UTF-8).", true}},
@@ -116,11 +119,15 @@ CommandRegistry::CommandRegistry() {
Mesh m;
SplatCloud splats;
std::string err;
+ GozInfo goz;
bool ok;
if (ext == ".glb" || ext == ".gltf") ok = loadGltf(path, m, err, &splats);
else if (ext == ".usda" || ext == ".usd" || ext == ".usdz") ok = loadUsd(path, m, splats, err);
else if (ext == ".splat") ok = loadDotSplat(path, splats, err);
else if (ext == ".fbx") ok = loadFbx(path, m, err);
+ else if (ext == ".goz") ok = loadGoz(path, m, err, &goz);
+ else if (ext == ".stl") ok = loadStl(path, m, err);
+ else if (ext == ".ztl" || ext == ".zpr" || ext == ".zbr") return {false, zbrushProprietaryMessage(ext)};
else if (ext == ".ply") {
PlyContent content;
ok = loadPly(path, m, splats, content, err);
@@ -130,6 +137,7 @@ CommandRegistry::CommandRegistry() {
if (m.triangleCount()) {
doc.setMesh(std::move(m));
doc.path = ext == ".obj" ? path : std::string(); // other formats are exported explicitly
+ if (ext == ".goz") doc.gozName = goz.name;
msg += " (" + std::to_string(doc.mesh.triangleCount()) + " triangles" +
(doc.mesh.layers.empty() ? "" : ", " + std::to_string(doc.mesh.layers.size()) + " layers") + ")";
}
@@ -596,6 +604,8 @@ CommandRegistry::CommandRegistry() {
<< b.max.y << ", " << b.max.z << ")";
return {true, s.str()};
}});
+
+ registerGozCommands(*this); // goz_import/export/send/receive, export_stl (io/GozCommands.cpp)
}
void CommandRegistry::add(Command cmd) { commands_.push_back(std::move(cmd)); }
diff --git a/src/core/Document.cpp b/src/core/Document.cpp
index 02feb890..5ccd910a 100644
--- a/src/core/Document.cpp
+++ b/src/core/Document.cpp
@@ -15,6 +15,7 @@ void Document::setMesh(Mesh m) {
modified = false;
activeLayer = -1;
bvhDirty = false;
+ gozName.clear();
}
int Document::addBrush(BrushRecipe recipe) {
diff --git a/src/core/Document.h b/src/core/Document.h
index 1920f1a7..9782976d 100644
--- a/src/core/Document.h
+++ b/src/core/Document.h
@@ -35,6 +35,8 @@ struct Document {
uint64_t splatsVersion = 0; // bump after editing `splats` so views re-upload
void splatsChanged() { ++splatsVersion; }
bool bvhDirty = false; // set after whole-mesh deformations (e.g. layer weights)
+ // SubTool name of a mesh that came from ZBrush (GoZ), so sending it back updates that SubTool.
+ std::string gozName;
void syncBvh() {
if (bvhDirty) bvh.build(mesh);
diff --git a/src/io/GozCommands.cpp b/src/io/GozCommands.cpp
new file mode 100644
index 00000000..fbb47828
--- /dev/null
+++ b/src/io/GozCommands.cpp
@@ -0,0 +1,122 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "io/GozCommands.h"
+
+#include "io/GozIO.h"
+#include "io/StlIO.h"
+
+#include <filesystem>
+
+namespace sf {
+
+namespace {
+
+std::string fileStem(const std::string& path) {
+ auto stem = std::filesystem::path(std::u8string(path.begin(), path.end())).stem().u8string();
+ return std::string(stem.begin(), stem.end());
+}
+
+std::string meshSummary(const Mesh& m) {
+ std::string s = std::to_string(m.triangleCount()) + " triangles";
+ if (m.hasPolygroups()) s += ", polygroups";
+ if (m.hasUvs()) s += ", UVs";
+ if (m.hasMask()) s += ", mask";
+ if (m.hasColors()) s += ", polypaint";
+ return s;
+}
+
+// The name ZBrush sees: the SubTool the mesh came from, else the document name.
+std::string sendName(const Document& doc, const Args& a) {
+ std::string name = argString(a, "name");
+ if (name.empty()) name = doc.gozName;
+ if (name.empty()) name = doc.assetName();
+ return name;
+}
+
+} // namespace
+
+void registerGozCommands(CommandRegistry& reg) {
+ using T = ParamSpec::Type;
+
+ reg.add({"goz_import",
+ "Open a ZBrush GoZ file (.GoZ), replacing the scene. Polygroups, UVs, mask and polypaint are kept; "
+ "quads are split into triangle pairs (exported back as quads).",
+ {{"path", T::String, "Input .GoZ path (UTF-8).", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const std::string path = argString(a, "path");
+ Mesh m;
+ GozInfo info;
+ std::string err;
+ if (!loadGoz(path, m, err, &info)) return {false, err};
+ doc.setMesh(std::move(m));
+ doc.path.clear();
+ doc.gozName = info.name.empty() ? fileStem(path) : info.name;
+ std::string msg = "Opened GoZ " + doc.gozName + " (" + meshSummary(doc.mesh) + ")";
+ if (!err.empty()) msg += "; " + err;
+ return {true, msg};
+ }});
+
+ reg.add({"goz_export",
+ "Export the mesh as a ZBrush GoZ file (.GoZ) with polygroups, UVs, mask and polypaint.",
+ {{"path", T::String, "Output .GoZ path (UTF-8).", true},
+ {"name", T::String, "SubTool name. Default: the name it came from ZBrush with, else the document name.", false},
+ {"quads", T::Bool, "Rebuild quads from triangle pairs made by GoZ import. Default true.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const std::string path = argString(a, "path");
+ GozWriteOptions o;
+ o.quads = argBool(a, "quads", true);
+ std::string err;
+ const std::string name = argString(a, "name", doc.gozName.empty() ? fileStem(path) : doc.gozName);
+ if (!saveGoz(path, doc.mesh, name, err, o)) return {false, err};
+ return {true, "Exported " + path};
+ }});
+
+ reg.add({"goz_send",
+ "Send the mesh to ZBrush through the GoZ bridge (Windows/macOS): writes it to the shared GoZ folder, "
+ "lists it in GoZ_ObjectList.txt and notifies or starts ZBrush. Sending a mesh received from ZBrush "
+ "updates that SubTool.",
+ {{"name", T::String, "SubTool name. Default: the name it came from ZBrush with, else the document name.", false},
+ {"folder", T::String, "GoZ root folder (contains GoZBrush/ and GoZProjects/). Default: the public Pixologic folder.", false},
+ {"launch", T::Bool, "Notify or start ZBrush. Default true.", false},
+ {"zbrush", T::String, "ZBrush executable to start if GoZ's notifier is missing (optional).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ GozSendOptions o;
+ o.root = argString(a, "folder");
+ o.name = sendName(doc, a);
+ o.launch = argBool(a, "launch", true);
+ o.zbrushPath = argString(a, "zbrush");
+ std::string msg;
+ const bool ok = gozSend(doc.mesh, o, msg);
+ if (ok) doc.gozName = gozObjectName(o.name);
+ return {ok, msg};
+ }});
+
+ reg.add({"goz_receive",
+ "Receive what ZBrush last sent with GoZ (the objects in GoZ_ObjectList.txt), replacing the mesh as an "
+ "undoable step. Several SubTools are merged into one mesh.",
+ {{"folder", T::String, "GoZ root folder. Default: the public Pixologic folder.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Mesh m;
+ std::string msg;
+ std::vector<std::string> names;
+ if (!gozReceive(argString(a, "folder"), m, msg, &names)) return {false, msg};
+ if (doc.mesh.triangleCount()) doc.replaceMeshUndoable(std::move(m), "Receive from ZBrush");
+ else doc.setMesh(std::move(m));
+ doc.path.clear();
+ doc.gozName = names.size() == 1 ? names.front() : std::string();
+ doc.modified = true;
+ return {true, msg};
+ }});
+
+ reg.add({"export_stl",
+ "Export the mesh as binary STL (for 3D printing).",
+ {{"path", T::String, "Output .stl path (UTF-8).", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const std::string path = argString(a, "path");
+ std::string err;
+ if (!saveStl(path, doc.mesh, err)) return {false, err};
+ return {true, "Exported " + path + " (" + std::to_string(doc.mesh.triangleCount()) + " triangles)"};
+ }});
+}
+
+} // namespace sf
diff --git a/src/io/GozCommands.h b/src/io/GozCommands.h
new file mode 100644
index 00000000..0bca32fd
--- /dev/null
+++ b/src/io/GozCommands.h
@@ -0,0 +1,14 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// ZBrush interoperability commands: goz_import, goz_export, goz_send,
+// goz_receive and export_stl. Registered by CommandRegistry's constructor.
+#pragma once
+
+#include "core/Commands.h"
+
+namespace sf {
+
+void registerGozCommands(CommandRegistry& registry);
+
+} // namespace sf
diff --git a/src/io/GozIO.cpp b/src/io/GozIO.cpp
new file mode 100644
index 00000000..db86c1cb
--- /dev/null
+++ b/src/io/GozIO.cpp
@@ -0,0 +1,670 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// GoZ reader/writer and bridge. The format notes come from GoB, the GPL
+// Blender add-on (github.com/JoseConseco/GoB: gob_import.py, gob_export.py,
+// paths.py); docs/goz.md describes the layout.
+#include "io/GozIO.h"
+
+#include <algorithm>
+#include <cctype>
+#include <cmath>
+#include <cstdlib>
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+#include <sstream>
+
+namespace sf {
+
+namespace {
+
+namespace fs = std::filesystem;
+
+fs::path utf8Path(const std::string& s) { return fs::path(std::u8string(s.begin(), s.end())); }
+std::string pathUtf8(const fs::path& p) {
+ auto u = p.u8string();
+ return std::string(u.begin(), u.end());
+}
+// GoZ text files use forward slashes on every platform (GoB writes them that way).
+std::string genericUtf8(const fs::path& p) {
+ auto u = p.generic_u8string();
+ return std::string(u.begin(), u.end());
+}
+
+// Section tags (little-endian uint32 values as GoB writes them).
+constexpr uint32_t kTagMeshName = 0x1389;
+constexpr uint32_t kTagSubdivision = 0x138a;
+constexpr uint32_t kTagVertices = 0x2711;
+constexpr uint32_t kTagFaces = 0x4e21;
+constexpr uint32_t kTagUvs = 0x61a9;
+constexpr uint32_t kTagMask = 0x7532;
+constexpr uint32_t kTagPolypaint = 0x88b9;
+constexpr uint32_t kTagPolygroups = 0x9c41;
+constexpr uint32_t kTagDiffuseMap = 0xafc9;
+constexpr uint32_t kTagNormalMap = 0xc351;
+constexpr uint32_t kTagDisplacementMap = 0xd6d9;
+constexpr uint32_t kNoIndex = 0xffffffffu;
+
+const char kHeader[] = "GoZb 1.0 ZBrush GoZ Binary";
+constexpr size_t kHeaderSize = 36; // the text, six '.' and the uint32 1 that tags the name record
+constexpr char kNamePrefix[] = "GoZMesh_";
+
+// ZBrush is Y-down; SculptForge (like OpenGL/glTF) is Y-up. GoB maps GoZ
+// (x, y, z) to Blender (x, z, -y); in Y-up terms that is (x, -y, -z), a
+// rotation (its own inverse) that keeps the winding.
+glm::vec3 fromZBrush(const glm::vec3& p) { return {p.x, -p.y, -p.z}; }
+glm::vec3 toZBrush(const glm::vec3& p) { return {p.x, -p.y, -p.z}; }
+
+class Reader {
+public:
+ explicit Reader(std::span<const uint8_t> d) : data_(d) {}
+ size_t pos() const { return pos_; }
+ size_t remaining() const { return data_.size() - pos_; }
+ void seek(size_t p) { pos_ = std::min(p, data_.size()); }
+ bool u32(uint32_t& v) {
+ if (remaining() < 4) return false;
+ v = uint32_t(data_[pos_]) | uint32_t(data_[pos_ + 1]) << 8 | uint32_t(data_[pos_ + 2]) << 16 |
+ uint32_t(data_[pos_ + 3]) << 24;
+ pos_ += 4;
+ return true;
+ }
+ bool u64(uint64_t& v) {
+ uint32_t lo, hi;
+ if (remaining() < 8 || !u32(lo) || !u32(hi)) return false;
+ v = uint64_t(lo) | uint64_t(hi) << 32;
+ return true;
+ }
+ const uint8_t* at(size_t p) const { return data_.data() + p; }
+
+private:
+ std::span<const uint8_t> data_;
+ size_t pos_ = 0;
+};
+
+uint32_t readU32(const uint8_t* p) {
+ return uint32_t(p[0]) | uint32_t(p[1]) << 8 | uint32_t(p[2]) << 16 | uint32_t(p[3]) << 24;
+}
+uint16_t readU16(const uint8_t* p) { return uint16_t(p[0] | p[1] << 8); }
+float readF32(const uint8_t* p) {
+ uint32_t bits = readU32(p);
+ float f;
+ std::memcpy(&f, &bits, 4);
+ return f;
+}
+
+class Writer {
+public:
+ std::vector<uint8_t> bytes;
+ void u8(uint8_t v) { bytes.push_back(v); }
+ void u16(uint16_t v) {
+ bytes.push_back(uint8_t(v & 0xff));
+ bytes.push_back(uint8_t(v >> 8));
+ }
+ void u32(uint32_t v) {
+ for (int i = 0; i < 4; ++i) bytes.push_back(uint8_t(v >> (8 * i)));
+ }
+ void u64(uint64_t v) {
+ u32(uint32_t(v & 0xffffffffu));
+ u32(uint32_t(v >> 32));
+ }
+ void f32(float f) {
+ uint32_t bits;
+ std::memcpy(&bits, &f, 4);
+ u32(bits);
+ }
+ void raw(const void* p, size_t n) {
+ auto* b = static_cast<const uint8_t*>(p);
+ bytes.insert(bytes.end(), b, b + n);
+ }
+ // Section header: tag, total length (tag + length + count + payload), element count.
+ void section(uint32_t tag, size_t payloadBytes, uint64_t count) {
+ u32(tag);
+ u32(uint32_t(payloadBytes + 16));
+ u64(count);
+ }
+};
+
+// A GoZ face: 4 indices, the fourth kNoIndex for triangles.
+struct Face {
+ uint32_t v[4];
+ bool quad() const { return v[3] != kNoIndex; }
+};
+
+std::string printable(const uint8_t* p, size_t n) {
+ std::string s;
+ for (size_t i = 0; i < n; ++i)
+ if (p[i] >= 0x20 && p[i] < 0x7f) s += char(p[i]);
+ while (!s.empty() && s.back() == ' ') s.pop_back();
+ return s;
+}
+
+} // namespace
+
+std::string gozObjectName(const std::string& name) {
+ std::string out;
+ for (char c : name) {
+ const bool ok = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' || c == '-';
+ if (ok) out += c;
+ else if (out.empty() || out.back() != '_') out += '_';
+ }
+ while (!out.empty() && (out.front() == '_' || out.front() == '-')) out.erase(out.begin());
+ while (!out.empty() && (out.back() == '_' || out.back() == '-')) out.pop_back();
+ return out.empty() ? "Object" : out;
+}
+
+bool parseGoz(std::span<const uint8_t> data, Mesh& out, std::string& error, GozInfo* info) {
+ GozInfo local;
+ GozInfo& gi = info ? *info : local;
+ gi = GozInfo{};
+ if (data.size() < kHeaderSize + 4 || std::memcmp(data.data(), "GoZb", 4) != 0) {
+ error = "Not a GoZ file (missing \"GoZb\" header)";
+ return false;
+ }
+ Reader r(data);
+ r.seek(kHeaderSize);
+ // Object name record: length (counted from the tag at offset 32), uint64 1, "GoZMesh_<name>".
+ uint32_t nameLen = 0;
+ if (!r.u32(nameLen) || nameLen < 16 || nameLen - 8 > r.remaining()) {
+ error = "GoZ file has a truncated object name";
+ return false;
+ }
+ {
+ const size_t start = r.pos();
+ const size_t n = nameLen - 8;
+ if (n >= 8 + 8 && std::memcmp(r.at(start + 8), kNamePrefix, 8) == 0)
+ gi.name = printable(r.at(start + 16), n - 16);
+ r.seek(start + n);
+ }
+
+ std::vector<glm::vec3> positions;
+ std::vector<Face> faces;
+ std::vector<glm::vec2> faceUvs; // 4 per face
+ std::vector<uint16_t> groups;
+ std::vector<float> mask;
+ std::vector<glm::vec3> colors;
+
+ uint32_t tag = 0;
+ while (r.u32(tag) && tag != 0) {
+ uint32_t length = 0;
+ if (!r.u32(length) || length < 8) break;
+ const size_t bodyStart = r.pos();
+ const size_t bodyLen = std::min<size_t>(length - 8, r.remaining());
+ const size_t next = bodyStart + bodyLen;
+ // Element sections: uint64 count then a payload of length - 16 bytes.
+ uint64_t count = 0;
+ const bool counted = bodyLen >= 8 && r.u64(count);
+ const uint8_t* payload = counted ? r.at(bodyStart + 8) : nullptr;
+ const size_t payloadLen = counted ? bodyLen - 8 : 0;
+ auto records = [&](size_t recordSize) { return size_t(std::min<uint64_t>(count, payloadLen / recordSize)); };
+
+ switch (tag) {
+ case kTagVertices: {
+ const size_t n = records(12);
+ for (size_t i = 0; i < n; ++i) {
+ const uint8_t* p = payload + i * 12;
+ positions.push_back(fromZBrush({readF32(p), readF32(p + 4), readF32(p + 8)}));
+ }
+ break;
+ }
+ case kTagFaces: {
+ const size_t n = records(16);
+ for (size_t i = 0; i < n; ++i) {
+ Face f;
+ for (int c = 0; c < 4; ++c) f.v[c] = readU32(payload + i * 16 + size_t(c) * 4);
+ faces.push_back(f);
+ }
+ break;
+ }
+ case kTagUvs: {
+ const size_t n = records(32);
+ for (size_t i = 0; i < n * 4; ++i) {
+ const uint8_t* p = payload + i * 8;
+ // GoZ stores V downwards (GoB flips it by default both ways).
+ faceUvs.push_back({readF32(p), 1.0f - readF32(p + 4)});
+ }
+ break;
+ }
+ case kTagPolypaint: {
+ const size_t n = records(4);
+ for (size_t i = 0; i < n; ++i) {
+ const uint8_t* p = payload + i * 4; // B, G, R, (alpha/unused), sRGB
+ colors.push_back(srgbToLinear(glm::vec3(p[2], p[1], p[0]) / 255.0f));
+ }
+ break;
+ }
+ case kTagMask: {
+ const size_t n = records(2);
+ for (size_t i = 0; i < n; ++i) mask.push_back(1.0f - float(readU16(payload + i * 2)) / 65535.0f);
+ break;
+ }
+ case kTagPolygroups: {
+ const size_t n = records(2);
+ for (size_t i = 0; i < n; ++i) groups.push_back(readU16(payload + i * 2));
+ break;
+ }
+ case kTagSubdivision:
+ if (records(16) > 0) gi.subdivisionLevel = int(readU32(payload + (records(16) - 1) * 16));
+ break;
+ case kTagDiffuseMap:
+ case kTagNormalMap:
+ case kTagDisplacementMap: {
+ std::string p = counted ? std::string(reinterpret_cast<const char*>(payload), payloadLen) : std::string();
+ while (!p.empty() && p.back() == '\0') p.pop_back();
+ (tag == kTagDiffuseMap ? gi.diffuseMap : tag == kTagNormalMap ? gi.normalMap : gi.displacementMap) = p;
+ break;
+ }
+ default: break; // kTagMeshName and unknown sections are skipped
+ }
+ r.seek(next);
+ }
+
+ if (positions.empty() || faces.empty()) {
+ error = "GoZ file has no " + std::string(positions.empty() ? "vertices" : "faces");
+ return false;
+ }
+
+ // Triangulate: quad (a,b,c,d) -> (a,b,c), (a,c,d). Faces with bad
+ // indices and degenerate triangles are dropped.
+ Mesh m;
+ m.positions = std::move(positions);
+ const uint32_t nv = uint32_t(m.positions.size());
+ const bool haveUvs = faceUvs.size() == faces.size() * 4;
+ const bool haveGroups = groups.size() == faces.size();
+ size_t skipped = 0;
+ for (size_t fi = 0; fi < faces.size(); ++fi) {
+ const Face& f = faces[fi];
+ const bool quad = f.quad();
+ const int corners = quad ? 4 : 3;
+ bool valid = true;
+ for (int c = 0; c < corners; ++c) valid = valid && f.v[c] < nv;
+ if (!valid) {
+ ++skipped;
+ continue;
+ }
+ if (quad) ++gi.quads;
+ else ++gi.triangles;
+ const int tris[2][3] = {{0, 1, 2}, {0, 2, 3}};
+ for (int t = 0; t < (quad ? 2 : 1); ++t) {
+ glm::uvec3 tri(f.v[tris[t][0]], f.v[tris[t][1]], f.v[tris[t][2]]);
+ if (tri.x == tri.y || tri.y == tri.z || tri.x == tri.z) continue;
+ m.triangles.push_back(tri);
+ if (haveGroups) m.polygroups.push_back(groups[fi]);
+ if (haveUvs)
+ for (int c = 0; c < 3; ++c) m.uvs.push_back(faceUvs[fi * 4 + size_t(tris[t][c])]);
+ }
+ }
+ if (m.triangles.empty()) {
+ error = "GoZ file has no valid faces";
+ return false;
+ }
+ if (mask.size() == nv && std::any_of(mask.begin(), mask.end(), [](float v) { return v > 0.0f; }))
+ m.mask = std::move(mask);
+ if (colors.size() == nv) m.colors = std::move(colors);
+ m.rebuildTopology();
+ m.recomputeAllNormals();
+ if (skipped) error = std::to_string(skipped) + " GoZ faces with out-of-range indices were skipped";
+ out = std::move(m);
+ return true;
+}
+
+std::vector<uint8_t> writeGoz(const Mesh& mesh, const std::string& name, const GozWriteOptions& options) {
+ const std::string objName = gozObjectName(name);
+ const size_t nv = mesh.vertexCount(), nt = mesh.triangleCount();
+ const bool uvs = mesh.uvs.size() == nt * 3;
+ const bool groups = mesh.polygroups.size() == nt;
+
+ // Faces (and their 4 UV corners), re-pairing quads split as (a,b,c),(a,c,d).
+ std::vector<Face> faces;
+ std::vector<glm::vec2> faceUvs;
+ std::vector<uint16_t> faceGroups;
+ faces.reserve(nt);
+ for (size_t t = 0; t < nt; ++t) {
+ const glm::uvec3& a = mesh.triangles[t];
+ const glm::vec2* ua = uvs ? &mesh.uvs[t * 3] : nullptr;
+ bool paired = false;
+ if (options.quads && t + 1 < nt) {
+ const glm::uvec3& b = mesh.triangles[t + 1];
+ const glm::vec2* ub = uvs ? &mesh.uvs[(t + 1) * 3] : nullptr;
+ paired = b.x == a.x && b.y == a.z && b.z != a.y && b.z != a.x && b.z != a.z &&
+ (!groups || mesh.polygroups[t] == mesh.polygroups[t + 1]) &&
+ (!uvs || (ub[0] == ua[0] && ub[1] == ua[2]));
+ if (paired) {
+ faces.push_back({{a.x, a.y, a.z, b.z}});
+ if (uvs) faceUvs.insert(faceUvs.end(), {ua[0], ua[1], ua[2], ub[2]});
+ }
+ }
+ if (!paired) {
+ faces.push_back({{a.x, a.y, a.z, kNoIndex}});
+ if (uvs) faceUvs.insert(faceUvs.end(), {ua[0], ua[1], ua[2], glm::vec2(0.0f, 0.0f)}); // GoB pads with (0, 1) in GoZ space
+ }
+ if (groups) faceGroups.push_back(uint16_t(mesh.polygroups[t] & 0xffffu));
+ if (paired) ++t;
+ }
+
+ Writer w;
+ w.raw(kHeader, sizeof(kHeader) - 1);
+ w.raw("......", 6);
+ w.u32(1);
+ w.u32(uint32_t(objName.size() + 24));
+ w.u64(1);
+ w.raw(kNamePrefix, 8);
+ w.raw(objName.data(), objName.size());
+ // Mesh name record exactly as GoB writes it.
+ w.u32(kTagMeshName);
+ w.u32(20);
+ w.u64(1);
+ w.u32(0);
+
+ w.section(kTagVertices, nv * 12, nv);
+ for (const auto& p : mesh.positions) {
+ glm::vec3 z = toZBrush(p);
+ w.f32(z.x);
+ w.f32(z.y);
+ w.f32(z.z);
+ }
+ w.section(kTagFaces, faces.size() * 16, faces.size());
+ for (const Face& f : faces)
+ for (uint32_t v : f.v) w.u32(v);
+ if (uvs) {
+ w.section(kTagUvs, faces.size() * 32, faces.size());
+ for (const auto& uv : faceUvs) {
+ w.f32(uv.x);
+ w.f32(1.0f - uv.y);
+ }
+ }
+ if (mesh.colors.size() == nv) {
+ // GoB writes the count as uint32 + float 0 (same 8 bytes as a uint64).
+ w.section(kTagPolypaint, nv * 4, nv);
+ for (const auto& c : mesh.colors) {
+ glm::vec3 s = glm::clamp(linearToSrgb(c), 0.0f, 1.0f) * 255.0f + 0.5f;
+ w.u8(uint8_t(s.z));
+ w.u8(uint8_t(s.y));
+ w.u8(uint8_t(s.x));
+ w.u8(0);
+ }
+ }
+ if (mesh.mask.size() == nv) {
+ w.section(kTagMask, nv * 2, nv);
+ for (float m : mesh.mask) w.u16(uint16_t((1.0f - std::clamp(m, 0.0f, 1.0f)) * 65535.0f + 0.5f));
+ }
+ if (groups) {
+ w.section(kTagPolygroups, faceGroups.size() * 2, faceGroups.size());
+ for (uint16_t g : faceGroups) w.u16(g);
+ }
+ // End: 16 zero bytes (a zero tag).
+ for (int i = 0; i < 16; ++i) w.u8(0);
+ return std::move(w.bytes);
+}
+
+bool loadGoz(const std::string& path, Mesh& out, std::string& error, GozInfo* info) {
+ std::ifstream f(utf8Path(path), std::ios::binary);
+ if (!f) {
+ error = "Cannot open " + path;
+ return false;
+ }
+ std::vector<uint8_t> data((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
+ std::string err;
+ if (!parseGoz(data, out, err, info)) {
+ error = err + ": " + path;
+ return false;
+ }
+ error = err; // warnings, if any
+ return true;
+}
+
+bool saveGoz(const std::string& path, const Mesh& mesh, const std::string& name, std::string& error,
+ const GozWriteOptions& options) {
+ if (mesh.triangleCount() == 0) {
+ error = "Nothing to export: the mesh is empty";
+ return false;
+ }
+ std::vector<uint8_t> bytes = writeGoz(mesh, name, options);
+ std::ofstream f(utf8Path(path), std::ios::binary);
+ if (!f || !f.write(reinterpret_cast<const char*>(bytes.data()), std::streamsize(bytes.size()))) {
+ error = "Cannot write " + path;
+ return false;
+ }
+ return true;
+}
+
+// ---------------------------------------------------------------------------
+// Bridge
+// ---------------------------------------------------------------------------
+
+namespace {
+
+std::string g_appPath;
+
+#ifdef _WIN32
+std::string envUtf8(const wchar_t* name) {
+ wchar_t* value = nullptr;
+ size_t len = 0;
+ if (_wdupenv_s(&value, &len, name) != 0 || !value) return {};
+ std::string s = pathUtf8(fs::path(value));
+ std::free(value);
+ return s;
+}
+#endif
+
+bool writeText(const fs::path& p, const std::string& text) {
+ std::ofstream f(p, std::ios::binary);
+ return f && f.write(text.data(), std::streamsize(text.size()));
+}
+
+#if defined(_WIN32) || defined(__APPLE__)
+bool launchDetached(const std::string& target) {
+#ifdef _WIN32
+ const std::string cmd = "start \"\" \"" + target + "\"";
+#else
+ const std::string cmd = "open \"" + target + "\"";
+#endif
+ return std::system(cmd.c_str()) == 0;
+}
+
+// Newest ZBrush in the default install locations (GoB's find_zbrush).
+std::string findZBrush() {
+ std::error_code ec;
+#ifdef _WIN32
+ const fs::path bases[] = {"C:\\Program Files", "C:\\Program Files\\Pixologic", "C:\\Program Files\\Maxon"};
+ const char* exe = "ZBrush.exe";
+#else
+ const fs::path bases[] = {"/Applications"};
+ const char* exe = "ZBrush.app";
+#endif
+ std::vector<fs::path> found;
+ for (const auto& base : bases) {
+ if (!fs::is_directory(base, ec)) continue;
+ for (const auto& entry : fs::directory_iterator(base, ec)) {
+ std::string n = pathUtf8(entry.path().filename());
+ std::transform(n.begin(), n.end(), n.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+ if (n.find("zbrush") == std::string::npos) continue;
+ if (n == "zbrush.app") found.push_back(entry.path());
+ else if (fs::exists(entry.path() / exe, ec)) found.push_back(entry.path() / exe);
+ }
+ }
+ if (found.empty()) return {};
+ std::sort(found.begin(), found.end()); // version numbers sort last-is-newest, like GoB's max()
+ return pathUtf8(found.back());
+}
+#endif
+
+} // namespace
+
+std::string gozDefaultRoot() {
+#ifdef _WIN32
+ std::string pub = envUtf8(L"PUBLIC");
+ if (pub.empty()) pub = "C:\\Users\\Public";
+ return pathUtf8(utf8Path(pub) / "Pixologic");
+#elif defined(__APPLE__)
+ return "/Users/Shared/Pixologic";
+#else
+ return {};
+#endif
+}
+
+std::string gozUnavailableMessage() {
+ return "The ZBrush bridge (GoZ) needs ZBrush, which runs only on Windows and macOS. Use Export GoZ / Import GoZ "
+ "to move .GoZ files by hand, or set a GoZ folder (e.g. a Wine prefix's Users/Public/Pixologic).";
+}
+
+void setGozApplicationPath(std::string executable) { g_appPath = std::move(executable); }
+
+std::string gozObjectListPath(const std::string& root) {
+ return root.empty() ? std::string() : pathUtf8(utf8Path(root) / "GoZBrush" / "GoZ_ObjectList.txt");
+}
+
+bool gozSend(const Mesh& mesh, const GozSendOptions& o, std::string& message) {
+ const std::string root = o.root.empty() ? gozDefaultRoot() : o.root;
+ if (root.empty()) {
+ message = gozUnavailableMessage();
+ return false;
+ }
+ if (mesh.triangleCount() == 0) {
+ message = "Nothing to send: the mesh is empty";
+ return false;
+ }
+ std::error_code ec;
+ const fs::path rootPath = utf8Path(root);
+ const fs::path brush = rootPath / "GoZBrush";
+ const fs::path project = rootPath / "GoZProjects" / "Default";
+ const fs::path app = rootPath / "GoZApps" / "SculptForge";
+ for (const auto& d : {brush, project, app}) fs::create_directories(d, ec);
+ if (!fs::is_directory(project, ec)) {
+ message = "Cannot create the GoZ folder " + pathUtf8(project);
+ return false;
+ }
+ const std::string name = gozObjectName(o.name.empty() ? "SculptForge" : o.name);
+ // Object paths are written without the .GoZ extension, ZBrush appends it.
+ const std::string base = genericUtf8(project / name);
+ std::string err;
+ if (!saveGoz(pathUtf8(project / (name + ".GoZ")), mesh, name, err)) {
+ message = err;
+ return false;
+ }
+ bool ok = writeText(project / (name + ".ztn"), base) && writeText(brush / "GoZ_ObjectList.txt", base + "\n") &&
+ writeText(brush / "GoZ_Application.txt", "SculptForge") &&
+ writeText(brush / "GoZ_ProjectPath.txt", genericUtf8(project) + "/");
+ // Register SculptForge in ZBrush's GoZ application list.
+ if (!fs::exists(app / "GoZ_Info.txt", ec))
+ ok = ok && writeText(app / "GoZ_Info.txt",
+ "NAME\t\t\t=\t\"SculptForge\"\nGOZ_VERSION\t\t=\t1\nEXTENSION\t\t=\t\".GoZ\"\n"
+ "TAMPLATE\t\t=\t\"GoZ Complete Binary.GoZ\"\n\nEXPORT_FLIP_Y\t\t\t=\tFALSE\n"
+ "EXPORT_FLIP_Z\t\t\t=\tFALSE\nIMPORT_FLIP_Y\t\t\t=\tFALSE\nIMPORT_FLIP_Z\t\t\t=\tFALSE\n");
+ if (!g_appPath.empty())
+ ok = ok && writeText(app / "GoZ_Config.txt", "PATH = \"" + genericUtf8(utf8Path(g_appPath)) + "\"");
+ if (!ok) {
+ message = "Cannot write the GoZ bridge files in " + root;
+ return false;
+ }
+ message = "Sent " + name + " to " + pathUtf8(project);
+ if (!o.launch) return true;
+
+ // Official GoZ plug-ins notify a running ZBrush with GoZBrushFromApp; GoB
+ // starts ZBrush itself. Do the first, fall back to the second.
+#ifdef _WIN32
+ const fs::path notifier = brush / "GoZBrushFromApp.exe";
+#else
+ const fs::path notifier = brush / "GoZBrushFromApp.app";
+#endif
+#if defined(_WIN32) || defined(__APPLE__)
+ if (fs::exists(notifier, ec)) {
+ launchDetached(pathUtf8(notifier));
+ message += "; ZBrush notified";
+ return true;
+ }
+ const std::string zbrush = o.zbrushPath.empty() ? findZBrush() : o.zbrushPath;
+ if (!zbrush.empty() && launchDetached(zbrush)) {
+ message += "; started " + zbrush + " (use GoZ in ZBrush to import it)";
+ return true;
+ }
+ message += "; ZBrush was not found (install GoZ from ZBrush's Preferences > GoZ, then press GoZ in ZBrush)";
+#else
+ (void)notifier;
+ message += "; " + gozUnavailableMessage();
+#endif
+ return true;
+}
+
+namespace {
+
+// Appends one attribute; a side that lacks it gets `fill` (`dn`, `sn` = element counts).
+template <class T>
+void appendAttribute(std::vector<T>& d, size_t dn, const std::vector<T>& s, size_t sn, const T& fill) {
+ if (d.empty() && s.empty()) return;
+ d.resize(dn, fill);
+ if (s.empty()) d.resize(dn + sn, fill);
+ else d.insert(d.end(), s.begin(), s.end());
+}
+
+// Appends `src` to `dst`, filling attributes the other side lacks with defaults.
+void appendMesh(Mesh& dst, const Mesh& src) {
+ const uint32_t off = uint32_t(dst.vertexCount());
+ const size_t dv = dst.vertexCount(), dt = dst.triangleCount();
+ const size_t sv = src.vertexCount(), st = src.triangleCount();
+ dst.positions.insert(dst.positions.end(), src.positions.begin(), src.positions.end());
+ for (const auto& t : src.triangles) dst.triangles.push_back(t + glm::uvec3(off));
+ appendAttribute(dst.mask, dv, src.mask, sv, 0.0f);
+ appendAttribute(dst.colors, dv, src.colors, sv, glm::vec3(1.0f));
+ appendAttribute(dst.polygroups, dt, src.polygroups, st, 0u);
+ appendAttribute(dst.uvs, dt * 3, src.uvs, st * 3, glm::vec2(0.0f));
+}
+
+} // namespace
+
+bool gozReceive(const std::string& rootIn, Mesh& out, std::string& message, std::vector<std::string>* names) {
+ const std::string root = rootIn.empty() ? gozDefaultRoot() : rootIn;
+ if (root.empty()) {
+ message = gozUnavailableMessage();
+ return false;
+ }
+ std::ifstream list(utf8Path(gozObjectListPath(root)), std::ios::binary);
+ if (!list) {
+ message = "Nothing to receive: " + gozObjectListPath(root) + " does not exist (press GoZ in ZBrush first)";
+ return false;
+ }
+ Mesh merged;
+ std::vector<std::string> loaded;
+ std::string line, problems;
+ while (std::getline(list, line)) {
+ while (!line.empty() && (line.back() == '\r' || line.back() == ' ' || line.back() == '\0')) line.pop_back();
+ if (line.empty()) continue;
+ std::string path = line;
+ std::string lower = path;
+ std::transform(lower.begin(), lower.end(), lower.begin(), [](unsigned char c) { return char(std::tolower(c)); });
+ if (lower.size() < 4 || lower.compare(lower.size() - 4, 4, ".goz") != 0) path += ".GoZ";
+ Mesh m;
+ GozInfo info;
+ std::string err;
+ if (!loadGoz(path, m, err, &info)) {
+ problems += (problems.empty() ? "" : "; ") + err;
+ continue;
+ }
+ loaded.push_back(info.name.empty() ? pathUtf8(utf8Path(path).stem()) : info.name);
+ appendMesh(merged, m);
+ }
+ if (loaded.empty()) {
+ message = problems.empty() ? "Nothing to receive: GoZ_ObjectList.txt is empty" : problems;
+ return false;
+ }
+ merged.rebuildTopology();
+ merged.recomputeAllNormals();
+ out = std::move(merged);
+ message = "Received " + loaded.front();
+ if (loaded.size() > 1) message += " and " + std::to_string(loaded.size() - 1) + " more SubTools (merged)";
+ message += " from ZBrush (" + std::to_string(out.triangleCount()) + " triangles)";
+ if (!problems.empty()) message += "; skipped: " + problems;
+ if (names) *names = std::move(loaded);
+ return true;
+}
+
+std::string zbrushProprietaryMessage(const std::string& extension) {
+ std::string ext = extension;
+ std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return char(std::toupper(c)); });
+ return ext + " is ZBrush's proprietary format and cannot be read. In ZBrush, send the model with GoZ "
+ "(File > ZBrush (GoZ) > Receive from ZBrush) or export it as OBJ or FBX "
+ "(Tool > Export / the FBX ExportImport plug-in) and open that instead.";
+}
+
+} // namespace sf
diff --git a/src/io/GozIO.h b/src/io/GozIO.h
new file mode 100644
index 00000000..71422b04
--- /dev/null
+++ b/src/io/GozIO.h
@@ -0,0 +1,82 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// GoZ: ZBrush's bridge format (.GoZ binary meshes plus a shared "GoZ folder"
+// with an object list). The binary layout follows the open-source
+// Blender add-on GoB (github.com/JoseConseco/GoB, GPL); see docs/goz.md.
+//
+// .GoZ carries positions, tri/quad faces, per-face-corner UVs, polygroups,
+// mask and polypaint. Quads are triangulated on import as (a,b,c) + (a,c,d)
+// in consecutive triangles, and export pairs such triangles back into quads.
+// ZBrush's own .ZTL/.ZPR files are proprietary and cannot be read.
+#pragma once
+
+#include "core/Mesh.h"
+
+#include <cstdint>
+#include <span>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+// Extra GoZ information that has no place in Mesh.
+struct GozInfo {
+ std::string name; // object (SubTool) name without the "GoZMesh_" prefix
+ int subdivisionLevel = 0; // as recorded by ZBrush (informational)
+ std::string diffuseMap, displacementMap, normalMap; // texture paths, if any
+ size_t quads = 0, triangles = 0; // GoZ faces read
+};
+
+struct GozWriteOptions {
+ bool quads = true; // pair (a,b,c)+(a,c,d) triangles back into quads
+};
+
+// Parses an in-memory .GoZ file. Positions are converted from ZBrush's
+// Y-down axes to SculptForge's Y-up ones (a 180 degree turn about X).
+bool parseGoz(std::span<const uint8_t> data, Mesh& out, std::string& error, GozInfo* info = nullptr);
+std::vector<uint8_t> writeGoz(const Mesh& mesh, const std::string& name, const GozWriteOptions& options = {});
+
+// Paths are UTF-8.
+bool loadGoz(const std::string& path, Mesh& out, std::string& error, GozInfo* info = nullptr);
+bool saveGoz(const std::string& path, const Mesh& mesh, const std::string& name, std::string& error,
+ const GozWriteOptions& options = {});
+
+// GoZ object names: ASCII letters, digits, '_' and '-' (GoB's escaping).
+std::string gozObjectName(const std::string& name);
+
+// ---------------------------------------------------------------------------
+// The GoZ bridge (ZBrush on Windows and macOS)
+// ---------------------------------------------------------------------------
+
+// The shared GoZ root: %PUBLIC%\Pixologic on Windows, /Users/Shared/Pixologic
+// on macOS, empty elsewhere (ZBrush does not run on Linux).
+std::string gozDefaultRoot();
+// Message for platforms without ZBrush.
+std::string gozUnavailableMessage();
+// Where SculptForge registers itself as a GoZ application (GoZApps/SculptForge/GoZ_Config.txt).
+void setGozApplicationPath(std::string executable);
+
+struct GozSendOptions {
+ std::string root; // GoZ root; empty = gozDefaultRoot()
+ std::string name; // object name; empty = "SculptForge"
+ bool launch = true; // notify ZBrush (GoZBrushFromApp) or start it
+ std::string zbrushPath; // ZBrush executable to start if GoZBrushFromApp is missing (optional)
+};
+
+// Writes the mesh to <root>/GoZProjects/Default/<name>.GoZ, lists it in
+// GoZBrush/GoZ_ObjectList.txt, names SculptForge in GoZ_Application.txt and
+// (optionally) tells ZBrush to import it. `message` describes what happened.
+bool gozSend(const Mesh& mesh, const GozSendOptions& options, std::string& message);
+
+// Reads every object in <root>/GoZBrush/GoZ_ObjectList.txt (what ZBrush last
+// sent) into one mesh. Several SubTools are merged.
+bool gozReceive(const std::string& root, Mesh& out, std::string& message, std::vector<std::string>* names = nullptr);
+
+// Path of the object list ZBrush rewrites on every send (for polling).
+std::string gozObjectListPath(const std::string& root);
+
+// Error text for ZBrush's proprietary files (.ztl, .zpr, .zbr).
+std::string zbrushProprietaryMessage(const std::string& extension);
+
+} // namespace sf
diff --git a/src/io/StlIO.cpp b/src/io/StlIO.cpp
new file mode 100644
index 00000000..fdcc5684
--- /dev/null
+++ b/src/io/StlIO.cpp
@@ -0,0 +1,134 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "io/StlIO.h"
+
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+#include <sstream>
+
+namespace sf {
+
+namespace {
+
+std::filesystem::path utf8Path(const std::string& s) { return std::filesystem::path(std::u8string(s.begin(), s.end())); }
+
+uint32_t readU32(const uint8_t* p) {
+ return uint32_t(p[0]) | uint32_t(p[1]) << 8 | uint32_t(p[2]) << 16 | uint32_t(p[3]) << 24;
+}
+float readF32(const uint8_t* p) {
+ uint32_t bits = readU32(p);
+ float f;
+ std::memcpy(&f, &bits, 4);
+ return f;
+}
+void putU32(std::vector<uint8_t>& out, uint32_t v) {
+ for (int i = 0; i < 4; ++i) out.push_back(uint8_t(v >> (8 * i)));
+}
+void putF32(std::vector<uint8_t>& out, float f) {
+ uint32_t bits;
+ std::memcpy(&bits, &f, 4);
+ putU32(out, bits);
+}
+
+// Turns a triangle soup into a welded mesh.
+bool finish(Mesh& soup, Mesh& out, std::string& error) {
+ for (uint32_t i = 0; i + 2 < soup.positions.size(); i += 3) soup.triangles.push_back({i, i + 1, i + 2});
+ if (soup.triangles.empty()) {
+ error = "STL file has no triangles";
+ return false;
+ }
+ Mesh welded = weldImported(soup);
+ if (welded.triangles.empty()) {
+ error = "STL file has only degenerate triangles";
+ return false;
+ }
+ out = std::move(welded);
+ return true;
+}
+
+} // namespace
+
+bool parseStl(std::span<const uint8_t> data, Mesh& out, std::string& error) {
+ Mesh soup;
+ // Binary: 80-byte header, uint32 count, 50 bytes per triangle. Some
+ // binary files also start with "solid", so the size decides.
+ if (data.size() >= 84) {
+ const uint64_t count = readU32(data.data() + 80);
+ if (84 + count * 50 == data.size()) {
+ soup.positions.reserve(size_t(count) * 3);
+ for (size_t t = 0; t < count; ++t) {
+ const uint8_t* p = data.data() + 84 + t * 50 + 12; // skip the facet normal
+ for (int c = 0; c < 3; ++c, p += 12) soup.positions.push_back({readF32(p), readF32(p + 4), readF32(p + 8)});
+ }
+ return finish(soup, out, error);
+ }
+ }
+ const std::string text(reinterpret_cast<const char*>(data.data()), data.size());
+ if (text.find_first_not_of(" \t\r\n") == std::string::npos || text.compare(text.find_first_not_of(" \t\r\n"), 5, "solid") != 0) {
+ error = "Not an STL file (bad binary size and no \"solid\" header)";
+ return false;
+ }
+ std::istringstream in(text);
+ std::string word;
+ while (in >> word) {
+ if (word != "vertex") continue;
+ glm::vec3 p;
+ if (!(in >> p.x >> p.y >> p.z)) {
+ error = "Malformed vertex in ASCII STL";
+ return false;
+ }
+ soup.positions.push_back(p);
+ }
+ return finish(soup, out, error);
+}
+
+bool loadStl(const std::string& path, Mesh& out, std::string& error) {
+ std::ifstream f(utf8Path(path), std::ios::binary);
+ if (!f) {
+ error = "Cannot open " + path;
+ return false;
+ }
+ std::vector<uint8_t> data((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
+ std::string err;
+ if (!parseStl(data, out, err)) {
+ error = err + ": " + path;
+ return false;
+ }
+ return true;
+}
+
+bool saveStl(const std::string& path, const Mesh& mesh, std::string& error) {
+ if (mesh.triangleCount() == 0) {
+ error = "Nothing to export: the mesh is empty";
+ return false;
+ }
+ std::vector<uint8_t> bytes;
+ bytes.reserve(84 + mesh.triangleCount() * 50);
+ const char header[] = "SculptForge binary STL";
+ bytes.insert(bytes.end(), header, header + sizeof(header) - 1);
+ bytes.resize(80, 0);
+ putU32(bytes, uint32_t(mesh.triangleCount()));
+ for (const auto& t : mesh.triangles) {
+ const glm::vec3 &a = mesh.positions[t.x], &b = mesh.positions[t.y], &c = mesh.positions[t.z];
+ glm::vec3 n = glm::cross(b - a, c - a);
+ const float len = glm::length(n);
+ n = len > 0.0f ? n / len : glm::vec3(0.0f);
+ for (const glm::vec3& v : {n, a, b, c}) {
+ putF32(bytes, v.x);
+ putF32(bytes, v.y);
+ putF32(bytes, v.z);
+ }
+ bytes.push_back(0); // attribute byte count
+ bytes.push_back(0);
+ }
+ std::ofstream f(utf8Path(path), std::ios::binary);
+ if (!f || !f.write(reinterpret_cast<const char*>(bytes.data()), std::streamsize(bytes.size()))) {
+ error = "Cannot write " + path;
+ return false;
+ }
+ return true;
+}
+
+} // namespace sf
diff --git a/src/io/StlIO.h b/src/io/StlIO.h
new file mode 100644
index 00000000..03e63a3f
--- /dev/null
+++ b/src/io/StlIO.h
@@ -0,0 +1,22 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// STL (3D printing): binary and ASCII import, binary export. Positions are
+// kept as stored (no axis or unit conversion).
+#pragma once
+
+#include "core/Mesh.h"
+
+#include <cstdint>
+#include <span>
+#include <string>
+
+namespace sf {
+
+// Coincident corners are welded into a connected mesh.
+bool loadStl(const std::string& path, Mesh& out, std::string& error);
+bool parseStl(std::span<const uint8_t> data, Mesh& out, std::string& error);
+// Writes binary STL (every triangle, including hidden ones). Paths are UTF-8.
+bool saveStl(const std::string& path, const Mesh& mesh, std::string& error);
+
+} // namespace sf
diff --git a/tests/test_goz.cpp b/tests/test_goz.cpp
new file mode 100644
index 00000000..d0704eec
--- /dev/null
+++ b/tests/test_goz.cpp
@@ -0,0 +1,335 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// ZBrush interoperability: GoZ read/write (checked against a buffer laid out
+// exactly like GoB's writer), the GoZ bridge folder, and STL.
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/Primitives.h"
+#include "io/GozIO.h"
+#include "io/StlIO.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+
+using namespace sf;
+
+namespace {
+
+// Byte writer mirroring GoB's struct.pack calls (little-endian).
+struct Bytes {
+ std::vector<uint8_t> b;
+ void u8(uint8_t v) { b.push_back(v); }
+ void raw(const char* s, size_t n) { b.insert(b.end(), s, s + n); }
+ void u16(uint16_t v) {
+ u8(uint8_t(v & 0xff));
+ u8(uint8_t(v >> 8));
+ }
+ void u32(uint32_t v) {
+ for (int i = 0; i < 4; ++i) u8(uint8_t(v >> (8 * i)));
+ }
+ void u64(uint64_t v) {
+ u32(uint32_t(v));
+ u32(uint32_t(v >> 32));
+ }
+ void f32(float f) {
+ uint32_t x;
+ std::memcpy(&x, &f, 4);
+ u32(x);
+ }
+ void tag(uint8_t a, uint8_t c) { u8(a), u8(c), u8(0), u8(0); }
+};
+
+// One quad (0,1,2,3) and one triangle (1,4,2) as GoB's exportGoZ writes them:
+// header, object name, mesh name, vertices, faces, UVs, polypaint, mask,
+// polygroups, 16 zero bytes. Coordinates are in ZBrush space.
+std::vector<uint8_t> gobQuadAndTriangle() {
+ const std::string name = "Quad";
+ Bytes w;
+ w.raw("GoZb 1.0 ZBrush GoZ Binary", 26);
+ for (int i = 0; i < 6; ++i) w.u8(0x2e);
+ w.u32(1);
+ w.u32(uint32_t(name.size() + 24));
+ w.u64(1);
+ w.raw("GoZMesh_", 8);
+ w.raw(name.data(), name.size());
+ w.tag(0x89, 0x13);
+ w.u32(20);
+ w.u64(1);
+ w.u32(0);
+ // Vertices
+ const float verts[5][3] = {{0, 0, 0}, {1, 0, 0}, {1, 1, 0}, {0, 1, 0}, {2, 0.5f, 0.25f}};
+ w.tag(0x11, 0x27);
+ w.u32(5 * 3 * 4 + 16);
+ w.u64(5);
+ for (auto& v : verts)
+ for (float c : v) w.f32(c);
+ // Faces
+ w.tag(0x21, 0x4e);
+ w.u32(2 * 4 * 4 + 16);
+ w.u64(2);
+ for (uint32_t i : {0u, 1u, 2u, 3u}) w.u32(i);
+ for (uint32_t i : {1u, 4u, 2u, 0xffffffffu}) w.u32(i);
+ // UVs: 4 corners per face, V flipped (GoB's default), triangles padded with (0, 1)
+ w.tag(0xa9, 0x61);
+ w.u32(2 * 4 * 2 * 4 + 16);
+ w.u64(2);
+ const float uvs[8][2] = {{0, 1}, {0.5f, 1}, {0.5f, 0.5f}, {0, 0.5f}, {0.5f, 1}, {1, 0.75f}, {0.5f, 0.5f}, {0, 1}};
+ for (auto& uv : uvs) w.f32(uv[0]), w.f32(uv[1]);
+ // Polypaint: count as uint32 + float 0, then B, G, R, 0 per vertex
+ w.tag(0xb9, 0x88);
+ w.u32(5 * 4 + 16);
+ w.u32(5);
+ w.f32(0.0f);
+ const uint8_t rgb[5][3] = {{255, 0, 0}, {0, 255, 0}, {0, 0, 255}, {255, 255, 255}, {128, 64, 32}};
+ for (auto& c : rgb) w.u8(c[2]), w.u8(c[1]), w.u8(c[0]), w.u8(0);
+ // Mask: (1 - mask) * 65535
+ w.tag(0x32, 0x75);
+ w.u32(5 * 2 + 16);
+ w.u64(5);
+ for (uint16_t m : {uint16_t(65535), uint16_t(0), uint16_t(65535), uint16_t(65535), uint16_t(32768)}) w.u16(m);
+ // Polygroups: uint16 per face
+ w.tag(0x41, 0x9c);
+ w.u32(2 * 2 + 16);
+ w.u64(2);
+ w.u16(7);
+ w.u16(65504);
+ for (int i = 0; i < 16; ++i) w.u8(0);
+ return w.b;
+}
+
+void paintAll(Mesh& m) {
+ m.ensureMask();
+ m.ensureColors();
+ for (uint32_t v = 0; v < m.vertexCount(); ++v) {
+ const glm::vec3& p = m.positions[v];
+ m.mask[v] = std::clamp(p.y * 0.5f + 0.5f, 0.0f, 1.0f);
+ m.colors[v] = srgbToLinear(glm::vec3(p.x, p.y, p.z) * 0.5f + 0.5f);
+ }
+ m.ensurePolygroups();
+ m.uvs.resize(m.triangleCount() * 3);
+ for (uint32_t t = 0; t < m.triangleCount(); ++t) {
+ m.polygroups[t] = t % 5 + (t % 2 ? 1000 : 0);
+ for (int c = 0; c < 3; ++c) {
+ const glm::vec3& p = m.positions[m.triangles[t][c]];
+ m.uvs[t * 3 + size_t(c)] = glm::vec2(p.x, p.z) * 0.25f + 0.5f;
+ }
+ }
+}
+
+std::vector<uint8_t> readFile(const std::string& path) {
+ std::ifstream f(path, std::ios::binary);
+ return {std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()};
+}
+
+float maxSrgbError(const Mesh& a, const Mesh& b) {
+ float e = 0.0f;
+ for (size_t v = 0; v < a.colors.size(); ++v) {
+ glm::vec3 d = glm::abs(linearToSrgb(a.colors[v]) - linearToSrgb(b.colors[v]));
+ e = std::max(e, std::max(d.x, std::max(d.y, d.z)));
+ }
+ return e;
+}
+
+} // namespace
+
+TEST(goz_round_trip_keeps_everything) {
+ Mesh m = makeIcosphere(3);
+ paintAll(m);
+ for (bool quads : {true, false}) {
+ GozWriteOptions o;
+ o.quads = quads;
+ std::vector<uint8_t> bytes = writeGoz(m, "My Head!", o);
+ Mesh r;
+ GozInfo info;
+ std::string err;
+ CHECK(parseGoz(bytes, r, err, &info));
+ CHECK(err.empty());
+ CHECK(info.name == "My_Head");
+ CHECK(r.positions == m.positions);
+ CHECK(r.triangles == m.triangles);
+ CHECK(r.polygroups == m.polygroups);
+ CHECK(r.uvs.size() == m.uvs.size());
+ float uvErr = 0.0f, maskErr = 0.0f;
+ for (size_t i = 0; i < m.uvs.size() && i < r.uvs.size(); ++i)
+ uvErr = std::max(uvErr, glm::length(r.uvs[i] - m.uvs[i]));
+ for (size_t v = 0; v < m.mask.size() && v < r.mask.size(); ++v) maskErr = std::max(maskErr, std::abs(r.mask[v] - m.mask[v]));
+ CHECK(uvErr < 1e-6f);
+ CHECK(r.mask.size() == m.mask.size() && maskErr < 1e-4f);
+ CHECK(r.colors.size() == m.colors.size() && maxSrgbError(r, m) <= 0.5f / 255.0f + 1e-4f);
+ CHECK(r.normals.size() == r.positions.size());
+ if (!quads) CHECK(info.quads == 0 && info.triangles == m.triangleCount());
+ }
+ // Writing what was read gives the same bytes.
+ std::vector<uint8_t> first = writeGoz(m, "Head");
+ Mesh r;
+ std::string err;
+ CHECK(parseGoz(first, r, err));
+ CHECK(writeGoz(r, "Head") == first);
+}
+
+TEST(goz_parses_gob_layout) {
+ const std::vector<uint8_t> bytes = gobQuadAndTriangle();
+ Mesh m;
+ GozInfo info;
+ std::string err;
+ CHECK(parseGoz(bytes, m, err, &info));
+ CHECK(info.name == "Quad" && info.quads == 1 && info.triangles == 1);
+ CHECK(m.vertexCount() == 5);
+ // Y-down ZBrush to Y-up: (x, y, z) -> (x, -y, -z).
+ CHECK(m.positions[2] == glm::vec3(1, -1, 0) && m.positions[4] == glm::vec3(2, -0.5f, -0.25f));
+ // The quad becomes (0,1,2) + (0,2,3), then the triangle.
+ CHECK(m.triangleCount() == 3);
+ CHECK(m.triangles[0] == glm::uvec3(0, 1, 2) && m.triangles[1] == glm::uvec3(0, 2, 3) && m.triangles[2] == glm::uvec3(1, 4, 2));
+ CHECK(m.polygroups == std::vector<uint32_t>({7u, 7u, 65504u}));
+ CHECK(m.uvs.size() == 9);
+ CHECK(m.uvs.size() == 9 && m.uvs[0] == glm::vec2(0, 0) && m.uvs[1] == glm::vec2(0.5f, 0) && m.uvs[5] == glm::vec2(0, 0.5f) &&
+ m.uvs[7] == glm::vec2(1, 0.25f));
+ CHECK(m.mask.size() == 5 && m.mask[0] == 0.0f && m.mask[1] == 1.0f && std::abs(m.mask[4] - 0.5f) < 1e-4f);
+ CHECK(m.colors.size() == 5);
+ CHECK(m.colors.size() == 5 && m.colors[0] == glm::vec3(1, 0, 0) && m.colors[1] == glm::vec3(0, 1, 0) &&
+ m.colors[2] == glm::vec3(0, 0, 1));
+ CHECK(m.colors.size() == 5 && std::abs(linearToSrgb(m.colors[4]).x - 128.0f / 255.0f) < 1e-4f);
+ // SculptForge writes the same layout back, byte for byte.
+ CHECK(writeGoz(m, "Quad") == bytes);
+}
+
+TEST(goz_skips_unknown_sections_and_rejects_garbage) {
+ std::vector<uint8_t> bytes = gobQuadAndTriangle();
+ // Insert an unknown section (tag 0x1234, 8 payload bytes) before the vertices, and a subdivision record.
+ const uint8_t vertexTag[4] = {0x11, 0x27, 0, 0};
+ auto at = std::search(bytes.begin(), bytes.end(), vertexTag, vertexTag + 4);
+ CHECK(at != bytes.end());
+ const uint8_t extra[] = {0x34, 0x12, 0, 0, 16, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8,
+ 0x8a, 0x13, 0, 0, 32, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
+ bytes.insert(at, std::begin(extra), std::end(extra));
+ Mesh m;
+ GozInfo info;
+ std::string err;
+ CHECK(parseGoz(bytes, m, err, &info));
+ CHECK(m.triangleCount() == 3 && info.subdivisionLevel == 2);
+
+ const char junk[] = "solid not a goz file";
+ CHECK(!parseGoz(std::span(reinterpret_cast<const uint8_t*>(junk), sizeof(junk)), m, err));
+ std::vector<uint8_t> truncated(bytes.begin(), bytes.begin() + 60);
+ CHECK(!parseGoz(truncated, m, err));
+ // Out-of-range indices are dropped, not trusted.
+ std::vector<uint8_t> bad = gobQuadAndTriangle();
+ const uint8_t faceTag[4] = {0x21, 0x4e, 0, 0};
+ auto f = std::search(bad.begin(), bad.end(), faceTag, faceTag + 4);
+ f[16 + 16 + 4] = 99; // second face, second index
+ CHECK(parseGoz(bad, m, err) && m.triangleCount() == 2 && !err.empty());
+}
+
+TEST(goz_commands_and_open) {
+ CommandRegistry reg;
+ for (const char* name : {"goz_import", "goz_export", "goz_send", "goz_receive", "export_stl"}) CHECK(reg.find(name));
+ Mesh m = makeIcosphere(2);
+ paintAll(m);
+ Document doc = makeDoc(m);
+ const std::string path = tempPath("sf_goz_cmd.GoZ");
+ CHECK(reg.execute(doc, "goz_export", {{"path", path}}).ok);
+ Document other;
+ CommandResult r = reg.execute(other, "open", {{"path", path}});
+ CHECK(r.ok);
+ CHECK(other.mesh.triangles == m.triangles && other.mesh.polygroups == m.polygroups && other.gozName == "sf_goz_cmd");
+ Document third;
+ r = reg.execute(third, "goz_import", {{"path", path}});
+ CHECK(r.ok && third.mesh.hasMask() && third.mesh.hasColors() && third.mesh.hasUvs() && third.gozName == "sf_goz_cmd");
+ std::filesystem::remove(path);
+
+ for (const char* ext : {".ZTL", ".zpr"}) {
+ r = reg.execute(doc, "open", {{"path", std::string("model") + ext}});
+ CHECK(!r.ok && r.message.find("proprietary") != std::string::npos && r.message.find("GoZ") != std::string::npos &&
+ r.message.find("OBJ") != std::string::npos);
+ }
+}
+
+TEST(goz_bridge_send_and_receive) {
+ namespace fs = std::filesystem;
+ const fs::path root = fs::temp_directory_path() / "sf_goz_bridge";
+ fs::remove_all(root);
+ CommandRegistry reg;
+ Mesh m = makeIcosphere(2);
+ paintAll(m);
+ Document doc = makeDoc(m);
+ const std::string folder = root.string();
+ CommandResult r = reg.execute(doc, "goz_send", {{"folder", folder}, {"name", "Sphere 1"}, {"launch", false}});
+ CHECK(r.ok);
+ const fs::path project = root / "GoZProjects" / "Default";
+ CHECK(fs::exists(project / "Sphere_1.GoZ") && fs::exists(project / "Sphere_1.ztn"));
+ CHECK(fs::exists(root / "GoZBrush" / "GoZ_Application.txt") && fs::exists(root / "GoZApps" / "SculptForge" / "GoZ_Info.txt"));
+ std::vector<uint8_t> list = readFile((root / "GoZBrush" / "GoZ_ObjectList.txt").string());
+ const std::string expected = (project / "Sphere_1").generic_string() + "\n";
+ CHECK(std::string(list.begin(), list.end()) == expected);
+ CHECK(doc.gozName == "Sphere_1");
+
+ // ZBrush sends two SubTools back: they are merged into one undoable step.
+ Mesh second = makeIcosphere(1);
+ for (auto& p : second.positions) p += glm::vec3(3, 0, 0);
+ std::string err;
+ CHECK(saveGoz((project / "Other.GoZ").string(), second, "Other", err));
+ {
+ std::ofstream f(root / "GoZBrush" / "GoZ_ObjectList.txt", std::ios::binary);
+ f << (project / "Sphere_1").generic_string() << "\r\n" << (project / "Other").generic_string() << "\r\n";
+ }
+ Document back = makeDoc(makeIcosphere(0));
+ r = reg.execute(back, "goz_receive", {{"folder", folder}});
+ CHECK(r.ok && r.message.find("Sphere_1") != std::string::npos);
+ CHECK(back.mesh.vertexCount() == m.vertexCount() + second.vertexCount());
+ CHECK(back.mesh.triangleCount() == m.triangleCount() + second.triangleCount());
+ CHECK(back.mesh.mask.size() == back.mesh.vertexCount() && back.mesh.polygroups.size() == back.mesh.triangleCount());
+ CHECK(back.mesh.uvs.size() == back.mesh.triangleCount() * 3);
+ CHECK(back.undo.canUndo());
+
+ // Missing object list explains what to do.
+ fs::remove(root / "GoZBrush" / "GoZ_ObjectList.txt");
+ r = reg.execute(back, "goz_receive", {{"folder", folder}});
+ CHECK(!r.ok && r.message.find("GoZ") != std::string::npos);
+ fs::remove_all(root);
+#if !defined(_WIN32) && !defined(__APPLE__)
+ CHECK(gozDefaultRoot().empty());
+ r = reg.execute(doc, "goz_send", {{"launch", false}});
+ CHECK(!r.ok && r.message.find("Windows and macOS") != std::string::npos);
+#endif
+}
+
+TEST(stl_round_trip_and_ascii) {
+ Mesh m = makeIcosphere(3);
+ const std::string path = tempPath("sf_stl_test.stl");
+ std::string err;
+ CHECK(saveStl(path, m, err));
+ CHECK(std::filesystem::file_size(path) == 84 + 50 * m.triangleCount());
+ Mesh r;
+ CHECK(loadStl(path, r, err));
+ CHECK(r.vertexCount() == m.vertexCount() && r.triangleCount() == m.triangleCount());
+ bool same = true;
+ for (size_t t = 0; t < m.triangleCount() && t < r.triangleCount(); ++t)
+ for (int c = 0; c < 3; ++c) same = same && r.positions[r.triangles[t][c]] == m.positions[m.triangles[t][c]];
+ CHECK(same);
+
+ // Commands: export_stl and open.
+ CommandRegistry reg;
+ Document doc = makeDoc(m);
+ CHECK(reg.execute(doc, "export_stl", {{"path", path}}).ok);
+ Document other;
+ CHECK(reg.execute(other, "open", {{"path", path}}).ok && other.mesh.triangleCount() == m.triangleCount());
+ std::filesystem::remove(path);
+
+ const char ascii[] = "solid tet\n"
+ " facet normal 0 0 -1\n outer loop\n vertex 0 0 0\n vertex 0 1 0\n vertex 1 0 0\n endloop\n endfacet\n"
+ " facet normal 0 -1 0\n outer loop\n vertex 0 0 0\n vertex 1 0 0\n vertex 0 0 1\n endloop\n endfacet\n"
+ " facet normal -1 0 0\n outer loop\n vertex 0 0 0\n vertex 0 0 1\n vertex 0 1 0\n endloop\n endfacet\n"
+ " facet normal 1 1 1\n outer loop\n vertex 1 0 0\n vertex 0 1 0\n vertex 0 0 1.5e0\n endloop\n endfacet\n"
+ "endsolid tet\n";
+ Mesh tet;
+ CHECK(parseStl(std::span(reinterpret_cast<const uint8_t*>(ascii), sizeof(ascii) - 1), tet, err));
+ CHECK(tet.vertexCount() == 5 && tet.triangleCount() == 4); // 0 0 1 and 0 0 1.5 differ
+ const char notStl[] = "hello";
+ CHECK(!parseStl(std::span(reinterpret_cast<const uint8_t*>(notStl), sizeof(notStl) - 1), tet, err));
+}