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.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
Project format 7 for material channels, written only when a texture has them
islandmedfc898c0aff84
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 82d295f3..045c82c7 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -70,6 +70,7 @@ add_library(sculptforge_core STATICsrc/core/TileImage.cppsrc/core/TextureChannels.cppsrc/core/TextureChannelCommands.cpp+ src/core/LayerStackIO.cppsrc/core/Multires.cppsrc/core/MultiresCommands.cppsrc/core/AutoUv.cppdiff --git a/src/core/BakeImage.cpp b/src/core/BakeImage.cppindex 39b85169..55017fdb 100644--- a/src/core/BakeImage.cpp+++ b/src/core/BakeImage.cpp@@ -124,7 +124,28 @@ std::vector<std::pair<const char*, int>> exrChannels(int channels) {bool savePng16(const std::string& path, int width, int height, int channels, const std::vector<uint16_t>& px,std::string& error) {- if (width <= 0 || height <= 0 || (channels != 1 && channels != 3) ||+ std::vector<uint8_t> out;+ if (!encodePng16(width, height, channels, px, out, error)) return false;+ return writeFile(path, out, error);+}++bool decodePng16(const uint8_t* bytes, size_t size, int& width, int& height, int& channels, std::vector<uint16_t>& pixels,+ std::string& error, int wantChannels) {+ int w = 0, h = 0, n = 0;+ stbi_us* data = size > 0 && size < (size_t(1) << 31) ? stbi_load_16_from_memory(bytes, int(size), &w, &h, &n, wantChannels) : nullptr;+ if (!data) {+ error = "Cannot decode the 16-bit PNG";+ return false;+ }+ width = w, height = h, channels = wantChannels ? wantChannels : n;+ pixels.assign(data, data + size_t(w) * size_t(h) * size_t(channels));+ stbi_image_free(data);+ return true;+}++bool encodePng16(int width, int height, int channels, const std::vector<uint16_t>& px, std::vector<uint8_t>& out,+ std::string& error) {+ if (width <= 0 || height <= 0 || channels < 1 || channels > 4 ||px.size() != size_t(width) * size_t(height) * size_t(channels)) {error = "Bad 16-bit image";return false;@@ -150,16 +171,17 @@ bool savePng16(const std::string& path, int width, int height, int channels, conerror = "PNG compression failed";return false;}- std::vector<uint8_t> out = {0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n'};+ out = {0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n'};std::vector<uint8_t> ihdr;putBe32(ihdr, uint32_t(width));putBe32(ihdr, uint32_t(height));- ihdr.insert(ihdr.end(), {16, uint8_t(channels == 1 ? 0 : 2), 0, 0, 0});+ static const uint8_t kColorType[5] = {0, 0, 4, 2, 6}; // grey, grey + alpha, RGB, RGBA+ ihdr.insert(ihdr.end(), {16, kColorType[channels], 0, 0, 0});chunk(out, "IHDR", ihdr.data(), ihdr.size());chunk(out, "IDAT", z, size_t(zlen));std::free(z);chunk(out, "IEND", nullptr, 0);- return writeFile(path, out, error);+ return true;}bool loadPng16(const std::string& path, int& width, int& height, int& channels, std::vector<uint16_t>& pixels,diff --git a/src/core/BakeImage.h b/src/core/BakeImage.hindex 1fc82826..3b93d5c0 100644--- a/src/core/BakeImage.h+++ b/src/core/BakeImage.h@@ -15,6 +15,12 @@ namespace sf {// `channels` is 1 (grey) or 3 (RGB); `pixels` holds width * height * channels values.bool savePng16(const std::string& path, int width, int height, int channels, const std::vector<uint16_t>& pixels,std::string& error);+// The same PNG in memory; `channels` 1-4 (grey, grey + alpha, RGB, RGBA).+bool encodePng16(int width, int height, int channels, const std::vector<uint16_t>& pixels, std::vector<uint8_t>& out,+ std::string& error);+// Decodes PNG bytes at 16 bits per channel (8-bit files are scaled up), as `wantChannels` (0 = as stored).+bool decodePng16(const uint8_t* bytes, size_t size, int& width, int& height, int& channels, std::vector<uint16_t>& pixels,+ std::string& error, int wantChannels = 0);// Reads any PNG as 16 bits per channel (8-bit files are scaled up); `channels` is what the file has.bool loadPng16(const std::string& path, int& width, int& height, int& channels, std::vector<uint16_t>& pixels,std::string& error);diff --git a/src/core/LayerStackIO.cpp b/src/core/LayerStackIO.cppnew file mode 100644index 00000000..e5bbf3b6--- /dev/null+++ b/src/core/LayerStackIO.cpp@@ -0,0 +1,248 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+#include "core/LayerStackIO.h"++#include "core/Texture.h"+#include "core/TextureChannels.h"++#include <algorithm>+#include <cmath>+#include <cstdlib>+#include <cstring>++#define STBI_NO_STDIO+#include "stb_image.h"++extern "C" unsigned char* stbi_zlib_compress(unsigned char* data, int data_len, int* out_len, int quality);++namespace sf {++namespace {++constexpr uint32_t kMagic = 0x49544653; // "SFTI"+constexpr uint32_t kTileFormat = 1;++void put32(std::vector<uint8_t>& o, uint32_t v) {+ for (int b = 0; b < 4; ++b) o.push_back(uint8_t(v >> (8 * b)));+}+void put16(std::vector<uint8_t>& o, uint16_t v) {+ o.push_back(uint8_t(v));+ o.push_back(uint8_t(v >> 8));+}+uint32_t get32(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 get16(const uint8_t* p) { return uint16_t(p[0] | p[1] << 8); }++} // namespace++int textureFormatVersion(const PaintTexture& tex) { return hasMaterialChannels(tex) ? 7 : 6; }++std::vector<uint8_t> encodeTileImage(const TileImage& img) {+ std::vector<uint8_t> raw;+ put32(raw, kMagic);+ put32(raw, kTileFormat);+ put32(raw, uint32_t(img.width()));+ put32(raw, uint32_t(img.height()));+ raw.push_back(uint8_t(img.components()));+ raw.push_back(uint8_t(img.bits()));+ put16(raw, 0);+ for (uint16_t f : img.fill()) put16(raw, f);+ uint32_t listed = 0;+ for (size_t i = 0; i < img.tileCount(); ++i) listed += img.tile(i) != nullptr;+ put32(raw, listed);+ const size_t tb = size_t(img.texelBytes());+ for (size_t i = 0; i < img.tileCount(); ++i) {+ const TileImage::Tile* t = img.tile(i);+ if (!t) continue;+ put32(raw, uint32_t(i));+ raw.push_back(t->uniform ? 1 : 2);+ if (t->uniform) {+ for (uint16_t v : t->value) put16(raw, v);+ } else if (img.bits() == 16) {+ for (size_t k = 0; k + 1 < t->data.size(); k += 2) {+ uint16_t v;+ std::memcpy(&v, &t->data[k], 2);+ put16(raw, v);+ }+ } else {+ raw.insert(raw.end(), t->data.begin(), t->data.begin() + std::ptrdiff_t(kTileImageTexels * tb));+ }+ }+ int zlen = 0;+ unsigned char* z = stbi_zlib_compress(raw.data(), int(raw.size()), &zlen, 6);+ std::vector<uint8_t> out;+ put32(out, uint32_t(raw.size()));+ if (z) {+ out.insert(out.end(), z, z + zlen);+ std::free(z);+ }+ return out;+}++bool decodeTileImage(const std::vector<uint8_t>& bytes, TileImage& img, std::string& error) {+ const size_t tb = size_t(img.texelBytes());+ const size_t maxRaw = 40 + img.tileCount() * (5 + std::max<size_t>(8, size_t(kTileImageTexels) * tb));+ if (bytes.size() < 5) {+ error = "truncated channel image";+ return false;+ }+ const size_t rawSize = get32(bytes.data());+ if (rawSize < 32 || rawSize > maxRaw || bytes.size() - 4 > (size_t(1) << 31)) {+ error = "channel image has an impossible size";+ return false;+ }+ std::vector<uint8_t> raw(rawSize);+ const int got = stbi_zlib_decode_buffer(reinterpret_cast<char*>(raw.data()), int(rawSize),+ reinterpret_cast<const char*>(bytes.data() + 4), int(bytes.size() - 4));+ if (got != int(rawSize)) {+ error = "channel image does not decompress";+ return false;+ }+ const uint8_t* p = raw.data();+ if (get32(p) != kMagic || get32(p + 4) != kTileFormat || int(get32(p + 8)) != img.width() || int(get32(p + 12)) != img.height() ||+ p[16] != img.components() || p[17] != img.bits()) {+ error = "channel image has the wrong size or format";+ return false;+ }+ std::array<uint16_t, 4> fill;+ for (int k = 0; k < 4; ++k) fill[size_t(k)] = get16(p + 20 + k * 2);+ img.reset(img.width(), img.height(), img.components(), img.bits(), fill);+ const uint32_t listed = get32(p + 28);+ size_t at = 32;+ if (listed > img.tileCount()) {+ error = "channel image lists too many tiles";+ return false;+ }+ for (uint32_t k = 0; k < listed; ++k) {+ if (at + 5 > raw.size()) {+ error = "truncated channel image";+ return false;+ }+ const uint32_t index = get32(p + at);+ const uint8_t kind = p[at + 4];+ at += 5;+ if (index >= img.tileCount()) {+ error = "channel image tile out of range";+ return false;+ }+ if (kind == 1) {+ if (at + 8 > raw.size()) {+ error = "truncated channel image";+ return false;+ }+ std::array<uint16_t, 4> v;+ for (int c = 0; c < 4; ++c) v[size_t(c)] = get16(p + at + c * 2);+ if (img.bits() == 8)+ for (auto& x : v) x = std::min<uint16_t>(x, 255);+ img.fillTile(index, v);+ at += 8;+ } else if (kind == 2) {+ const size_t n = size_t(kTileImageTexels) * tb;+ if (at + n > raw.size()) {+ error = "truncated channel image";+ return false;+ }+ uint8_t* d = img.writableTile(index);+ if (img.bits() == 16) {+ for (size_t i = 0; i < n; i += 2) {+ const uint16_t v = get16(p + at + i);+ std::memcpy(d + i, &v, 2);+ }+ } else {+ std::memcpy(d, p + at, n);+ }+ at += n;+ } else {+ error = "channel image has an unknown tile kind";+ return false;+ }+ }+ return true;+}++Json writeTextureChannels(const PaintTexture& t, const std::string& prefix, const BlobWriter& write) {+ if (!hasMaterialChannels(t)) return Json();+ Json out = Json::object();+ out.set("height_normal_strength", double(t.heightNormalStrength));+ Json channels = Json::array();+ for (int c = 1; c < kChannelCount; ++c) {+ if (!channelEnabled(t, Channel(c))) continue;+ Json cj = Json::object();+ cj.set("channel", channelFormat(c).id);+ cj.set("base", write(prefix + "texture/pbr/" + channelFormat(c).id + ".sftiles", encodeTileImage(t.channels[size_t(c)].base)));+ channels.push(std::move(cj));+ }+ out.set("channels", std::move(channels));+ Json layers = Json::array();+ for (size_t li = 0; li < t.layers.size(); ++li) {+ const TextureLayer& l = t.layers[li];+ Json lj = Json::array();+ for (int c = 0; c < kChannelCount; ++c) {+ if (!channelEnabled(t, Channel(c))) continue;+ const LayerChannel& lc = l.channels[size_t(c)];+ Json cj = Json::object();+ cj.set("channel", channelFormat(c).id);+ cj.set("enabled", lc.enabled);+ if (c > 0) {+ cj.set("blend", channelBlendId(lc.blend));+ cj.set("opacity", double(lc.opacity));+ if (lc.image.valid() && !lc.image.empty())+ cj.set("image", write(prefix + "texture/pbr/" + std::to_string(li) + "_" + channelFormat(c).id + ".sftiles",+ encodeTileImage(lc.image)));+ }+ lj.push(std::move(cj));+ }+ layers.push(std::move(lj));+ }+ out.set("layers", std::move(layers));+ return out;+}++bool readTextureChannels(const Json& pbr, PaintTexture& t, const BlobReader& read, std::string& error) {+ if (!pbr.isObject()) return true;+ const double strength = pbr["height_normal_strength"].asNumber(4.0);+ t.heightNormalStrength = std::isfinite(strength) ? std::clamp(float(strength), 0.0f, 100.0f) : 4.0f;+ auto loadImage = [&](const Json& desc, TileImage& img, const char* what) {+ const size_t maxBytes = 64 + img.tileCount() * (16 + size_t(kTileImageTexels) * size_t(img.texelBytes())) * 2;+ std::vector<uint8_t> bytes;+ if (!read(desc, what, maxBytes, bytes)) {+ if (error.empty()) error = std::string("Project ") + what + " cannot be read";+ return false;+ }+ std::string why;+ if (!decodeTileImage(bytes, img, why)) {+ error = std::string("Project ") + what + ": " + why;+ return false;+ }+ return true;+ };+ for (size_t i = 0; i < pbr["channels"].size(); ++i) {+ const Json& cj = pbr["channels"][i];+ Channel c;+ if (!parseChannel(cj["channel"].asString(), c) || c == Channel::BaseColor) continue; // unknown: skip (newer file)+ setChannelEnabled(t, c, true);+ if (cj["base"].isObject() && !loadImage(cj["base"], t.channels[size_t(c)].base, "material channel")) return false;+ }+ syncLayerChannels(t);+ const Json& layers = pbr["layers"];+ for (size_t li = 0; li < layers.size() && li < t.layers.size(); ++li) {+ TextureLayer& l = t.layers[li];+ for (size_t k = 0; k < layers[li].size(); ++k) {+ const Json& cj = layers[li][k];+ Channel c;+ if (!parseChannel(cj["channel"].asString(), c) || !channelEnabled(t, c)) continue;+ LayerChannel& lc = l.channels[size_t(c)];+ lc.enabled = cj["enabled"].asBool(true);+ if (c == Channel::BaseColor) continue;+ uint8_t blend = 0;+ if (parseChannelBlend(cj["blend"].asString(), blend) && (blend != kBlendNormalCombine || c == Channel::Normal)) lc.blend = blend;+ const double o = cj["opacity"].asNumber(1.0);+ lc.opacity = std::isfinite(o) ? std::clamp(float(o), 0.0f, 1.0f) : 1.0f;+ if (cj["image"].isObject() && !loadImage(cj["image"], lc.image, "material layer channel")) return false;+ }+ }+ compositeChannels(t, 0, 0, t.width, t.height);+ t.markAllDirty();+ return true;+}++} // namespace sfdiff --git a/src/core/LayerStackIO.h b/src/core/LayerStackIO.hnew file mode 100644index 00000000..f620653a--- /dev/null+++ b/src/core/LayerStackIO.h@@ -0,0 +1,50 @@+// SculptForge - open source digital sculpting+// SPDX-License-Identifier: GPL-3.0-or-later+//+// Project IO for a texture's material channels (core/TextureChannels.h), kept out of core/Project.cpp so the+// project code only calls two hooks. Written under the texture's key "pbr" (project format 7):+//+// "pbr": { "height_normal_strength": 4,+// "channels": [ {"channel": "roughness", "base": <blob>}, ... ], // enabled channels+// "layers": [ [ {"channel": "roughness", "enabled": true, "blend": "multiply",+// "opacity": 1, "image": <blob or absent when transparent>}, ... ], ... ] }+//+// "layers" has one entry per texture layer (same order as the texture's "layers"); BaseColor's entry holds only+// "enabled". A blob is a TileImage in a small sparse format ("sftiles", zlib-compressed): only the tiles that+// aren't the fill are stored, uniform tiles as one value, so unpainted channels cost a few bytes.+//+// Readers that don't know "pbr" (format 6) ignore it and load the base colour. A project with no material+// channels writes no "pbr" key and stays format 6 (textureNeedsFormat7).+#pragma once++#include "core/Json.h"+#include "core/TileImage.h"++#include <cstdint>+#include <functional>+#include <string>+#include <vector>++namespace sf {++struct PaintTexture;++// The project format the texture's material data needs: 7 with material channels, else 6.+int textureFormatVersion(const PaintTexture& tex);++// Stores bytes as a project blob named `file` and returns its descriptor (Project.cpp's Writer::bytes).+using BlobWriter = std::function<Json(const std::string& file, const std::vector<uint8_t>& bytes)>;+// Reads the blob a descriptor names (at most `maxBytes`); false with the reader's error.+using BlobReader = std::function<bool(const Json& desc, const char* what, size_t maxBytes, std::vector<uint8_t>& out)>;++// The "pbr" object for the texture (null Json when it has no material channels). Blobs are named under `prefix`.+Json writeTextureChannels(const PaintTexture& tex, const std::string& prefix, const BlobWriter& write);+// Reads "pbr" into `tex` (already sized, with its layers). A missing key is fine; malformed data fails with `error`.+bool readTextureChannels(const Json& pbr, PaintTexture& tex, const BlobReader& read, std::string& error);++// The sparse tile encoding on its own (tests, tools).+std::vector<uint8_t> encodeTileImage(const TileImage& img);+// Decodes into `img`, which must already have the expected size and format; false when the bytes don't match.+bool decodeTileImage(const std::vector<uint8_t>& bytes, TileImage& img, std::string& error);++} // namespace sfdiff --git a/src/core/Project.cpp b/src/core/Project.cppindex eb4418dd..c82d5115 100644--- a/src/core/Project.cpp+++ b/src/core/Project.cpp@@ -4,6 +4,7 @@#include "core/Multires.h"+#include "core/LayerStackIO.h"#include "core/Texture.h"#include "core/ThreadPool.h"#include "core/ZSpheres.h"@@ -509,6 +510,12 @@ Json writeTexture(Writer& w, const std::string& prefix, const Mesh& m) {layers.push(std::move(l));}out.set("layers", std::move(layers));+ // Material channels (format 7, core/LayerStackIO.h); absent for a base-colour-only texture.+ if (Json pbr = writeTextureChannels(t, prefix, [&](const std::string& file, const std::vector<uint8_t>& bytes) {+ return w.bytes(file, bytes);+ });+ pbr.isObject())+ out.set("pbr", std::move(pbr));return out;}@@ -544,6 +551,15 @@ bool readTexture(Reader& r, const Json& tj, Mesh& m, std::string& error) {}for (size_t i = 3; i < (tex->layers.empty() ? tex->pixels : tex->base).size(); i += 4)(tex->layers.empty() ? tex->pixels : tex->base)[i] = 255; // Base is opaque+ if (!readTextureChannels(tj["pbr"], *tex,+ [&](const Json& desc, const char* what, size_t maxBytes, std::vector<uint8_t>& out) {+ const size_t n = countOf(desc["count"]);+ return n != size_t(-1) && n <= maxBytes && r.bytes(desc, what, n, out);+ },+ error)) {+ if (!r.error.empty()) error = r.error;+ return false;+ }tex->markAllDirty();m.texture = std::move(tex);m.paintToTexture = tj["paint_to_texture"].asBool(true);@@ -765,7 +781,8 @@ bool saveProject(const std::string& path, const Document& doc, std::string& erroWriter w;Json manifest = Json::object();manifest.set("format", kFormatName);- manifest.set("version", kProjectVersion);+ ProjectVersionNeed version; // the lowest format the content needs (set again once the SubTools are written)+ manifest.set("version", version.version);manifest.set("app_version", SCULPTFORGE_VERSION);// Every SubTool with its mesh, layers and state; blobs live under subtools/<i>/.@@ -781,8 +798,10 @@ bool saveProject(const std::string& path, const Document& doc, std::string& errost.set("active_layer", active ? doc.activeLayer : s.activeLayer);if (hasPaintLayers(doc.subtoolMesh(i)))st.set("paint_layers", writePaintLayers(w, "subtools/" + std::to_string(i) + "/", doc.subtoolMesh(i)));- if (doc.subtoolMesh(i).texture && doc.subtoolMesh(i).texture->width > 0)+ if (doc.subtoolMesh(i).texture && doc.subtoolMesh(i).texture->width > 0) {st.set("texture", writeTexture(w, "subtools/" + std::to_string(i) + "/", doc.subtoolMesh(i)));+ version.need(textureFormatVersion(*doc.subtoolMesh(i).texture));+ }if (subdivLevelCount(doc.subtoolMesh(i)))st.set("subdiv", writeSubdiv(w, "subtools/" + std::to_string(i) + "/", doc.subtoolMesh(i)));const std::string& gozName = active ? doc.gozName : s.gozName;@@ -842,6 +861,7 @@ bool saveProject(const std::string& path, const Document& doc, std::string& errofor (const auto& [key, value] : doc.projectSettings.members())if (!isCoreKey(key)) manifest.set(key, value);+ manifest.set("version", version.version);const std::string text = manifest.dump(true);w.entries.insert(w.entries.begin(), ZipEntry{kManifestName, std::vector<uint8_t>(text.begin(), text.end())});// The preview goes second, so loadProjectThumbnail finds it after reading two local headers.diff --git a/src/core/Project.h b/src/core/Project.hindex 4ad2eae5..9cc8e1d8 100644--- a/src/core/Project.h+++ b/src/core/Project.h@@ -24,8 +24,18 @@ namespace sf {// painted texture with layers ("texture"; older files still load). 4: SubTools may carry subdivision levels// ("subdiv"; older files still load). 5: sculpt-layer details of subdivision levels are in the levels' local// frames, not world space (format 4 files are converted when they load). 6: levels made by Divide keep no-// triangles, child maps or (where their positions say it) details; older files still load.-constexpr int kProjectVersion = 6;+// triangles, child maps or (where their positions say it) details; older files still load. 7: a SubTool texture+// may carry material channels (the texture's "pbr" key, core/LayerStackIO.h).+//+// kProjectVersion is the newest format this build reads. Saving writes the lowest version the content needs+// (ProjectVersionNeed): a project that uses nothing newer than format 6 is still written as 6, so older+// SculptForge versions keep opening it. A feature that needs a newer format calls need(N) while saving.+constexpr int kProjectVersion = 7;+constexpr int kProjectBaseWriteVersion = 6;+struct ProjectVersionNeed {+ int version = kProjectBaseWriteVersion;+ void need(int v) { version = v > version ? v : version; }+};constexpr const char* kProjectExtension = ".sfproj";// True for paths ending in .sfproj (any case).diff --git a/tests/test_malformed_files.cpp b/tests/test_malformed_files.cppindex 781f4f8d..dcf89d37 100644--- a/tests/test_malformed_files.cpp+++ b/tests/test_malformed_files.cpp@@ -9,10 +9,16 @@#include "core/Splats.h"#include "io/ObjIO.h"#include "io/PlyIO.h"+#include "core/LayerStackIO.h"+#include "core/Project.h"+#include "core/Primitives.h"+#include "core/Texture.h"+#include "io/Zip.h"#include <cmath>#include <filesystem>#include <fstream>+#include <functional>#include <string>using namespace sf;@@ -78,3 +84,138 @@ TEST(weld_handles_far_off_and_non_finite_positions) {const Mesh w = weldImported(m);CHECK(w.positions.size() <= m.positions.size()); // no crash or UB; duplicates may merge}++// --- Material channels (core/LayerStackIO.h): the sparse tile blobs and the project's "pbr" key ---++TEST(malformed_material_channel_blobs_are_rejected) {+ TileImage img;+ img.reset(256, 256, 1, 8, TileImage::toUnits(8, 0.5f));+ const float v[1] = {1.0f};+ img.setValues(3, 3, v);+ const std::vector<uint8_t> good = encodeTileImage(img);+ std::string err;+ TileImage out;+ out.reset(256, 256, 1, 8, {});+ CHECK(decodeTileImage(good, out, err));+ CHECK(out.sameTexels(img));+ auto rejects = [&](std::vector<uint8_t> bytes, TileImage target) {+ std::string why;+ const bool ok = decodeTileImage(bytes, target, why);+ return !ok && !why.empty();+ };+ TileImage same;+ same.reset(256, 256, 1, 8, {});+ CHECK(rejects({}, same));+ CHECK(rejects({1, 2, 3}, same));+ std::vector<uint8_t> truncated(good.begin(), good.begin() + std::ptrdiff_t(good.size() / 2));+ CHECK(rejects(truncated, same));+ std::vector<uint8_t> flipped = good;+ for (size_t i = 6; i < flipped.size(); i += 3) flipped[i] ^= 0x5A;+ CHECK(rejects(flipped, same));+ std::vector<uint8_t> huge = good;+ huge[0] = huge[1] = huge[2] = huge[3] = 0xFF; // claims a 4 GB payload+ CHECK(rejects(huge, same));+ TileImage other; // a different size or format than the file holds+ other.reset(512, 256, 1, 8, {});+ CHECK(rejects(good, other));+ TileImage deeper;+ deeper.reset(256, 256, 1, 16, {});+ CHECK(rejects(good, deeper));+}++TEST(malformed_material_channels_in_a_project_fail_cleanly) {+ Mesh m = makePlane(4);+ m.uvs.assign(m.triangleCount() * 3, glm::vec2(0.5f));+ for (size_t t = 0; t < m.triangleCount(); ++t) {+ m.uvs[t * 3] = glm::vec2(0, 0);+ m.uvs[t * 3 + 1] = glm::vec2(1, 0);+ m.uvs[t * 3 + 2] = glm::vec2(0, 1);+ }+ m.texture = makeTexture(1024, 1024);+ m.paintToTexture = true;+ setChannelEnabled(*m.texture, Channel::Roughness, true);+ const float v[1] = {0.1f};+ m.texture->channels[size_t(Channel::Roughness)].base.setValues(10, 10, v);+ addTextureLayer(*m.texture, "Layer 1");+ Document doc = makeDoc(std::move(m));+ const std::string path = tempPath("sf_malformed_pbr.sfproj");+ std::string err;+ CHECK(saveProject(path, doc, err));+ std::vector<ZipEntry> entries;+ CHECK(readStoredZip(path, entries, err));+ // A garbled channel blob: the load fails with a message and leaves the open document alone.+ for (auto& e : entries)+ if (e.name.find(".sftiles") != std::string::npos)+ for (size_t i = 4; i < e.data.size(); ++i) e.data[i] = uint8_t(i * 37);+ CHECK(writeStoredZip(path, entries, 64, err));+ Document keep = makeDoc(makePlane(2));+ const size_t tris = keep.mesh.triangleCount();+ err.clear();+ CHECK(!loadProject(path, keep, err));+ CHECK(!err.empty());+ CHECK(keep.mesh.triangleCount() == tris);+ // Unknown channel names, wrong types and absurd values in "pbr" are skipped or clamped.+ CHECK(saveProject(path, doc, err));+ entries.clear();+ CHECK(readStoredZip(path, entries, err));+ Json manifest;+ CHECK(Json::parse(std::string(entries[0].data.begin(), entries[0].data.end()), manifest, err));+ // Json is read-only through [], so edits copy the path down and set it back.+ auto editPbr = [&](const std::function<void(Json&)>& edit) {+ Json subtools = manifest["subtools"];+ Json st = subtools[0], tex = st["texture"], pbr = tex["pbr"];+ edit(pbr);+ tex.set("pbr", std::move(pbr));+ st.set("texture", std::move(tex));+ Json list = Json::array();+ list.push(std::move(st));+ for (size_t i = 1; i < subtools.size(); ++i) list.push(subtools[i]);+ manifest.set("subtools", std::move(list));+ };+ editPbr([](Json& pbr) {+ Json channels = pbr["channels"];+ Json extra = Json::object();+ extra.set("channel", "sparkle");+ channels.push(std::move(extra));+ pbr.set("channels", std::move(channels));+ pbr.set("height_normal_strength", -1e30);+ Json layers = pbr["layers"], first = layers[0];+ Json layerEntry = Json::object();+ layerEntry.set("channel", "roughness");+ layerEntry.set("blend", "normal_combine"); // only for normals: ignored+ layerEntry.set("opacity", "lots");+ first.push(std::move(layerEntry));+ Json newLayers = Json::array();+ newLayers.push(std::move(first));+ pbr.set("layers", std::move(newLayers));+ });+ const std::string text = manifest.dump(true);+ entries[0].data.assign(text.begin(), text.end());+ CHECK(writeStoredZip(path, entries, 64, err));+ Document back;+ CHECK(loadProject(path, back, err));+ CHECK(back.mesh.texture && channelEnabled(*back.mesh.texture, Channel::Roughness));+ CHECK(back.mesh.texture->heightNormalStrength == 0.0f);+ CHECK(back.mesh.texture->layers[0].channels[size_t(Channel::Roughness)].blend != kBlendNormalCombine);+ // A blob whose count is beyond what the texture could hold is refused before reading it.+ editPbr([](Json& pbr) {+ Json channels = Json::array();+ for (size_t i = 0; i < pbr["channels"].size(); ++i) {+ Json c = pbr["channels"][i];+ if (i == 0) {+ Json base = c["base"];+ base.set("count", 1e12);+ c.set("base", std::move(base));+ }+ channels.push(std::move(c));+ }+ pbr.set("channels", std::move(channels));+ });+ const std::string text2 = manifest.dump(true);+ entries[0].data.assign(text2.begin(), text2.end());+ CHECK(writeStoredZip(path, entries, 64, err));+ err.clear();+ CHECK(!loadProject(path, back, err));+ CHECK(!err.empty());+ std::filesystem::remove(path);+}diff --git a/tests/test_project.cpp b/tests/test_project.cppindex 556aba14..9a197558 100644--- a/tests/test_project.cpp+++ b/tests/test_project.cpp@@ -8,8 +8,10 @@#include "core/Commands.h"#include "core/Primitives.h"#include "core/Project.h"+#include "core/Texture.h"#include "io/Zip.h"+#include <cmath>#include <filesystem>using namespace sf;@@ -248,7 +250,8 @@ TEST(project_version_handling) {std::string err;CHECK(saveProject(path, doc, err));const std::string manifest = readManifest(path);- const std::string v = std::to_string(kProjectVersion);+ const std::string v = std::to_string(kProjectBaseWriteVersion); // nothing in it needs a newer format+ CHECK(kProjectVersion >= 7);CHECK(manifest.find("\"version\": " + v) != std::string::npos || manifest.find("\"version\":" + v) != std::string::npos);CHECK(manifest.find("app_version") != std::string::npos);@@ -370,3 +373,93 @@ TEST(project_save_adds_extension_to_any_other_extension) {CHECK(std::filesystem::exists(doc.path));std::filesystem::remove(doc.path);}++namespace {++// A plane with planar UVs and a 512 texture (texture tests have their own helpers; this one is enough here).+Document texturedDoc() {+ Mesh m = makePlane(8);+ const AABB b = m.bounds();+ m.uvs.resize(m.triangleCount() * 3);+ for (size_t t = 0; t < m.triangleCount(); ++t)+ 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 - b.min.x) / b.extent().x, (p.z - b.min.z) / b.extent().z);+ }+ m.texture = makeTexture(512, 512);+ m.paintToTexture = true;+ return makeDoc(std::move(m));+}++} // namespace++TEST(project_texture_without_material_channels_writes_format_6) {+ Document doc = texturedDoc();+ addTextureLayer(*doc.mesh.texture, "Layer 1");+ const std::string path = tempPath("sf_project_v6_texture.sfproj");+ std::string err;+ CHECK(saveProject(path, doc, err));+ Json manifest;+ CHECK(Json::parse(readManifest(path), manifest, err));+ CHECK(manifest["version"].asNumber() == 6);+ CHECK(!manifest["subtools"][0]["texture"].has("pbr"));+ // A format 6 texture project loads with no material channels.+ Document back;+ CHECK(loadProject(path, back, err));+ CHECK(back.mesh.texture && back.mesh.texture->layers.size() == 1 && !hasMaterialChannels(*back.mesh.texture));+ std::filesystem::remove(path);+}++TEST(project_material_channels_round_trip_as_format_7) {+ Document doc = texturedDoc();+ PaintTexture& t = *doc.mesh.texture;+ for (Channel c : {Channel::Roughness, Channel::Metallic, Channel::Normal, Channel::Height, Channel::Emissive}) setChannelEnabled(t, c, true);+ t.heightNormalStrength = 2.5f;+ const float rough[1] = {0.125f}, height[1] = {0.700012f};+ for (int y = 100; y < 180; ++y)+ for (int x = 100; x < 180; ++x) {+ t.channels[size_t(Channel::Roughness)].base.setValues(x, y, rough);+ t.channels[size_t(Channel::Height)].base.setValues(x, y, height);+ }+ addTextureLayer(t, "Scratches");+ LayerChannel& ln = t.layers[0].channels[size_t(Channel::Normal)];+ ln.blend = kBlendNormalCombine;+ ln.opacity = 0.75f;+ const float n4[4] = {0.7f, 0.5f, 0.9f, 1.0f};+ ln.image.setValues(300, 300, n4);+ t.layers[0].channels[size_t(Channel::Metallic)].enabled = false;+ t.layers[0].channels[0].enabled = false;+ compositeTextureAll(t);+ const std::string path = tempPath("sf_project_v7_pbr.sfproj");+ std::string err;+ CHECK(saveProject(path, doc, err));+ Json manifest;+ CHECK(Json::parse(readManifest(path), manifest, err));+ CHECK(manifest["version"].asNumber() == 7);+ CHECK(manifest["subtools"][0]["texture"]["pbr"]["channels"].size() == 5);+ Document back;+ CHECK(loadProject(path, back, err));+ const PaintTexture& b = *back.mesh.texture;+ CHECK(enabledChannelMask(b) == enabledChannelMask(t));+ CHECK(b.heightNormalStrength == 2.5f);+ for (Channel c : {Channel::Roughness, Channel::Metallic, Channel::Normal, Channel::Height, Channel::Emissive})+ CHECK(b.channels[size_t(c)].base.sameTexels(t.channels[size_t(c)].base));+ CHECK(std::abs(b.channels[size_t(Channel::Height)].base.value(150, 150) - 0.700012f) < 2e-5f); // 16 bits kept+ CHECK(b.layers.size() == 1);+ CHECK(b.layers[0].channels[size_t(Channel::Normal)].blend == kBlendNormalCombine);+ CHECK(b.layers[0].channels[size_t(Channel::Normal)].opacity == 0.75f);+ CHECK(!b.layers[0].channels[size_t(Channel::Metallic)].enabled);+ CHECK(!b.layers[0].channels[0].enabled);+ CHECK(b.layers[0].channels[size_t(Channel::Normal)].image.sameTexels(ln.image));+ CHECK(b.layers[0].channels[size_t(Channel::Roughness)].image.empty()); // transparent layer channels store nothing+ CHECK(channelImage(b, Channel::Normal).sameTexels(channelImage(t, Channel::Normal)));+ // Sparse: the unpainted channels cost a few bytes in the file.+ CHECK(std::filesystem::file_size(path) < 400 * 1024);+ // Turning every channel off goes back to format 6.+ for (Channel c : {Channel::Roughness, Channel::Metallic, Channel::Normal, Channel::Height, Channel::Emissive})+ setChannelEnabled(*back.mesh.texture, c, false);+ CHECK(saveProject(path, back, err));+ CHECK(Json::parse(readManifest(path), manifest, err));+ CHECK(manifest["version"].asNumber() == 6);+ std::filesystem::remove(path);+}diff --git a/tests/test_subtool_io.cpp b/tests/test_subtool_io.cppindex 7a6538a2..4c192423 100644--- a/tests/test_subtool_io.cpp+++ b/tests/test_subtool_io.cpp@@ -179,7 +179,7 @@ TEST(subtool_project_v2_round_trip) {CHECK(readStoredZip(path, entries, err));Json manifest;CHECK(!entries.empty() && Json::parse(std::string(entries[0].data.begin(), entries[0].data.end()), manifest, err));- CHECK(manifest["version"].asNumber() == kProjectVersion && manifest["subtools"].size() == 3);+ CHECK(manifest["version"].asNumber() == kProjectBaseWriteVersion && manifest["subtools"].size() == 3);CHECK(manifest["active_subtool"].asNumber() == 1 && !manifest.has("mesh"));CHECK(manifest["subtools"][1]["goz_name"].asString() == "Eye_ZB");