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.

Map export presets (export_maps) and PBR material slots in glTF, USD, OBJ and FBX

islandmed02fb0e8e75a7
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 045c82c7..e5c26a8e 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -71,6 +71,7 @@ add_library(sculptforge_core STATIC
src/core/TextureChannels.cpp
src/core/TextureChannelCommands.cpp
src/core/LayerStackIO.cpp
+ src/core/MapExport.cpp
src/core/Multires.cpp
src/core/MultiresCommands.cpp
src/core/AutoUv.cpp
diff --git a/src/core/MapExport.cpp b/src/core/MapExport.cpp
new file mode 100644
index 00000000..76380cab
--- /dev/null
+++ b/src/core/MapExport.cpp
@@ -0,0 +1,484 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/MapExport.h"
+
+#include "core/BakeImage.h"
+#include "core/Commands.h"
+#include "core/Document.h"
+#include "core/Json.h"
+#include "core/Texture.h"
+#include "core/TextureChannels.h"
+#include "core/ThreadPool.h"
+
+#include <algorithm>
+#include <cctype>
+#include <cmath>
+#include <cstdio>
+#include <filesystem>
+#include <fstream>
+#include <sstream>
+
+namespace sf {
+
+namespace {
+
+// The built-in presets, in the same JSON a user preset file holds (so the parser is what defines them).
+const char* const kBuiltinPresets[] = {
+ R"PRESET({"id": "unreal", "label": "Unreal Engine",
+ "description": "Base colour (opacity in alpha when painted), DirectX normal, packed occlusion / roughness / metallic. The Unreal bridge imports these and builds a material.",
+ "file": "T_{name}_{map}", "normal": "directx",
+ "maps": [{"map": "BC", "channels": ["base_color.r", "base_color.g", "base_color.b", "opacity?"]},
+ {"map": "N", "channels": ["normal.r", "normal.g", "normal.b"]},
+ {"map": "ORM", "channels": ["ao", "roughness", "metallic"]},
+ {"map": "E", "channels": ["emissive.r", "emissive.g", "emissive.b"], "optional": true},
+ {"map": "H", "channels": ["height"], "bits": 16, "optional": true}]})PRESET",
+ R"PRESET({"id": "unity_urp", "label": "Unity (URP Lit)",
+ "description": "Base map, OpenGL normal, metallic in red with smoothness in alpha, occlusion, emission and height.",
+ "file": "{name}_{map}", "normal": "opengl",
+ "maps": [{"map": "BaseMap", "channels": ["base_color.r", "base_color.g", "base_color.b", "opacity?"]},
+ {"map": "Normal", "channels": ["normal.r", "normal.g", "normal.b"]},
+ {"map": "MetallicSmoothness", "channels": ["metallic", "0", "0", "smoothness"]},
+ {"map": "Occlusion", "channels": ["ao"], "optional": true},
+ {"map": "Emission", "channels": ["emissive.r", "emissive.g", "emissive.b"], "optional": true},
+ {"map": "Height", "channels": ["height"], "bits": 16, "optional": true}]})PRESET",
+ R"PRESET({"id": "unity_hdrp", "label": "Unity (HDRP Lit)",
+ "description": "Base map, OpenGL normal and the mask map: metallic, occlusion, detail mask (white), smoothness.",
+ "file": "{name}_{map}", "normal": "opengl",
+ "maps": [{"map": "BaseMap", "channels": ["base_color.r", "base_color.g", "base_color.b", "opacity?"]},
+ {"map": "Normal", "channels": ["normal.r", "normal.g", "normal.b"]},
+ {"map": "MaskMap", "channels": ["metallic", "ao", "1", "smoothness"]},
+ {"map": "Emission", "channels": ["emissive.r", "emissive.g", "emissive.b"], "optional": true},
+ {"map": "Height", "channels": ["height"], "bits": 16, "optional": true}]})PRESET",
+ R"PRESET({"id": "gltf", "label": "glTF",
+ "description": "glTF 2.0 metal-rough: base colour, OpenGL normal, occlusion / roughness / metallic packed in R / G / B.",
+ "file": "{name}_{map}", "normal": "opengl",
+ "maps": [{"map": "baseColor", "channels": ["base_color.r", "base_color.g", "base_color.b", "opacity?"]},
+ {"map": "normal", "channels": ["normal.r", "normal.g", "normal.b"]},
+ {"map": "occlusionRoughnessMetallic", "channels": ["ao", "roughness", "metallic"]},
+ {"map": "emissive", "channels": ["emissive.r", "emissive.g", "emissive.b"], "optional": true}]})PRESET",
+ R"PRESET({"id": "godot", "label": "Godot",
+ "description": "Godot StandardMaterial3D: albedo, OpenGL normal, ORM (occlusion / roughness / metallic), emission, height.",
+ "file": "{name}_{map}", "normal": "opengl",
+ "maps": [{"map": "albedo", "channels": ["base_color.r", "base_color.g", "base_color.b", "opacity?"]},
+ {"map": "normal", "channels": ["normal.r", "normal.g", "normal.b"]},
+ {"map": "orm", "channels": ["ao", "roughness", "metallic"]},
+ {"map": "emission", "channels": ["emissive.r", "emissive.g", "emissive.b"], "optional": true},
+ {"map": "height", "channels": ["height"], "bits": 16, "optional": true}]})PRESET",
+ R"PRESET({"id": "blender", "label": "Blender",
+ "description": "One file per channel for the Principled BSDF: base colour, roughness, metallic, OpenGL normal, height (16-bit), AO, emission, alpha.",
+ "file": "{name}_{map}", "normal": "opengl",
+ "maps": [{"map": "BaseColor", "channels": ["base_color.r", "base_color.g", "base_color.b"]},
+ {"map": "Roughness", "channels": ["roughness"]},
+ {"map": "Metallic", "channels": ["metallic"]},
+ {"map": "Normal", "channels": ["normal.r", "normal.g", "normal.b"]},
+ {"map": "Height", "channels": ["height"], "bits": 16, "optional": true},
+ {"map": "AO", "channels": ["ao"], "optional": true},
+ {"map": "Emission", "channels": ["emissive.r", "emissive.g", "emissive.b"], "optional": true},
+ {"map": "Alpha", "channels": ["opacity"], "optional": true}]})PRESET",
+ R"PRESET({"id": "usd", "label": "USD (UsdPreviewSurface)",
+ "description": "One file per UsdPreviewSurface input: diffuseColor, roughness, metallic, normal, occlusion, emissiveColor, opacity, displacement.",
+ "file": "{name}_{map}", "normal": "opengl",
+ "maps": [{"map": "diffuseColor", "channels": ["base_color.r", "base_color.g", "base_color.b"]},
+ {"map": "roughness", "channels": ["roughness"]},
+ {"map": "metallic", "channels": ["metallic"]},
+ {"map": "normal", "channels": ["normal.r", "normal.g", "normal.b"]},
+ {"map": "occlusion", "channels": ["ao"], "optional": true},
+ {"map": "emissiveColor", "channels": ["emissive.r", "emissive.g", "emissive.b"], "optional": true},
+ {"map": "opacity", "channels": ["opacity"], "optional": true},
+ {"map": "displacement", "channels": ["height"], "bits": 16, "optional": true}]})PRESET",
+};
+
+std::string lower(std::string s) {
+ for (char& c : s) c = char(std::tolower(static_cast<unsigned char>(c)));
+ return s;
+}
+
+std::filesystem::path fsPath(const std::string& s) { return std::filesystem::path(std::u8string(s.begin(), s.end())); }
+std::string utf8(const std::filesystem::path& p) {
+ const auto u = p.u8string();
+ return std::string(u.begin(), u.end());
+}
+
+// Safe in file names: letters, digits, '-', '_' and '.'.
+std::string safeName(const std::string& s) {
+ std::string out;
+ for (unsigned char c : s) out += std::isalnum(c) || c == '-' || c == '_' || c == '.' ? char(c) : '_';
+ return out.empty() ? std::string("Object") : out;
+}
+
+// The sources a map keeps for this texture ('?' components dropped when their channel is off).
+std::vector<MapSource> keptSources(const PaintTexture& t, const MapSpec& map) {
+ std::vector<MapSource> out;
+ for (const MapSource& s : map.sources)
+ if (!(s.dropIfMissing && s.kind == MapSource::Kind::Channel && !channelEnabled(t, Channel(s.channel)))) out.push_back(s);
+ if (out.size() == 2) out.resize(1); // grey + alpha isn't offered: keep grey
+ return out;
+}
+
+// Evaluates the map's sources over the texture: fn(x, y, values) with values in 0..1, rows bottom-up.
+template <class Fn>
+void evaluate(const PaintTexture& t, const std::vector<MapSource>& srcs, bool directX, Fn&& fn) {
+ bool needNormal = false;
+ uint32_t needed = 0;
+ for (const MapSource& s : srcs)
+ if (s.kind == MapSource::Kind::Channel) {
+ if (s.channel == int(Channel::Normal)) needNormal = true;
+ else needed |= 1u << s.channel;
+ }
+ const TileImage* imgs[kChannelCount] = {};
+ for (int c = 1; c < kChannelCount; ++c)
+ if ((needed & (1u << c)) && channelEnabled(t, Channel(c))) imgs[c] = &channelImage(t, Channel(c));
+ poolFor(size_t(t.height), [&](size_t b, size_t e) {
+ float vals[4];
+ for (int y = int(b); y < int(e); ++y)
+ for (int x = 0; x < t.width; ++x) {
+ float chan[kChannelCount][3];
+ glm::vec3 n(0, 0, 1);
+ if (needNormal) n = effectiveNormalAt(t, x, y);
+ const uint8_t* px = &t.pixels[(size_t(y) * size_t(t.width) + size_t(x)) * 4];
+ for (size_t k = 0; k < srcs.size(); ++k) {
+ const MapSource& s = srcs[k];
+ float v = s.constant;
+ if (s.kind == MapSource::Kind::Channel) {
+ if (s.channel == int(Channel::BaseColor)) {
+ v = float(px[std::clamp(s.component, 0, 2)]) / 255.0f;
+ } else if (s.channel == int(Channel::Normal)) {
+ float c = n[std::clamp(s.component, 0, 2)];
+ if (s.component == 1 && directX) c = -c;
+ v = c * 0.5f + 0.5f;
+ } else if (const TileImage* img = imgs[s.channel]) {
+ img->values(x, y, chan[s.channel]);
+ v = chan[s.channel][std::clamp(s.component, 0, img->components() - 1)];
+ } else {
+ v = channelFormat(s.channel).defaultValue[size_t(std::clamp(s.component, 0, 2))];
+ }
+ }
+ vals[k] = std::clamp(s.invert ? 1.0f - v : v, 0.0f, 1.0f);
+ }
+ fn(x, y, vals);
+ }
+ }, 8, 2);
+}
+
+} // namespace
+
+bool parseMapSource(const std::string& textIn, MapSource& out, std::string& error) {
+ out = MapSource();
+ std::string text;
+ for (char c : textIn)
+ if (!std::isspace(static_cast<unsigned char>(c))) text += char(std::tolower(static_cast<unsigned char>(c)));
+ if (!text.empty() && text.back() == '?') {
+ out.dropIfMissing = true;
+ text.pop_back();
+ }
+ if (text.rfind("1-", 0) == 0) {
+ out.invert = true;
+ text = text.substr(2);
+ }
+ if (text.empty()) {
+ error = "Empty map source";
+ return false;
+ }
+ if (std::isdigit(static_cast<unsigned char>(text[0])) || text[0] == '.') {
+ char* end = nullptr;
+ const float v = std::strtof(text.c_str(), &end);
+ if (end && *end == '\0' && std::isfinite(v)) {
+ out.kind = MapSource::Kind::Constant;
+ out.constant = std::clamp(v, 0.0f, 1.0f);
+ if (out.invert) out.constant = 1.0f - out.constant, out.invert = false;
+ return true;
+ }
+ }
+ if (text == "smoothness" || text == "gloss" || text == "glossiness") {
+ out.kind = MapSource::Kind::Channel;
+ out.channel = int(Channel::Roughness);
+ out.invert = !out.invert;
+ return true;
+ }
+ std::string name = text, comp;
+ if (const size_t dot = text.find('.'); dot != std::string::npos) {
+ name = text.substr(0, dot);
+ comp = text.substr(dot + 1);
+ }
+ Channel c;
+ if (!parseChannel(name, c)) {
+ error = "Unknown map source '" + textIn + "'";
+ return false;
+ }
+ out.kind = MapSource::Kind::Channel;
+ out.channel = int(c);
+ if (!comp.empty()) {
+ static const char* names[] = {"r", "g", "b"};
+ int found = -1;
+ for (int i = 0; i < 3; ++i)
+ if (comp == names[i] || comp == std::string(1, "xyz"[i])) found = i;
+ if (comp == "a" && c == Channel::BaseColor) { // base colour's alpha is the opacity channel
+ out.channel = int(Channel::Opacity);
+ found = 0;
+ }
+ if (found < 0 || (found > 0 && channelFormat(out.channel).components < 3 && out.channel != int(Channel::BaseColor))) {
+ error = "Unknown component in map source '" + textIn + "'";
+ return false;
+ }
+ out.component = found;
+ }
+ return true;
+}
+
+bool parseExportPreset(const std::string& json, ExportPreset& out, std::string& error) {
+ Json j;
+ if (!Json::parse(json, j, error) || !j.isObject()) {
+ error = "Export preset is not a JSON object" + (error.empty() ? "" : " (" + error + ")");
+ return false;
+ }
+ out = ExportPreset();
+ out.id = j["id"].asString();
+ out.label = j["label"].isString() ? j["label"].asString() : out.id;
+ out.description = j["description"].asString();
+ out.file = j["file"].isString() ? j["file"].asString() : std::string("{name}_{map}");
+ if (out.file.find("{map}") == std::string::npos) {
+ error = "Export preset 'file' must contain {map}";
+ return false;
+ }
+ const std::string normal = lower(j["normal"].isString() ? j["normal"].asString() : std::string("opengl"));
+ if (normal != "opengl" && normal != "directx") {
+ error = "Export preset 'normal' must be opengl or directx";
+ return false;
+ }
+ out.normalDirectX = normal == "directx";
+ if (!j["maps"].isArray() || j["maps"].size() == 0 || j["maps"].size() > 32) {
+ error = "Export preset needs a list of 1-32 maps";
+ return false;
+ }
+ for (size_t i = 0; i < j["maps"].size(); ++i) {
+ const Json& mj = j["maps"][i];
+ MapSpec m;
+ m.map = mj["map"].asString();
+ if (m.map.empty() || safeName(m.map) != m.map) {
+ error = "Export preset map " + std::to_string(i + 1) + " needs a 'map' name of letters, digits, - and _";
+ return false;
+ }
+ const size_t n = mj["channels"].size();
+ if (!mj["channels"].isArray() || (n != 1 && n != 3 && n != 4)) {
+ error = "Map '" + m.map + "' needs 1, 3 or 4 channels";
+ return false;
+ }
+ for (size_t k = 0; k < n; ++k) {
+ MapSource s;
+ if (!parseMapSource(mj["channels"][k].asString(), s, error)) return false;
+ m.sources.push_back(s);
+ }
+ m.bits = int(mj["bits"].asNumber(8));
+ if (m.bits != 8 && m.bits != 16) {
+ error = "Map '" + m.map + "': bits must be 8 or 16";
+ return false;
+ }
+ m.optional = mj["optional"].asBool(false);
+ out.maps.push_back(std::move(m));
+ }
+ return true;
+}
+
+const std::vector<ExportPreset>& builtinExportPresets() {
+ static const std::vector<ExportPreset> presets = [] {
+ std::vector<ExportPreset> v;
+ for (const char* text : kBuiltinPresets) {
+ ExportPreset p;
+ std::string err;
+ if (parseExportPreset(text, p, err)) v.push_back(std::move(p));
+ }
+ return v;
+ }();
+ return presets;
+}
+
+bool findExportPreset(const std::string& idOrPath, ExportPreset& out, std::string& error) {
+ std::string id = lower(idOrPath);
+ if (id == "ue" || id == "unreal_engine") id = "unreal";
+ if (id == "unity") id = "unity_urp";
+ if (id == "urp") id = "unity_urp";
+ if (id == "hdrp") id = "unity_hdrp";
+ if (id == "gltf2" || id == "glb") id = "gltf";
+ for (const ExportPreset& p : builtinExportPresets())
+ if (p.id == id) {
+ out = p;
+ return true;
+ }
+ std::ifstream f(fsPath(idOrPath), std::ios::binary);
+ if (!f) {
+ std::string ids;
+ for (const ExportPreset& p : builtinExportPresets()) ids += (ids.empty() ? "" : ", ") + p.id;
+ error = "No export preset '" + idOrPath + "' (built-in: " + ids + ", or a preset .json file)";
+ return false;
+ }
+ std::stringstream ss;
+ ss << f.rdbuf();
+ if (!parseExportPreset(ss.str(), out, error)) return false;
+ if (out.id.empty()) out.id = utf8(fsPath(idOrPath).stem());
+ return true;
+}
+
+bool mapWanted(const PaintTexture& t, const MapSpec& map) {
+ if (!map.optional) return true;
+ for (const MapSource& s : map.sources)
+ if (s.kind == MapSource::Kind::Channel && s.channel != int(Channel::BaseColor) && channelEnabled(t, Channel(s.channel)))
+ return true;
+ return false;
+}
+
+bool renderMap(const PaintTexture& t, const MapSpec& map, bool directX, Image& out, int& channels) {
+ if (t.width <= 0 || t.pixels.size() != t.texelCount() * 4) return false;
+ const std::vector<MapSource> srcs = keptSources(t, map);
+ channels = int(srcs.size());
+ out.width = t.width;
+ out.height = t.height;
+ out.rgba.assign(t.texelCount() * 4, 255);
+ evaluate(t, srcs, directX, [&](int x, int y, const float* v) {
+ uint8_t* o = &out.rgba[(size_t(t.height - 1 - y) * size_t(t.width) + size_t(x)) * 4];
+ auto b = [](float f) { return uint8_t(std::lround(f * 255.0f)); };
+ if (channels == 1) {
+ o[0] = o[1] = o[2] = b(v[0]);
+ } else {
+ o[0] = b(v[0]), o[1] = b(v[1]), o[2] = b(v[2]);
+ if (channels == 4) o[3] = b(v[3]);
+ }
+ });
+ return true;
+}
+
+bool renderMap16(const PaintTexture& t, const MapSpec& map, bool directX, std::vector<uint16_t>& out, int& channels) {
+ if (t.width <= 0 || t.pixels.size() != t.texelCount() * 4) return false;
+ const std::vector<MapSource> srcs = keptSources(t, map);
+ channels = int(srcs.size());
+ out.assign(t.texelCount() * size_t(channels), 0);
+ evaluate(t, srcs, directX, [&](int x, int y, const float* v) {
+ uint16_t* o = &out[(size_t(t.height - 1 - y) * size_t(t.width) + size_t(x)) * size_t(channels)];
+ for (int k = 0; k < channels; ++k) o[k] = uint16_t(std::lround(v[k] * 65535.0f));
+ });
+ return true;
+}
+
+std::string mapFileName(const ExportPreset& preset, const MapSpec& map, const std::string& name) {
+ std::string f = preset.file;
+ auto put = [&](const std::string& key, const std::string& value) {
+ for (size_t at = f.find(key); at != std::string::npos; at = f.find(key, at + value.size())) f.replace(at, key.size(), value);
+ };
+ put("{name}", safeName(name));
+ put("{map}", map.map);
+ return safeName(f) + ".png";
+}
+
+bool exportMaps(const PaintTexture& t, const ExportPreset& preset, const std::string& folder, const std::string& name,
+ std::vector<ExportedMap>& written, std::string& error) {
+ written.clear();
+ std::error_code ec;
+ std::filesystem::create_directories(fsPath(folder), ec);
+ if (!std::filesystem::is_directory(fsPath(folder))) {
+ error = "Cannot create the folder " + folder;
+ return false;
+ }
+ for (const MapSpec& map : preset.maps) {
+ if (!mapWanted(t, map)) continue;
+ const std::string path = utf8(fsPath(folder) / fsPath(mapFileName(preset, map, name)));
+ int channels = 0;
+ bool ok = false;
+ if (map.bits == 16) {
+ std::vector<uint16_t> px;
+ ok = renderMap16(t, map, preset.normalDirectX, px, channels) && savePng16(path, t.width, t.height, channels, px, error);
+ } else {
+ Image img;
+ ok = renderMap(t, map, preset.normalDirectX, img, channels) && img.savePng(path, error);
+ }
+ if (!ok) {
+ if (error.empty()) error = "Cannot write " + path;
+ return false;
+ }
+ written.push_back({map.map, path});
+ }
+ return true;
+}
+
+bool encodeMapPng(const PaintTexture& t, const std::vector<std::string>& sources, bool directX, std::vector<uint8_t>& png) {
+ MapSpec spec;
+ spec.map = "map";
+ for (const std::string& s : sources) {
+ MapSource src;
+ std::string err;
+ if (!parseMapSource(s, src, err)) return false;
+ spec.sources.push_back(src);
+ }
+ Image img;
+ int channels = 0;
+ return renderMap(t, spec, directX, img, channels) && img.encodePng(png);
+}
+
+std::vector<std::string> pbrSlots(const PaintTexture& t, bool packedOrm) {
+ std::vector<std::string> out;
+ if (!hasMaterialChannels(t)) return out;
+ out.push_back("base_color");
+ if (channelEnabled(t, Channel::Normal) || channelEnabled(t, Channel::Height)) out.push_back("normal");
+ if (packedOrm) {
+ out.push_back("orm");
+ } else {
+ out.push_back("roughness");
+ out.push_back("metallic");
+ if (channelEnabled(t, Channel::AO)) out.push_back("occlusion");
+ }
+ if (channelEnabled(t, Channel::Emissive)) out.push_back("emissive");
+ if (!packedOrm && channelEnabled(t, Channel::Opacity)) out.push_back("opacity");
+ return out;
+}
+
+std::vector<std::string> pbrSlotSources(const std::string& slot) {
+ if (slot == "base_color") return {"base_color.r", "base_color.g", "base_color.b", "opacity?"};
+ if (slot == "normal") return {"normal.r", "normal.g", "normal.b"};
+ if (slot == "orm") return {"ao", "roughness", "metallic"};
+ if (slot == "roughness") return {"roughness"};
+ if (slot == "metallic") return {"metallic"};
+ if (slot == "occlusion") return {"ao"};
+ if (slot == "emissive") return {"emissive.r", "emissive.g", "emissive.b"};
+ if (slot == "opacity") return {"opacity"};
+ return {};
+}
+
+void registerMapExportCommands(CommandRegistry& reg) {
+ using T = ParamSpec::Type;
+ reg.add({"export_maps",
+ "Export the active SubTool's texture channels as image files for an engine or DCC, using an export "
+ "preset: unreal (T_<name>_BC / _N in DirectX / _ORM), unity_urp, unity_hdrp (mask map), gltf, godot, "
+ "blender (one file per channel), usd, or your own preset .json file (docs/guide/export-presets.md). "
+ "list=true lists the presets.",
+ {{"preset", T::String, "Preset id or a preset .json path. Default gltf.", false},
+ {"folder", T::String, "Output folder (created if missing).", false},
+ {"name", T::String, "Object name in the file names. Default: the SubTool's name.", false},
+ {"list", T::Bool, "List the built-in presets instead.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ if (argBool(a, "list", false)) {
+ std::string s = "Export presets:";
+ for (const ExportPreset& p : builtinExportPresets()) {
+ s += "\n " + p.id + " (" + p.label + "):";
+ for (const MapSpec& m : p.maps) s += " " + m.map + (m.optional ? "?" : "");
+ }
+ return {true, s};
+ }
+ if (!hasTexture(doc.mesh))
+ return {false, "The SubTool has no texture: create one first (Tool > Texture Map > New, or texture_create)"};
+ const std::string folder = argString(a, "folder");
+ if (folder.empty()) return {false, "Give a folder"};
+ ExportPreset preset;
+ std::string err;
+ if (!findExportPreset(argString(a, "preset", "gltf"), preset, err)) return {false, err};
+ std::string name = argString(a, "name");
+ if (name.empty() && doc.activeSubtool >= 0 && doc.activeSubtool < doc.subtoolCount())
+ name = doc.subtools[size_t(doc.activeSubtool)].name;
+ if (name.empty()) name = "Sculpt";
+ std::vector<ExportedMap> written;
+ if (!exportMaps(*doc.mesh.texture, preset, folder, name, written, err)) return {false, err};
+ std::string files;
+ for (const ExportedMap& m : written) files += "\n " + m.path;
+ return {true, "Exported " + std::to_string(written.size()) + " " + preset.label + " maps (" +
+ std::to_string(doc.mesh.texture->width) + "x" + std::to_string(doc.mesh.texture->height) + "):" + files};
+ }});
+}
+
+} // namespace sf
diff --git a/src/core/MapExport.h b/src/core/MapExport.h
new file mode 100644
index 00000000..b189338e
--- /dev/null
+++ b/src/core/MapExport.h
@@ -0,0 +1,99 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Map export: writes a texture's channels (core/TextureChannels.h) as the image files a game engine or DCC
+// expects, driven by export presets (export_maps).
+//
+// A preset is a small JSON document (our own format; built-ins below, or any .json file):
+//
+// { "id": "unreal", "label": "Unreal Engine", "file": "T_{name}_{map}", "normal": "directx",
+// "maps": [ {"map": "BC", "channels": ["base_color.r", "base_color.g", "base_color.b", "opacity?"]},
+// {"map": "N", "channels": ["normal.r", "normal.g", "normal.b"]},
+// {"map": "ORM", "channels": ["ao", "roughness", "metallic"]},
+// {"map": "H", "channels": ["height"], "bits": 16, "optional": true} ] }
+//
+// Each map lists 1 (grey), 3 (RGB) or 4 (RGBA) sources. A source is a channel ("roughness", "ao", "height",
+// "metallic", "opacity"), a component ("base_color.g", "normal.r", "emissive.b"), "smoothness" (1 - roughness),
+// a constant ("0", "1", "0.5"), or "1-<source>". A trailing '?' drops that component when its channel isn't
+// enabled (an RGBA map becomes RGB). "optional": true writes the map only when one of its channels is enabled.
+// "normal": "directx" flips green (Y down); the normal is the effective one (Height's normal combined in).
+// "bits": 16 writes a 16-bit PNG (height). Channels that aren't enabled export their default value.
+//
+// Built-in presets: unreal, unity_urp, unity_hdrp, gltf, godot, blender, usd.
+#pragma once
+
+#include "core/Image.h"
+
+#include <string>
+#include <vector>
+
+namespace sf {
+
+struct PaintTexture;
+class CommandRegistry;
+struct Document;
+
+struct MapSource {
+ enum class Kind { Channel, Constant } kind = Kind::Constant;
+ int channel = 0; // Channel
+ int component = 0; // 0..2
+ bool invert = false; // 1 - value
+ bool dropIfMissing = false;
+ float constant = 0;
+};
+
+struct MapSpec {
+ std::string map; // the file suffix ("BC", "ORM", "Normal")
+ std::vector<MapSource> sources;
+ int bits = 8;
+ bool optional = false;
+};
+
+struct ExportPreset {
+ std::string id, label, description;
+ std::string file = "{name}_{map}"; // {name}: object name, {map}: MapSpec::map
+ bool normalDirectX = false;
+ std::vector<MapSpec> maps;
+};
+
+// Parses one source ("base_color.r", "1-roughness", "opacity?", "0.5"); false for an unknown one.
+bool parseMapSource(const std::string& text, MapSource& out, std::string& error);
+bool parseExportPreset(const std::string& json, ExportPreset& out, std::string& error);
+const std::vector<ExportPreset>& builtinExportPresets();
+// A built-in preset by id (any case; "godot" etc.), or a preset .json file.
+bool findExportPreset(const std::string& idOrPath, ExportPreset& out, std::string& error);
+
+// Whether a map is written for this texture (optional maps need one of their channels).
+bool mapWanted(const PaintTexture& tex, const MapSpec& map);
+// The map as an 8-bit image (top row = v 1, as image files are): grey, RGB or RGBA after '?' drops
+// (Image is always RGBA; `channels` says how many are meaningful: 1, 3 or 4).
+bool renderMap(const PaintTexture& tex, const MapSpec& map, bool normalDirectX, Image& out, int& channels);
+// 16-bit version (top-down), `channels` 1, 3 or 4 values per pixel.
+bool renderMap16(const PaintTexture& tex, const MapSpec& map, bool normalDirectX, std::vector<uint16_t>& out, int& channels);
+
+// A map from a list of sources (as a preset's "channels") encoded as an 8-bit PNG (top row = v 1). The model
+// exporters use it for their PBR material slots.
+bool encodeMapPng(const PaintTexture& tex, const std::vector<std::string>& sources, bool normalDirectX, std::vector<uint8_t>& png);
+
+// The PBR material slots a model exporter writes for a texture with material channels: "base_color" (opacity in
+// alpha when painted), "normal" (OpenGL; written when Normal or Height is enabled), "orm" (glTF's occlusion /
+// roughness / metallic), "roughness", "metallic", "occlusion", "emissive", "opacity". Empty for a texture without
+// material channels. `packedOrm`: glTF packs roughness / metallic / occlusion into "orm" instead of separate maps.
+std::vector<std::string> pbrSlots(const PaintTexture& tex, bool packedOrm);
+// Sources of a slot (for encodeMapPng); empty for an unknown slot.
+std::vector<std::string> pbrSlotSources(const std::string& slot);
+
+// The file name (no folder, with .png) of `map` for an object called `name`.
+std::string mapFileName(const ExportPreset& preset, const MapSpec& map, const std::string& name);
+
+struct ExportedMap {
+ std::string map, path;
+};
+// Writes every wanted map of `preset` into `folder` (created if missing). False with `error` on failure.
+bool exportMaps(const PaintTexture& tex, const ExportPreset& preset, const std::string& folder, const std::string& name,
+ std::vector<ExportedMap>& written, std::string& error);
+
+// export_maps.
+void registerMapExportCommands(CommandRegistry& registry);
+
+} // namespace sf
diff --git a/src/core/Polypaint.cpp b/src/core/Polypaint.cpp
index fcbc5b72..48b3abcc 100644
--- a/src/core/Polypaint.cpp
+++ b/src/core/Polypaint.cpp
@@ -1,6 +1,7 @@
// SculptForge - open source digital sculpting
// SPDX-License-Identifier: GPL-3.0-or-later
#include "core/Polypaint.h"
+#include "core/MapExport.h"
#include "core/Commands.h"
#include "core/SubTools.h"
@@ -403,6 +404,7 @@ void registerPaintCommands(CommandRegistry& registry) {
registerPaintLayerCommands(registry); // paint_layer_* (core/PaintLayer.cpp)
registerTextureCommands(registry); // texture_*, uv_auto, paint_target (core/TextureCommands.cpp)
registerTextureChannelCommands(registry); // texture_channels, paint_material, channel_view (core/TextureChannelCommands.cpp)
+ registerMapExportCommands(registry); // export_maps (core/MapExport.cpp)
}
} // namespace sf
diff --git a/src/io/FbxIO.cpp b/src/io/FbxIO.cpp
index 711001f8..acebc6d2 100644
--- a/src/io/FbxIO.cpp
+++ b/src/io/FbxIO.cpp
@@ -391,33 +391,55 @@ bool saveFbx(const std::string& path, const std::vector<FbxObject>& fbxObjects,
prop70(p70, "Shininess", "double", "Number", "").f64(20.0);
prop70(p70, "ShininessExponent", "double", "Number", "").f64(20.0);
- const std::string texName = safeTextureName(name) + "_color";
- Node& tex = objects.add("Texture").i64(textureId).objName(texName, "Texture").str("");
- tex.add("Type").str("TextureVideoClip");
- tex.add("Version").i32(202);
- tex.add("TextureName").objName(texName, "Texture");
- Node& tp70 = tex.add("Properties70");
- prop70(tp70, "UseMaterial", "bool", "", "").i32(1);
- prop70(tp70, "UseMipMap", "bool", "", "").i32(0);
- tex.add("Media").objName(texName, "Video");
- tex.add("FileName").str(file);
- tex.add("RelativeFilename").str(pngs[oi]);
- tex.add("ModelUVTranslation").f64(0.0).f64(0.0);
- tex.add("ModelUVScaling").f64(1.0).f64(1.0);
- tex.add("Texture_Alpha_Source").str("None");
- tex.add("Cropping").i32(0).i32(0).i32(0).i32(0);
-
- Node& video = objects.add("Video").i64(videoId).objName(texName, "Video").str("Clip");
- video.add("Type").str("Clip");
- prop70(video.add("Properties70"), "Path", "KString", "XRefUrl", "").str(file);
- video.add("UseMipMap").i32(0);
- video.add("Filename").str(file);
- video.add("RelativeFilename").str(pngs[oi]);
-
- addConnection(connections, "OO", videoId, textureId);
- addPropertyConnection(connections, textureId, objectMaterialId, "DiffuseColor");
+ // One Texture + Video pair reading `fileAbs` (relative name `rel`), connected to the material's `property`.
+ auto addTexture = [&](int64_t texId, int64_t vidId, const std::string& texName, const std::string& fileAbs,
+ const std::string& rel, const std::string& property) {
+ Node& tex = objects.add("Texture").i64(texId).objName(texName, "Texture").str("");
+ tex.add("Type").str("TextureVideoClip");
+ tex.add("Version").i32(202);
+ tex.add("TextureName").objName(texName, "Texture");
+ Node& tp70 = tex.add("Properties70");
+ prop70(tp70, "UseMaterial", "bool", "", "").i32(1);
+ prop70(tp70, "UseMipMap", "bool", "", "").i32(0);
+ tex.add("Media").objName(texName, "Video");
+ tex.add("FileName").str(fileAbs);
+ tex.add("RelativeFilename").str(rel);
+ tex.add("ModelUVTranslation").f64(0.0).f64(0.0);
+ tex.add("ModelUVScaling").f64(1.0).f64(1.0);
+ tex.add("Texture_Alpha_Source").str("None");
+ tex.add("Cropping").i32(0).i32(0).i32(0).i32(0);
+
+ Node& video = objects.add("Video").i64(vidId).objName(texName, "Video").str("Clip");
+ video.add("Type").str("Clip");
+ prop70(video.add("Properties70"), "Path", "KString", "XRefUrl", "").str(fileAbs);
+ video.add("UseMipMap").i32(0);
+ video.add("Filename").str(fileAbs);
+ video.add("RelativeFilename").str(rel);
+
+ addConnection(connections, "OO", vidId, texId);
+ addPropertyConnection(connections, texId, objectMaterialId, property);
+ ++textures;
+ };
+ addTexture(textureId, videoId, safeTextureName(name) + "_color", file, pngs[oi], "DiffuseColor");
+ // Material channels (core/TextureChannels.h): their maps on the FBX material properties importers map
+ // to PBR inputs (Blender: ShininessExponent -> roughness, ReflectionFactor -> metallic).
+ std::vector<PbrPng> pbr;
+ if (!encodePbrPngs(*lods[0], false, pngs[oi], pbr) || !writePbrPngsBeside(path, pbr, error)) {
+ if (error.empty()) error = "Cannot encode the material maps of " + name;
+ return false;
+ }
+ for (const PbrPng& p : pbr) {
+ const char* property = p.slot == "normal" ? "NormalMap"
+ : p.slot == "roughness" ? "ShininessExponent"
+ : p.slot == "metallic" ? "ReflectionFactor"
+ : p.slot == "emissive" ? "EmissiveColor"
+ : p.slot == "opacity" ? "TransparencyFactor"
+ : nullptr;
+ if (!property) continue; // occlusion: no FBX material input; the file is still written
+ const std::string pngAbs = textureUtf8(textureFsPath(file).parent_path() / textureFsPath(p.name));
+ addTexture(ids(), ids(), safeTextureName(name) + "_" + p.slot, pngAbs, p.name, property);
+ }
++materials;
- ++textures;
}
if (grouped) {
const int64_t groupId = ids(), attrId = ids();
diff --git a/src/io/GltfIO.cpp b/src/io/GltfIO.cpp
index ec1465be..0d6572e7 100644
--- a/src/io/GltfIO.cpp
+++ b/src/io/GltfIO.cpp
@@ -115,7 +115,7 @@ bool saveGlb(const std::string& path, const std::vector<MeshObjectRef>& objects,
};
std::vector<View> views;
std::ostringstream accessors, meshes, nodes, images, materials;
- int accessorCount = 0, textureCount = 0;
+ int accessorCount = 0, textureCount = 0, materialCount = 0; // images and textures share an index
auto addVec3 = [&](const std::vector<glm::vec3>& v, bool withMinMax) {
size_t off = bin.append(v.data(), v.size() * sizeof(glm::vec3));
@@ -212,17 +212,43 @@ bool saveGlb(const std::string& path, const std::vector<MeshObjectRef>& objects,
std::vector<int> targetAccs;
for (const auto& l : mesh.layers) targetAccs.push_back(addVec3(uvs ? split(l.delta) : l.delta, true));
- // The texture (core/Texture.h) embedded as a PNG: image, texture and material share one index.
+ // The texture (core/Texture.h) embedded as PNGs: one image and texture per map. With material channels
+ // (core/TextureChannels.h) the material gets the glTF metal-rough slots: occlusion / roughness / metallic
+ // packed in one image, the normal map, emission, and opacity in the base colour's alpha.
int material = -1;
std::vector<uint8_t> png;
+ auto addImage = [&](const std::vector<uint8_t>& bytes, const std::string& suffix) {
+ const size_t off = bin.append(bytes.data(), bytes.size());
+ views.push_back({off, bytes.size(), 0});
+ const int index = textureCount++;
+ images << (index ? "," : "") << "{\"bufferView\":" << views.size() - 1 << ",\"mimeType\":\"image/png\",\"name\":\""
+ << jsonEscape(name) << "_" << suffix << "\"}";
+ return index;
+ };
if (encodeTexturePng(mesh, png)) {
- const size_t off = bin.append(png.data(), png.size());
- views.push_back({off, png.size(), 0});
- material = textureCount++;
- images << (material ? "," : "") << "{\"bufferView\":" << views.size() - 1 << ",\"mimeType\":\"image/png\",\"name\":\""
- << jsonEscape(name) << "_color\"}";
+ const int color = addImage(png, "color");
+ std::vector<PbrPng> pbr;
+ if (!encodePbrPngs(mesh, true, std::string(), pbr)) {
+ error = "Cannot encode the material maps of " + name;
+ return false;
+ }
+ material = materialCount++;
materials << (material ? "," : "") << "{\"name\":\"" << jsonEscape(name) << "\",\"pbrMetallicRoughness\":{"
- << "\"baseColorTexture\":{\"index\":" << material << "},\"metallicFactor\":0,\"roughnessFactor\":0.65}}";
+ << "\"baseColorTexture\":{\"index\":" << color << "}";
+ const PbrPng* orm = findPbrPng(pbr, "orm");
+ int ormTex = -1;
+ if (orm) {
+ ormTex = addImage(orm->png, "occlusionRoughnessMetallic");
+ materials << ",\"metallicRoughnessTexture\":{\"index\":" << ormTex << "},\"metallicFactor\":1,\"roughnessFactor\":1}";
+ } else {
+ materials << ",\"metallicFactor\":0,\"roughnessFactor\":0.65}";
+ }
+ if (orm && channelEnabled(*mesh.texture, Channel::AO)) materials << ",\"occlusionTexture\":{\"index\":" << ormTex << "}";
+ if (const PbrPng* n = findPbrPng(pbr, "normal")) materials << ",\"normalTexture\":{\"index\":" << addImage(n->png, "normal") << "}";
+ if (const PbrPng* e = findPbrPng(pbr, "emissive"))
+ materials << ",\"emissiveTexture\":{\"index\":" << addImage(e->png, "emissive") << "},\"emissiveFactor\":[1,1,1]";
+ if (hasPbrTexture(mesh) && channelEnabled(*mesh.texture, Channel::Opacity)) materials << ",\"alphaMode\":\"BLEND\"";
+ materials << "}";
}
nodes << (oi ? "," : "") << "{\"mesh\":" << oi << ",\"name\":\"" << jsonEscape(name) << "\"}";
@@ -295,6 +321,7 @@ bool saveGlb(const std::string& path, const std::vector<MeshObjectRef>& objects,
json << ",\"images\":[" << images.str() << "],\"samplers\":[{\"magFilter\":9729,\"minFilter\":9987,"
<< "\"wrapS\":10497,\"wrapT\":10497}],\"textures\":[";
for (int i = 0; i < textureCount; ++i) json << (i ? "," : "") << "{\"sampler\":0,\"source\":" << i << "}";
+ (void)materialCount;
json << "],\"materials\":[" << materials.str() << "]";
}
if (animated)
diff --git a/src/io/ObjIO.cpp b/src/io/ObjIO.cpp
index f25f53e0..de902111 100644
--- a/src/io/ObjIO.cpp
+++ b/src/io/ObjIO.cpp
@@ -316,6 +316,20 @@ bool saveObj(const std::string& path, const std::vector<MeshObjectRef>& objects,
std::string pngPath;
if (!writeTextureBeside(path, pngs[i], *objects[i].mesh, pngPath, error)) return false;
mtl += "\nnewmtl " + name + "\nKa 0 0 0\nKd 1 1 1\nKs 0 0 0\nillum 1\nmap_Kd " + pngs[i] + "\n";
+ // Material channels: the PBR extension of MTL (Pr / Pm / Ke, map_Pr, map_Pm, map_Ke, norm), as Blender
+ // and other importers read it; occlusion has no MTL key and goes out as its file only.
+ std::vector<PbrPng> pbr;
+ if (!encodePbrPngs(*objects[i].mesh, false, pngs[i], pbr) || !writePbrPngsBeside(path, pbr, error)) {
+ if (error.empty()) error = "Cannot encode the material maps of " + objects[i].name;
+ return false;
+ }
+ for (const PbrPng& p : pbr) {
+ if (p.slot == "roughness") mtl += "Pr 1\nmap_Pr " + p.name + "\n";
+ else if (p.slot == "metallic") mtl += "Pm 1\nmap_Pm " + p.name + "\n";
+ else if (p.slot == "normal") mtl += "norm " + p.name + "\nmap_Bump -bm 1 " + p.name + "\n";
+ else if (p.slot == "emissive") mtl += "Ke 1 1 1\nmap_Ke " + p.name + "\n";
+ else if (p.slot == "opacity") mtl += "map_d " + p.name + "\n";
+ }
}
if (clayUsed) mtl += "\nnewmtl " + clay + "\nKa 0 0 0\nKd 0.8 0.55 0.45\nKs 0 0 0\nillum 1\n";
const std::filesystem::path mtlPath = utf8Path(path).parent_path() / utf8Path(sidecarStem(path) + ".mtl");
diff --git a/src/io/TextureExport.h b/src/io/TextureExport.h
index b2242bcb..5dadd597 100644
--- a/src/io/TextureExport.h
+++ b/src/io/TextureExport.h
@@ -10,6 +10,7 @@
#pragma once
#include "core/Image.h"
+#include "core/MapExport.h"
#include "core/Mesh.h"
#include "core/Texture.h"
#include "io/MeshObject.h"
@@ -18,6 +19,7 @@
#include <cctype>
#include <cstdint>
#include <filesystem>
+#include <fstream>
#include <string>
#include <vector>
@@ -99,10 +101,14 @@ inline std::vector<std::string> textureFileNames(const std::string& modelPath, c
return names;
}
-// The mesh's texture (its composite) as PNG bytes.
+// The mesh has a texture with material channels (core/TextureChannels.h): exporters add PBR material slots.
+inline bool hasPbrTexture(const Mesh& mesh) { return hasTexture(mesh) && hasMaterialChannels(*mesh.texture); }
+
+// The mesh's texture (its composite) as PNG bytes; with material channels, opacity goes into alpha.
inline bool encodeTexturePng(const Mesh& mesh, std::vector<uint8_t>& png) {
png.clear();
if (!hasTexture(mesh)) return false;
+ if (hasPbrTexture(mesh)) return encodeMapPng(*mesh.texture, pbrSlotSources("base_color"), false, png);
return textureImage(*mesh.texture).encodePng(png);
}
@@ -114,7 +120,70 @@ inline bool writeTextureBeside(const std::string& modelPath, const std::string&
error = "The mesh has no texture";
return false;
}
+ if (hasPbrTexture(mesh)) {
+ std::vector<uint8_t> png;
+ if (!encodeTexturePng(mesh, png)) {
+ error = "Cannot encode the texture";
+ return false;
+ }
+ std::ofstream f(textureFsPath(pngPath), std::ios::binary);
+ if (!f || !f.write(reinterpret_cast<const char*>(png.data()), std::streamsize(png.size()))) {
+ error = "Cannot write " + pngPath;
+ return false;
+ }
+ return true;
+ }
return textureImage(*mesh.texture).savePng(pngPath, error);
}
+// --- PBR material slots (core/MapExport.h pbrSlots): one PNG per slot beside / inside the model ---
+
+// The file name of a slot's PNG, made from the object's colour PNG name ("<stem>_color.png" ->
+// "<stem>_roughness.png").
+inline std::string pbrFileName(const std::string& colorName, const std::string& slot) {
+ const std::string tail = "_color.png";
+ std::string stem = colorName;
+ if (stem.size() > tail.size() && stem.compare(stem.size() - tail.size(), tail.size(), tail) == 0)
+ stem.resize(stem.size() - tail.size());
+ else if (stem.size() > 4)
+ stem.resize(stem.size() - 4);
+ return stem + "_" + slot + ".png";
+}
+
+struct PbrPng {
+ std::string slot, name; // name: pbrFileName of the colour PNG ("" when written inside the file)
+ std::vector<uint8_t> png;
+};
+// Every PBR slot but base colour (which is the colour PNG) for the mesh, encoded. Empty without material channels.
+inline bool encodePbrPngs(const Mesh& mesh, bool packedOrm, const std::string& colorName, std::vector<PbrPng>& out) {
+ out.clear();
+ if (!hasPbrTexture(mesh)) return true;
+ for (const std::string& slot : pbrSlots(*mesh.texture, packedOrm)) {
+ if (slot == "base_color") continue;
+ PbrPng p;
+ p.slot = slot;
+ p.name = colorName.empty() ? std::string() : pbrFileName(colorName, slot);
+ if (!encodeMapPng(*mesh.texture, pbrSlotSources(slot), false, p.png)) return false;
+ out.push_back(std::move(p));
+ }
+ return true;
+}
+// Writes encodePbrPngs' files beside `modelPath`.
+inline bool writePbrPngsBeside(const std::string& modelPath, const std::vector<PbrPng>& pngs, std::string& error) {
+ for (const PbrPng& p : pngs) {
+ const std::string path = textureUtf8(textureFsPath(modelPath).parent_path() / textureFsPath(p.name));
+ std::ofstream f(textureFsPath(path), std::ios::binary);
+ if (!f || !f.write(reinterpret_cast<const char*>(p.png.data()), std::streamsize(p.png.size()))) {
+ error = "Cannot write " + path;
+ return false;
+ }
+ }
+ return true;
+}
+inline const PbrPng* findPbrPng(const std::vector<PbrPng>& pngs, const std::string& slot) {
+ for (const PbrPng& p : pngs)
+ if (p.slot == slot) return &p;
+ return nullptr;
+}
+
} // namespace sf
diff --git a/src/io/UsdIO.cpp b/src/io/UsdIO.cpp
index e4f4647f..f2209063 100644
--- a/src/io/UsdIO.cpp
+++ b/src/io/UsdIO.cpp
@@ -306,18 +306,56 @@ void writeMaterial(Writer& w, const std::string& path, const std::string& name,
w.close();
}
-// A UsdPreviewSurface whose colour is the texture `file` (an asset path) on the "st" primvar.
-void writeTextureMaterial(Writer& w, const std::string& path, const std::string& name, const std::string& file) {
+// A UsdUVTexture reading `file` on the "st" primvar (raw data unless `srgb`); normal maps get scale 2, bias -1.
+void writeUvTexture(Writer& w, const std::string& path, const std::string& shader, const std::string& file, bool srgb,
+ bool normal, const char* output) {
+ w.s += '\n';
+ w.open("def Shader " + quoted(shader));
+ w.line("uniform token info:id = \"UsdUVTexture\"");
+ w.line("asset inputs:file = @" + file + "@");
+ w.line(std::string("token inputs:sourceColorSpace = \"") + (srgb ? "sRGB" : "raw") + "\"");
+ w.line("float2 inputs:st.connect = <" + path + "/TexCoords.outputs:result>");
+ w.line("token inputs:wrapS = \"repeat\"");
+ w.line("token inputs:wrapT = \"repeat\"");
+ if (normal) {
+ w.line("float4 inputs:scale = (2, 2, 2, 1)");
+ w.line("float4 inputs:bias = (-1, -1, -1, 0)");
+ }
+ w.line(output);
+ w.close();
+}
+
+// A UsdPreviewSurface whose colour is the texture `file` (an asset path) on the "st" primvar. `pbr`: material
+// channel maps (slot, asset path) for its other inputs (core/MapExport.h pbrSlots).
+void writeTextureMaterial(Writer& w, const std::string& path, const std::string& name, const std::string& file,
+ const std::vector<std::pair<std::string, std::string>>& pbr = {}) {
+ auto slotFile = [&](const char* slot) -> std::string {
+ for (const auto& [s, f] : pbr)
+ if (s == slot) return f;
+ return {};
+ };
w.open("def Material " + quoted(name));
w.line("token outputs:surface.connect = <" + path + "/PreviewSurface.outputs:surface>");
w.s += '\n';
w.open("def Shader \"PreviewSurface\"");
w.line("uniform token info:id = \"UsdPreviewSurface\"");
w.line("color3f inputs:diffuseColor.connect = <" + path + "/Texture.outputs:rgb>");
- w.line("float inputs:metallic = 0");
- w.line("float inputs:roughness = 0.65");
+ if (!slotFile("metallic").empty()) w.line("float inputs:metallic.connect = <" + path + "/MetallicTexture.outputs:r>");
+ else w.line("float inputs:metallic = 0");
+ if (!slotFile("roughness").empty()) w.line("float inputs:roughness.connect = <" + path + "/RoughnessTexture.outputs:r>");
+ else w.line("float inputs:roughness = 0.65");
+ if (!slotFile("normal").empty()) w.line("normal3f inputs:normal.connect = <" + path + "/NormalTexture.outputs:rgb>");
+ if (!slotFile("occlusion").empty()) w.line("float inputs:occlusion.connect = <" + path + "/OcclusionTexture.outputs:r>");
+ if (!slotFile("emissive").empty()) w.line("color3f inputs:emissiveColor.connect = <" + path + "/EmissiveTexture.outputs:rgb>");
+ if (!slotFile("opacity").empty()) w.line("float inputs:opacity.connect = <" + path + "/OpacityTexture.outputs:r>");
w.line("token outputs:surface");
w.close();
+ if (!slotFile("metallic").empty()) writeUvTexture(w, path, "MetallicTexture", slotFile("metallic"), false, false, "float outputs:r");
+ if (!slotFile("roughness").empty()) writeUvTexture(w, path, "RoughnessTexture", slotFile("roughness"), false, false, "float outputs:r");
+ if (!slotFile("normal").empty()) writeUvTexture(w, path, "NormalTexture", slotFile("normal"), false, true, "float3 outputs:rgb");
+ if (!slotFile("occlusion").empty()) writeUvTexture(w, path, "OcclusionTexture", slotFile("occlusion"), false, false, "float outputs:r");
+ if (!slotFile("emissive").empty()) writeUvTexture(w, path, "EmissiveTexture", slotFile("emissive"), true, false, "float3 outputs:rgb");
+ if (!slotFile("opacity").empty()) writeUvTexture(w, path, "OpacityTexture", slotFile("opacity"), false, false, "float outputs:r");
w.s += '\n';
w.open("def Shader \"Texture\"");
w.line("uniform token info:id = \"UsdUVTexture\"");
@@ -337,9 +375,11 @@ void writeTextureMaterial(Writer& w, const std::string& path, const std::string&
w.close();
}
-// `textures`: per mesh, the PNG asset path its material reads ("" = no texture).
+// `textures`: per mesh, the PNG asset path its material reads ("" = no texture). `pbr`: per mesh, its material
+// channel maps (slot, asset path).
std::string buildUsda(const std::vector<MeshObjectRef>& meshes, const std::vector<std::string>& textures,
- const SplatCloud* splats, const std::string& name, const MorphAnimation* animation) {
+ const SplatCloud* splats, const std::string& name, const MorphAnimation* animation,
+ const std::vector<std::vector<std::pair<std::string, std::string>>>& pbr) {
const std::string root = usdIdentifier(name.empty() ? "Sculpt" : name);
// Textured meshes bind a material of their own. Of the others, polypainted ones bind a material that
// reads their colours; with a mix, plain ones bind "Clay".
@@ -385,6 +425,7 @@ std::string buildUsda(const std::vector<MeshObjectRef>& meshes, const std::vecto
// One prim per object: "Sculpt" for a single one, else valid unique names from the objects.
std::set<std::string> used = {"Materials", "Splats"};
std::vector<std::pair<std::string, std::string>> textured; // material name, texture
+ std::vector<size_t> texturedMesh; // which mesh each textured material is for
for (size_t i = 0; i < meshes.size(); ++i) {
const MeshObjectRef& m = meshes[i];
std::string prim = "Sculpt";
@@ -397,6 +438,7 @@ std::string buildUsda(const std::vector<MeshObjectRef>& meshes, const std::vecto
std::string material = mixed && m.mesh->hasColors() ? paintedClay : clay;
if (!textures[i].empty()) {
textured.push_back({prim + "_Material", textures[i]});
+ texturedMesh.push_back(i);
material = "/" + root + "/Materials/" + textured.back().first;
}
writeMesh(w, *m.mesh, root, prim, material, animation);
@@ -410,7 +452,8 @@ std::string buildUsda(const std::vector<MeshObjectRef>& meshes, const std::vecto
}
for (size_t k = 0; k < textured.size(); ++k) {
if (plain || k) w.s += '\n';
- writeTextureMaterial(w, "/" + root + "/Materials/" + textured[k].first, textured[k].first, textured[k].second);
+ writeTextureMaterial(w, "/" + root + "/Materials/" + textured[k].first, textured[k].first, textured[k].second,
+ texturedMesh[k] < pbr.size() ? pbr[texturedMesh[k]] : std::vector<std::pair<std::string, std::string>>{});
}
w.close();
}
@@ -1049,7 +1092,18 @@ bool saveUsd(const std::string& path, const std::vector<MeshObjectRef>& meshesIn
}
// Textures: PNGs inside a .usdz package, else beside the layer; asset paths are relative to the layer.
const std::vector<std::string> pngs = textureFileNames(path, meshes);
- const std::string text = buildUsda(meshes, pngs, hasSplats ? splats : nullptr, name, animation);
+ // Material channel maps (PBR slots) per textured mesh, named after its colour PNG.
+ std::vector<std::vector<PbrPng>> pbrPngs(meshes.size());
+ std::vector<std::vector<std::pair<std::string, std::string>>> pbr(meshes.size());
+ for (size_t i = 0; i < meshes.size(); ++i) {
+ if (pngs[i].empty()) continue;
+ if (!encodePbrPngs(*meshes[i].mesh, false, pngs[i], pbrPngs[i])) {
+ error = "Cannot encode the material maps of " + meshes[i].name;
+ return false;
+ }
+ for (const PbrPng& p : pbrPngs[i]) pbr[i].push_back({p.slot, p.name});
+ }
+ const std::string text = buildUsda(meshes, pngs, hasSplats ? splats : nullptr, name, animation, pbr);
if (ext == ".usdz") {
std::string inner = usdIdentifier(name.empty() ? "Sculpt" : name) + ".usda";
std::vector<ZipEntry> entries = {{inner, std::vector<uint8_t>(text.begin(), text.end())}};
@@ -1060,12 +1114,14 @@ bool saveUsd(const std::string& path, const std::vector<MeshObjectRef>& meshesIn
error = "Cannot encode the texture of " + meshes[i].name;
return false;
}
+ for (const PbrPng& p : pbrPngs[i]) entries.push_back({p.name, p.png});
}
return writeStoredZip(path, entries, 64, error);
}
for (size_t i = 0; i < meshes.size(); ++i) {
std::string pngPath;
if (!pngs[i].empty() && !writeTextureBeside(path, pngs[i], *meshes[i].mesh, pngPath, error)) return false;
+ if (!writePbrPngsBeside(path, pbrPngs[i], error)) return false;
}
std::ofstream f(fsPath(path), std::ios::binary);
if (!f || !f.write(text.data(), std::streamsize(text.size()))) {
diff --git a/tests/test_map_export.cpp b/tests/test_map_export.cpp
new file mode 100644
index 00000000..41502dfa
--- /dev/null
+++ b/tests/test_map_export.cpp
@@ -0,0 +1,245 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Map export (core/MapExport.h): the preset format, every built-in preset's files and channel packing
+// (Unreal BC / N in DirectX / ORM, Unity URP and HDRP mask maps, glTF / Godot ORM, Blender and USD separate
+// maps), optional maps, 16-bit height, user preset files and the export_maps command.
+#include "TestHarness.h"
+
+#include "core/BakeImage.h"
+#include "core/Commands.h"
+#include "core/MapExport.h"
+#include "core/Primitives.h"
+#include "core/Texture.h"
+#include "core/TextureChannels.h"
+
+#include <cmath>
+#include <filesystem>
+#include <fstream>
+
+using namespace sf;
+
+namespace {
+
+namespace fs = std::filesystem;
+
+fs::path freshDir(const char* name) {
+ const fs::path dir = fs::temp_directory_path() / name;
+ std::error_code ec;
+ fs::remove_all(dir, ec);
+ return dir;
+}
+
+// A 64 texture: base colour (0.8, 0.4, 0.2) display, roughness 0.25, metallic 1, AO 0.5, a height ramp along x,
+// and a normal tilted towards +y.
+std::shared_ptr<PaintTexture> sampleTexture(bool height = true) {
+ auto t = makeTexture(64, 64);
+ for (size_t i = 0; i < t->pixels.size(); i += 4) t->pixels[i] = 204, t->pixels[i + 1] = 102, t->pixels[i + 2] = 51;
+ for (Channel c : {Channel::Roughness, Channel::Metallic, Channel::AO, Channel::Normal}) setChannelEnabled(*t, c, true);
+ if (height) setChannelEnabled(*t, Channel::Height, true);
+ t->heightNormalStrength = 0.0f; // the ramp shouldn't tilt the normals checked below
+ const glm::vec3 n = glm::normalize(glm::vec3(0, 0.5f, 1));
+ const float r[1] = {0.25f}, m[1] = {1.0f}, ao[1] = {0.5f}, nv[3] = {n.x * 0.5f + 0.5f, n.y * 0.5f + 0.5f, n.z * 0.5f + 0.5f};
+ for (int y = 0; y < 64; ++y)
+ for (int x = 0; x < 64; ++x) {
+ t->channels[size_t(Channel::Roughness)].base.setValues(x, y, r);
+ t->channels[size_t(Channel::Metallic)].base.setValues(x, y, m);
+ t->channels[size_t(Channel::AO)].base.setValues(x, y, ao);
+ t->channels[size_t(Channel::Normal)].base.setValues(x, y, nv);
+ if (height) {
+ const float h[1] = {float(x) / 63.0f};
+ t->channels[size_t(Channel::Height)].base.setValues(x, y, h);
+ }
+ }
+ return t;
+}
+
+int px(const Image& img, int x, int y, int c) { return img.rgba[(size_t(y) * size_t(img.width) + size_t(x)) * 4 + size_t(c)]; }
+bool near(int a, int b, int tol = 1) { return std::abs(a - b) <= tol; }
+
+} // namespace
+
+TEST(map_export_sources_parse) {
+ MapSource s;
+ std::string err;
+ CHECK(parseMapSource("roughness", s, err) && s.kind == MapSource::Kind::Channel && s.channel == int(Channel::Roughness));
+ CHECK(parseMapSource("smoothness", s, err) && s.channel == int(Channel::Roughness) && s.invert);
+ CHECK(parseMapSource("1-metallic", s, err) && s.invert && s.channel == int(Channel::Metallic));
+ CHECK(parseMapSource("base_color.g", s, err) && s.channel == 0 && s.component == 1);
+ CHECK(parseMapSource("base_color.a", s, err) && s.channel == int(Channel::Opacity));
+ CHECK(parseMapSource("normal.b", s, err) && s.component == 2);
+ CHECK(parseMapSource("opacity?", s, err) && s.dropIfMissing);
+ CHECK(parseMapSource("0.5", s, err) && s.kind == MapSource::Kind::Constant && s.constant == 0.5f);
+ CHECK(parseMapSource("1-0.25", s, err) && s.constant == 0.75f);
+ CHECK(!parseMapSource("sparkle", s, err) && !err.empty());
+ CHECK(!parseMapSource("roughness.g", s, err));
+ CHECK(!parseMapSource("", s, err));
+}
+
+TEST(map_export_builtin_presets) {
+ const auto& presets = builtinExportPresets();
+ CHECK(presets.size() == 7);
+ for (const char* id : {"unreal", "unity_urp", "unity_hdrp", "gltf", "godot", "blender", "usd"}) {
+ ExportPreset p;
+ std::string err;
+ CHECK(findExportPreset(id, p, err));
+ CHECK(p.id == id && !p.maps.empty() && !p.label.empty());
+ }
+ ExportPreset p;
+ std::string err;
+ CHECK(findExportPreset("UE", p, err) && p.id == "unreal" && p.normalDirectX);
+ CHECK(findExportPreset("hdrp", p, err) && p.id == "unity_hdrp");
+ CHECK(!findExportPreset("no_such_preset", p, err) && err.find("unreal") != std::string::npos);
+}
+
+TEST(map_export_unreal_packs_bc_n_orm) {
+ auto t = sampleTexture();
+ ExportPreset unreal, gltf;
+ std::string err;
+ CHECK(findExportPreset("unreal", unreal, err) && findExportPreset("gltf", gltf, err));
+ const fs::path dir = freshDir("sf_map_export_unreal");
+ std::vector<ExportedMap> files;
+ CHECK(exportMaps(*t, unreal, dir.string(), "Rock", files, err));
+ // BC, N, ORM and H (height is on); E is optional and emissive is off.
+ CHECK(files.size() == 4);
+ CHECK(fs::exists(dir / "T_Rock_BC.png") && fs::exists(dir / "T_Rock_N.png") && fs::exists(dir / "T_Rock_ORM.png"));
+ CHECK(fs::exists(dir / "T_Rock_H.png") && !fs::exists(dir / "T_Rock_E.png"));
+ Image bc, n, orm;
+ CHECK(Image::load((dir / "T_Rock_BC.png").string(), bc, err));
+ CHECK(near(px(bc, 5, 5, 0), 204) && near(px(bc, 5, 5, 1), 102) && px(bc, 5, 5, 3) == 255);
+ CHECK(Image::load((dir / "T_Rock_ORM.png").string(), orm, err));
+ CHECK(near(px(orm, 3, 3, 0), 128) && near(px(orm, 3, 3, 1), 64) && near(px(orm, 3, 3, 2), 255));
+ // DirectX normal: green flipped compared with glTF's OpenGL normal.
+ CHECK(Image::load((dir / "T_Rock_N.png").string(), n, err));
+ Image glN;
+ int ch = 0;
+ CHECK(renderMap(*t, gltf.maps[1], gltf.normalDirectX, glN, ch) && ch == 3);
+ CHECK(px(n, 7, 7, 1) < 128 && px(glN, 7, 7, 1) > 128);
+ CHECK(near(px(n, 7, 7, 1) + px(glN, 7, 7, 1), 255, 2));
+ CHECK(near(px(n, 7, 7, 2), px(glN, 7, 7, 2)));
+ // Height: 16-bit grey, the ramp kept to 16-bit precision.
+ int w = 0, h = 0, c = 0;
+ std::vector<uint16_t> hp;
+ CHECK(loadPng16((dir / "T_Rock_H.png").string(), w, h, c, hp, err));
+ CHECK(w == 64 && h == 64 && c == 1);
+ CHECK(hp[0] == 0 && hp[63] == 65535);
+ CHECK(std::abs(int(hp[31]) - int(std::lround(31.0 / 63.0 * 65535.0))) <= 2);
+ fs::remove_all(dir);
+}
+
+TEST(map_export_unity_godot_blender_usd) {
+ auto t = sampleTexture(false);
+ std::string err;
+ const fs::path dir = freshDir("sf_map_export_engines");
+ auto run = [&](const char* id, std::vector<ExportedMap>& files) {
+ ExportPreset p;
+ CHECK(findExportPreset(id, p, err));
+ CHECK(exportMaps(*t, p, (dir / id).string(), "Prop", files, err));
+ };
+ std::vector<ExportedMap> files;
+ // URP: metallic in R, smoothness (1 - roughness) in A.
+ run("unity_urp", files);
+ Image ms;
+ CHECK(Image::load((dir / "unity_urp" / "Prop_MetallicSmoothness.png").string(), ms, err));
+ CHECK(near(px(ms, 1, 1, 0), 255) && near(px(ms, 1, 1, 3), 191));
+ CHECK(fs::exists(dir / "unity_urp" / "Prop_Occlusion.png")); // AO is on
+ CHECK(!fs::exists(dir / "unity_urp" / "Prop_Height.png")); // height is off
+ // HDRP mask map: metallic, AO, detail mask (white), smoothness.
+ run("unity_hdrp", files);
+ Image mask;
+ CHECK(Image::load((dir / "unity_hdrp" / "Prop_MaskMap.png").string(), mask, err));
+ CHECK(near(px(mask, 2, 2, 0), 255) && near(px(mask, 2, 2, 1), 128) && px(mask, 2, 2, 2) == 255 && near(px(mask, 2, 2, 3), 191));
+ // Godot ORM.
+ run("godot", files);
+ CHECK(files.size() == 3 && fs::exists(dir / "godot" / "Prop_orm.png"));
+ // Blender: one file per channel, optional ones only when enabled.
+ run("blender", files);
+ CHECK(fs::exists(dir / "blender" / "Prop_Roughness.png") && fs::exists(dir / "blender" / "Prop_AO.png"));
+ CHECK(!fs::exists(dir / "blender" / "Prop_Emission.png") && !fs::exists(dir / "blender" / "Prop_Alpha.png"));
+ Image rough;
+ CHECK(Image::load((dir / "blender" / "Prop_Roughness.png").string(), rough, err));
+ CHECK(near(px(rough, 0, 0, 0), 64) && px(rough, 0, 0, 0) == px(rough, 0, 0, 2));
+ // USD names follow the UsdPreviewSurface inputs.
+ run("usd", files);
+ CHECK(fs::exists(dir / "usd" / "Prop_diffuseColor.png") && fs::exists(dir / "usd" / "Prop_occlusion.png"));
+ // A texture without material channels still exports, with the defaults (roughness 0.65, metallic 0).
+ auto plain = makeTexture(16, 16);
+ ExportPreset gltf;
+ CHECK(findExportPreset("gltf", gltf, err));
+ CHECK(exportMaps(*plain, gltf, (dir / "plain").string(), "P", files, err));
+ Image orm;
+ CHECK(Image::load((dir / "plain" / "P_occlusionRoughnessMetallic.png").string(), orm, err));
+ CHECK(px(orm, 0, 0, 0) == 255 && near(px(orm, 0, 0, 1), 166) && px(orm, 0, 0, 2) == 0);
+ fs::remove_all(dir);
+}
+
+TEST(map_export_opacity_goes_into_alpha_only_when_painted) {
+ auto t = sampleTexture(false);
+ ExportPreset unreal;
+ std::string err;
+ CHECK(findExportPreset("unreal", unreal, err));
+ Image bc;
+ int ch = 0;
+ CHECK(renderMap(*t, unreal.maps[0], true, bc, ch) && ch == 3);
+ setChannelEnabled(*t, Channel::Opacity, true);
+ const float a[1] = {0.25f};
+ t->channels[size_t(Channel::Opacity)].base.setValues(0, 63, a); // top row of the texture = first image row
+ CHECK(renderMap(*t, unreal.maps[0], true, bc, ch) && ch == 4);
+ CHECK(near(px(bc, 0, 0, 3), 64) && px(bc, 1, 0, 3) == 255);
+}
+
+TEST(map_export_user_preset_files) {
+ const fs::path dir = freshDir("sf_map_export_user");
+ fs::create_directories(dir);
+ const fs::path presetPath = dir / "studio.json";
+ {
+ std::ofstream f(presetPath);
+ f << R"({"label": "Studio", "file": "{name}-{map}", "normal": "directx",
+ "maps": [{"map": "rma", "channels": ["roughness", "metallic", "ao"]},
+ {"map": "gloss", "channels": ["1-roughness"]}]})";
+ }
+ ExportPreset p;
+ std::string err;
+ CHECK(findExportPreset(presetPath.string(), p, err));
+ CHECK(p.id == "studio" && p.maps.size() == 2 && p.normalDirectX);
+ auto t = sampleTexture(false);
+ std::vector<ExportedMap> files;
+ CHECK(exportMaps(*t, p, (dir / "out").string(), "My Rock", files, err));
+ CHECK(fs::exists(dir / "out" / "My_Rock-rma.png") && fs::exists(dir / "out" / "My_Rock-gloss.png"));
+ // Broken presets say what is wrong.
+ auto bad = [&](const char* json) {
+ ExportPreset q;
+ std::string why;
+ return !parseExportPreset(json, q, why) && !why.empty();
+ };
+ CHECK(bad("not json"));
+ CHECK(bad(R"({"maps": []})"));
+ CHECK(bad(R"({"file": "{name}", "maps": [{"map": "a", "channels": ["roughness"]}]})"));
+ CHECK(bad(R"({"maps": [{"map": "a", "channels": ["roughness", "metallic"]}]})"));
+ CHECK(bad(R"({"maps": [{"map": "a/b", "channels": ["roughness"]}]})"));
+ CHECK(bad(R"({"maps": [{"map": "a", "channels": ["glitter"]}]})"));
+ CHECK(bad(R"({"maps": [{"map": "a", "channels": ["height"], "bits": 12}]})"));
+ CHECK(bad(R"({"normal": "sideways", "maps": [{"map": "a", "channels": ["height"]}]})"));
+ fs::remove_all(dir);
+}
+
+TEST(map_export_command) {
+ Mesh m = makePlane(4);
+ m.uvs.assign(m.triangleCount() * 3, glm::vec2(0.5f));
+ m.texture = makeTexture(1024, 1024);
+ m.paintToTexture = true;
+ Document doc = makeDoc(std::move(m));
+ CommandRegistry reg;
+ const fs::path dir = freshDir("sf_map_export_cmd");
+ CHECK(reg.execute(doc, "texture_channels", {{"enable", std::string("roughness,metallic,normal")}}).ok);
+ const CommandResult r = reg.execute(doc, "export_maps", {{"preset", std::string("unreal")}, {"folder", dir.string()}, {"name", std::string("Lion")}});
+ CHECK(r.ok);
+ CHECK(r.message.find("3 Unreal Engine maps") != std::string::npos);
+ CHECK(fs::exists(dir / "T_Lion_BC.png") && fs::exists(dir / "T_Lion_N.png") && fs::exists(dir / "T_Lion_ORM.png"));
+ CHECK(reg.execute(doc, "export_maps", {{"list", true}}).message.find("unity_hdrp") != std::string::npos);
+ CHECK(!reg.execute(doc, "export_maps", {{"preset", std::string("nope")}, {"folder", dir.string()}}).ok);
+ CHECK(!reg.execute(doc, "export_maps", {}).ok);
+ Document plain = makeDoc(makePlane(2));
+ CHECK(!reg.execute(plain, "export_maps", {{"folder", dir.string()}}).ok);
+ fs::remove_all(dir);
+}
diff --git a/tests/test_texture_io.cpp b/tests/test_texture_io.cpp
index 3e28a704..cca20e16 100644
--- a/tests/test_texture_io.cpp
+++ b/tests/test_texture_io.cpp
@@ -398,3 +398,104 @@ TEST(texture_io_export_commands_write_textures) {
CHECK(checkPng(dir / "out_Body_color.png"));
fs::remove_all(dir);
}
+
+// --- PBR material slots from material channels (core/TextureChannels.h, core/MapExport.h) ---
+
+namespace {
+
+// The red-bottom texture with roughness, metallic, normal, AO, emissive and opacity painted in places.
+std::shared_ptr<PaintTexture> pbrTexture() {
+ auto t = redBottomTexture();
+ for (Channel c : {Channel::Roughness, Channel::Metallic, Channel::Normal, Channel::AO, Channel::Emissive, Channel::Opacity})
+ setChannelEnabled(*t, c, true);
+ const float rough[1] = {0.2f}, metal[1] = {1.0f}, alpha[1] = {0.5f};
+ for (int y = 0; y < 8; ++y)
+ for (int x = 0; x < 16; ++x) {
+ t->channels[size_t(Channel::Roughness)].base.setValues(x, y, rough);
+ t->channels[size_t(Channel::Metallic)].base.setValues(x, y, metal);
+ t->channels[size_t(Channel::Opacity)].base.setValues(x, y, alpha);
+ }
+ return t;
+}
+
+} // namespace
+
+TEST(texture_io_pbr_slots_in_gltf_usd_obj_fbx) {
+ const fs::path dir = testDir("sf_texture_io_pbr");
+ std::string err;
+ Mesh m = seamSphere();
+ m.texture = pbrTexture();
+
+ // glTF: ORM image on metallicRoughness and occlusion, normal, emissive, opacity -> BLEND.
+ CHECK(saveGlb(str(dir / "model.glb"), m, "Sculpt", err));
+ const std::string glb = readText(dir / "model.glb");
+ CHECK(glb.find("\"baseColorTexture\":{\"index\":0}") != std::string::npos);
+ CHECK(glb.find("\"metallicRoughnessTexture\":{\"index\":1},\"metallicFactor\":1,\"roughnessFactor\":1") != std::string::npos);
+ CHECK(glb.find("\"occlusionTexture\":{\"index\":1}") != std::string::npos);
+ CHECK(glb.find("\"normalTexture\":{\"index\":2}") != std::string::npos);
+ CHECK(glb.find("\"emissiveTexture\":{\"index\":3},\"emissiveFactor\":[1,1,1]") != std::string::npos);
+ CHECK(glb.find("\"alphaMode\":\"BLEND\"") != std::string::npos);
+ CHECK(glb.find("Sculpt_occlusionRoughnessMetallic") != std::string::npos);
+ CHECK(glb.find("\"materials\":[{") != std::string::npos);
+ Mesh back;
+ CHECK(loadGltf(str(dir / "model.glb"), back, err));
+
+ // USD: every UsdPreviewSurface input reads its own raw map; normal with scale / bias.
+ CHECK(saveUsd(str(dir / "model.usda"), &m, nullptr, "Sculpt", err));
+ const std::string usda = readText(dir / "model.usda");
+ CHECK(usda.find("float inputs:roughness.connect = </Sculpt/Materials/Sculpt_Material/RoughnessTexture.outputs:r>") != std::string::npos);
+ CHECK(usda.find("float inputs:metallic.connect") != std::string::npos);
+ CHECK(usda.find("normal3f inputs:normal.connect") != std::string::npos);
+ CHECK(usda.find("float inputs:occlusion.connect") != std::string::npos);
+ CHECK(usda.find("color3f inputs:emissiveColor.connect") != std::string::npos);
+ CHECK(usda.find("float inputs:opacity.connect") != std::string::npos);
+ CHECK(usda.find("@model_roughness.png@") != std::string::npos && usda.find("@model_normal.png@") != std::string::npos);
+ CHECK(usda.find("float4 inputs:bias = (-1, -1, -1, 0)") != std::string::npos);
+ CHECK(usda.find("token inputs:sourceColorSpace = \"raw\"") != std::string::npos);
+ Image color;
+ for (const char* f : {"model_color.png", "model_roughness.png", "model_metallic.png", "model_normal.png", "model_occlusion.png",
+ "model_emissive.png", "model_opacity.png"})
+ CHECK(fs::exists(dir / f) && Image::load(str(dir / f), color, err) && color.width == 16);
+ // The roughness map holds the painted value at the bottom (image rows top-down: the last row).
+ Image rough;
+ CHECK(Image::load(str(dir / "model_roughness.png"), rough, err));
+ CHECK(std::abs(int(rough.rgba[(size_t(rough.height - 1) * size_t(rough.width)) * 4]) - 51) <= 1);
+ CHECK(std::abs(int(rough.rgba[0]) - 166) <= 1);
+ // Base colour carries the opacity in alpha.
+ CHECK(Image::load(str(dir / "model_color.png"), color, err));
+ CHECK(std::abs(int(color.rgba[(size_t(color.height - 1) * size_t(color.width)) * 4 + 3]) - 128) <= 1);
+ CHECK(color.rgba[3] == 255);
+ // USDZ packs the maps.
+ CHECK(saveUsd(str(dir / "model.usdz"), &m, nullptr, "Sculpt", err));
+ std::vector<ZipEntry> entries;
+ CHECK(readStoredZip(str(dir / "model.usdz"), entries, err));
+ CHECK(entries.size() == 8);
+
+ // OBJ: the PBR MTL keys.
+ CHECK(saveObj(str(dir / "model.obj"), m, err));
+ const std::string mtl = readText(dir / "model.mtl");
+ CHECK(mtl.find("map_Pr model_roughness.png") != std::string::npos);
+ CHECK(mtl.find("map_Pm model_metallic.png") != std::string::npos);
+ CHECK(mtl.find("norm model_normal.png") != std::string::npos);
+ CHECK(mtl.find("map_Ke model_emissive.png") != std::string::npos);
+ CHECK(mtl.find("map_d model_opacity.png") != std::string::npos);
+
+ // FBX: maps on the material properties importers read.
+ CHECK(saveFbx(str(dir / "model.fbx"), "Sculpt", {&m}, FbxExportOptions{}, err));
+ const std::string fbx = readText(dir / "model.fbx");
+ for (const char* key : {"NormalMap", "ShininessExponent", "ReflectionFactor", "EmissiveColor", "TransparencyFactor",
+ "model_normal.png", "model_roughness.png"})
+ CHECK(fbx.find(key) != std::string::npos);
+
+ // A texture without material channels exports exactly as before (no extra maps).
+ Mesh plain = seamSphere();
+ plain.texture = redBottomTexture();
+ const fs::path pdir = testDir("sf_texture_io_pbr_plain");
+ CHECK(saveObj(str(pdir / "plain.obj"), plain, err));
+ CHECK(!fs::exists(pdir / "plain_roughness.png"));
+ CHECK(readText(pdir / "plain.mtl").find("map_Pr") == std::string::npos);
+ CHECK(saveGlb(str(pdir / "plain.glb"), plain, "Sculpt", err));
+ CHECK(readText(pdir / "plain.glb").find("\"metallicFactor\":0,\"roughnessFactor\":0.65") != std::string::npos);
+ fs::remove_all(dir);
+ fs::remove_all(pdir);
+}