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.

Material channels for painted textures: sparse copy-on-write TileImage, Roughness/Metallic/Normal/Height/AO/Emissive/Opacity

islandmedc05cde966c6c
diff --git a/CMakeLists.txt b/CMakeLists.txt
index ff6dc1f0..82d295f3 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -67,6 +67,9 @@ add_library(sculptforge_core STATIC
src/core/PaintLayer.cpp
src/core/Texture.cpp
src/core/TextureCommands.cpp
+ src/core/TileImage.cpp
+ src/core/TextureChannels.cpp
+ src/core/TextureChannelCommands.cpp
src/core/Multires.cpp
src/core/MultiresCommands.cpp
src/core/AutoUv.cpp
diff --git a/src/core/Document.h b/src/core/Document.h
index 9ece67a3..347af152 100644
--- a/src/core/Document.h
+++ b/src/core/Document.h
@@ -10,6 +10,7 @@
#include "core/QRemeshGuides.h"
#include "core/Sculpt.h"
#include "core/Splats.h"
+#include "core/TextureChannels.h"
#include "core/Undo.h"
#include "core/Vdm.h"
@@ -79,6 +80,10 @@ struct Document {
int activeBrush = -1; // index into `brushes`, -1 = use a built-in brush type
BrushAlpha brushAlpha; // stamp shaping every brush's falloff (empty = round); brush_set_alpha
glm::vec3 paintColor{0.22f, 0.22f, 0.22f}; // current polypaint colour (linear RGB; see set_color); a mid grey
+ // Material texture painting (core/TextureChannels.h): what the Paint brush lays on the material channels
+ // (paint_material; its colour is paintColor), and the channel the view shows on its own (channel_view).
+ BrushMaterial paintMaterial;
+ Channel channelView = Channel::BaseColor;
// Vector displacement maps for the VDM brush (core/Vdm.h): the built-ins, then the studio and user
// library's .sfvdm files and any loaded this session. `brushVdm` is the one the VDM brush stamps.
std::vector<std::shared_ptr<const VectorDisplacement>> vdms = builtinVdms();
diff --git a/src/core/Polypaint.cpp b/src/core/Polypaint.cpp
index 1b6245d3..fcbc5b72 100644
--- a/src/core/Polypaint.cpp
+++ b/src/core/Polypaint.cpp
@@ -402,6 +402,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)
}
} // namespace sf
diff --git a/src/core/Texture.cpp b/src/core/Texture.cpp
index 00dccee9..8138479a 100644
--- a/src/core/Texture.cpp
+++ b/src/core/Texture.cpp
@@ -225,16 +225,161 @@ void dropStackIfEmpty(PaintTexture& t) {
if (t.base.size() == t.pixels.size()) t.pixels = t.base;
std::vector<uint8_t>().swap(t.base);
t.activeLayer = -1;
+ syncLayerChannels(t); // drops the channel composites
t.markAllDirty();
}
+static_assert(kTileImageTile == kTextureTile, "material channel tiles line up with the texture's undo tiles");
+
+// Writes paint of weight `w` into one texel of a material channel (n components of `bits`), starting from
+// `orig`: Base mixes towards `val` (erase: towards the channel's default); a layer paints "source over" onto its
+// coverage (component n), erase lowers the coverage. Normals are renormalised.
+inline void paintChannelTexel(uint8_t* dst, const uint8_t* orig, int n, int bits, bool layer, const float* val,
+ const float* def, float w, bool erase, bool normal) {
+ const int m = layer ? n + 1 : n;
+ float o[5], v[5];
+ if (bits == 16) {
+ for (int k = 0; k < m; ++k) {
+ uint16_t u;
+ std::memcpy(&u, orig + k * 2, 2);
+ o[k] = float(u) * (1.0f / 65535.0f);
+ }
+ } else {
+ for (int k = 0; k < m; ++k) o[k] = float(orig[k]) * (1.0f / 255.0f);
+ }
+ if (!layer) {
+ const float* to = erase ? def : val;
+ for (int k = 0; k < n; ++k) v[k] = o[k] + (to[k] - o[k]) * w;
+ } else if (erase) {
+ for (int k = 0; k < n; ++k) v[k] = o[k];
+ v[n] = o[n] * (1.0f - w);
+ } else {
+ const float a = o[n], na = a + w * (1.0f - a);
+ for (int k = 0; k < n; ++k) v[k] = na > 0.0f ? (o[k] * (a * (1.0f - w)) + val[k] * w) / na : val[k];
+ v[n] = na;
+ }
+ if (normal && n == 3) {
+ glm::vec3 d(v[0] * 2.0f - 1.0f, v[1] * 2.0f - 1.0f, v[2] * 2.0f - 1.0f);
+ const float len = glm::length(d);
+ d = len > 1e-6f ? d / len : glm::vec3(0, 0, 1);
+ v[0] = d.x * 0.5f + 0.5f, v[1] = d.y * 0.5f + 0.5f, v[2] = d.z * 0.5f + 0.5f;
+ }
+ if (bits == 16) {
+ for (int k = 0; k < m; ++k) {
+ const uint16_t u = uint16_t(std::clamp(v[k], 0.0f, 1.0f) * 65535.0f + 0.5f);
+ std::memcpy(dst + k * 2, &u, 2);
+ }
+ } else {
+ for (int k = 0; k < m; ++k) dst[k] = uint8_t(std::clamp(v[k], 0.0f, 1.0f) * 255.0f + 0.5f);
+ }
+}
+
+// A layer channel image made from a Base channel image (opaque coverage), for duplicating Base.
+TileImage layerImageFromBase(const TileImage& base) {
+ TileImage out;
+ if (!base.valid()) return out;
+ const int n = base.components(), bits = base.bits();
+ std::array<uint16_t, 4> fill = base.fill();
+ if (n < 4) fill[size_t(n)] = bits == 16 ? 65535 : 255;
+ out.reset(base.width(), base.height(), n + 1, bits, fill);
+ for (size_t ti = 0; ti < base.tileCount(); ++ti) {
+ const TileImage::Tile* t = base.tile(ti);
+ if (!t) continue; // stays the opaque fill
+ const int x0 = int(ti % size_t(base.tilesX())) * kTileImageTile, y0 = int(ti / size_t(base.tilesX())) * kTileImageTile;
+ for (int y = y0; y < std::min(y0 + kTileImageTile, base.height()); ++y)
+ for (int x = x0; x < std::min(x0 + kTileImageTile, base.width()); ++x) {
+ float v[5] = {0, 0, 0, 0, 0};
+ base.values(x, y, v);
+ v[n] = 1.0f;
+ out.setValues(x, y, v);
+ }
+ out.compactTile(ti);
+ }
+ return out;
+}
+
+// A layer channel merged onto a Base channel image (the lowest layer merging down).
+void mergeChannelIntoBase(TileImage& base, const TileImage& layer, float opacity, uint8_t blend, bool normal) {
+ if (!base.valid() || !layer.valid()) return;
+ const int n = base.components();
+ for (size_t ti = 0; ti < layer.tileCount(); ++ti) {
+ if (!layer.tile(ti)) continue;
+ const int x0 = int(ti % size_t(layer.tilesX())) * kTileImageTile, y0 = int(ti / size_t(layer.tilesX())) * kTileImageTile;
+ for (int y = y0; y < std::min(y0 + kTileImageTile, base.height()); ++y)
+ for (int x = x0; x < std::min(x0 + kTileImageTile, base.width()); ++x) {
+ float v[4] = {0, 0, 0, 0}, s[5] = {0, 0, 0, 0, 0};
+ base.values(x, y, v);
+ layer.values(x, y, s);
+ const float a = std::min(s[n] * opacity, 1.0f);
+ if (a <= 0.0f) continue;
+ if (normal && n == 3) {
+ const glm::vec3 b = glm::normalize(decodeNormal(v[0], v[1], v[2]) + glm::vec3(0, 0, 1e-6f));
+ const glm::vec3 d = glm::normalize(decodeNormal(s[0], s[1], s[2]) + glm::vec3(0, 0, 1e-6f));
+ const glm::vec3 r = blend == kBlendNormalCombine ? normalCombine(b, d) : d;
+ const glm::vec3 mixed = glm::normalize(b * (1.0f - a) + r * a + glm::vec3(0, 0, 1e-6f));
+ v[0] = mixed.x * 0.5f + 0.5f, v[1] = mixed.y * 0.5f + 0.5f, v[2] = mixed.z * 0.5f + 0.5f;
+ } else {
+ const BlendMode mode = blend < kBlendModeCount ? BlendMode(blend) : BlendMode::Normal;
+ const glm::vec3 bc = n == 1 ? glm::vec3(v[0]) : glm::vec3(v[0], v[1], v[2]);
+ const glm::vec3 sc = n == 1 ? glm::vec3(s[0]) : glm::vec3(s[0], s[1], s[2]);
+ const glm::vec3 o = glm::mix(bc, glm::clamp(blendColors(mode, bc, sc), 0.0f, 1.0f), a);
+ for (int k = 0; k < n; ++k) v[k] = o[k];
+ }
+ base.setValues(x, y, v);
+ }
+ base.compactTile(ti);
+ }
+}
+
+// A layer channel merged into the layer channel below it (keeping coverage, as the colour merge does).
+void mergeChannelIntoLayer(TileImage& low, float lowOpacity, const TileImage& up, float upOpacity, uint8_t blend, bool normal) {
+ if (!low.valid() || !up.valid()) return;
+ const int n = low.components() - 1;
+ for (size_t ti = 0; ti < low.tileCount(); ++ti) {
+ if (!up.tile(ti) && (!low.tile(ti) || lowOpacity == 1.0f)) continue;
+ const int x0 = int(ti % size_t(low.tilesX())) * kTileImageTile, y0 = int(ti / size_t(low.tilesX())) * kTileImageTile;
+ for (int y = y0; y < std::min(y0 + kTileImageTile, low.height()); ++y)
+ for (int x = x0; x < std::min(x0 + kTileImageTile, low.width()); ++x) {
+ float d[5] = {0, 0, 0, 0, 0}, s[5] = {0, 0, 0, 0, 0};
+ low.values(x, y, d);
+ up.values(x, y, s);
+ const float ab = std::min(d[n] * lowOpacity, 1.0f), as = std::min(s[n] * upOpacity, 1.0f);
+ if (as <= 0.0f) {
+ if (lowOpacity != 1.0f) {
+ d[n] = ab;
+ low.setValues(x, y, d);
+ }
+ continue;
+ }
+ const float ao = as + ab * (1.0f - as);
+ float mixed[3];
+ if (normal && n == 3) {
+ const glm::vec3 b = glm::normalize(decodeNormal(d[0], d[1], d[2]) + glm::vec3(0, 0, 1e-6f));
+ const glm::vec3 t = glm::normalize(decodeNormal(s[0], s[1], s[2]) + glm::vec3(0, 0, 1e-6f));
+ const glm::vec3 r = blend == kBlendNormalCombine ? normalCombine(b, t) : t;
+ mixed[0] = r.x * 0.5f + 0.5f, mixed[1] = r.y * 0.5f + 0.5f, mixed[2] = r.z * 0.5f + 0.5f;
+ } else {
+ const BlendMode mode = blend < kBlendModeCount ? BlendMode(blend) : BlendMode::Normal;
+ const glm::vec3 bc = n == 1 ? glm::vec3(d[0]) : glm::vec3(d[0], d[1], d[2]);
+ const glm::vec3 sc = n == 1 ? glm::vec3(s[0]) : glm::vec3(s[0], s[1], s[2]);
+ const glm::vec3 o = glm::clamp(blendColors(mode, bc, sc), 0.0f, 1.0f);
+ mixed[0] = o.x, mixed[1] = o.y, mixed[2] = o.z;
+ }
+ for (int k = 0; k < n; ++k) d[k] = (as * (1.0f - ab) * s[k] + as * ab * mixed[k] + (1.0f - as) * ab * d[k]) / ao;
+ d[n] = ao;
+ low.setValues(x, y, d);
+ }
+ low.compactTile(ti);
+ }
+}
+
// One texel of the composite: Base and the visible layers in display (sRGB) space, as compositePaintVertex.
inline void compositeTexel(const PaintTexture& t, size_t i, uint8_t* out) {
const uint8_t* b = &t.base[i * 4];
glm::vec3 c(0.0f);
bool blended = false;
for (const TextureLayer& l : t.layers) {
- if (!l.visible) continue;
+ if (!l.visible || !l.channels[0].enabled) continue; // channels[BaseColor]: the layer shows its colour
const uint8_t* s = &l.rgba[i * 4];
const float a = std::min(float(s[3]) / 255.0f * l.opacity, 1.0f);
if (a <= 0.0f) continue;
@@ -337,6 +482,8 @@ std::shared_ptr<PaintTexture> packTexture(const PaintTexture* t, const PaintText
shell->width = t->width;
shell->height = t->height;
shell->activeLayer = t->activeLayer;
+ shell->channels = t->channels; // material channels: copy-on-write tiles, shared until either side edits them
+ shell->heightNormalStrength = t->heightNormalStrength;
shell->layers.reserve(t->layers.size());
for (const TextureLayer& l : t->layers) {
TextureLayer s;
@@ -346,6 +493,7 @@ std::shared_ptr<PaintTexture> packTexture(const PaintTexture* t, const PaintText
s.blend = l.blend;
s.visible = l.visible;
s.locked = l.locked;
+ s.channels = l.channels;
shell->layers.push_back(std::move(s));
}
const int tilesX = tileCount(t->width), tilesY = tileCount(t->height);
@@ -382,6 +530,8 @@ std::shared_ptr<PaintTexture> unpackTexture(const PaintTexture& shell, const std
t->height = shell.height;
t->serial = gTextureSerial++;
t->activeLayer = shell.activeLayer;
+ t->channels = shell.channels;
+ t->heightNormalStrength = shell.heightNormalStrength;
t->layers = shell.layers;
const size_t n = t->texelCount() * 4, stride = size_t(t->width) * 4;
const int tilesX = tileCount(t->width);
@@ -471,7 +621,7 @@ std::vector<uint8_t>& PaintTexture::target(int layer) {
size_t PaintTexture::bytes() const {
size_t n = pixels.size() + base.size() + coverage.size() + sizeof(PaintTexture);
for (const auto& l : layers) n += l.rgba.size() + sizeof(TextureLayer);
- return n;
+ return n + channelBytes(*this);
}
std::shared_ptr<PaintTexture> makeTexture(int width, int height) {
@@ -540,6 +690,7 @@ void compositeTexture(PaintTexture& t, int x0, int y0, int x1, int y1) {
compositeTexel(t, i, &t.pixels[i * 4]);
}
});
+ compositeChannels(t, x0, y0, x1, y1);
}
t.markDirty(x0, y0, x1, y1);
}
@@ -579,7 +730,7 @@ glm::vec3 sampleTextureAt(const Mesh& m, uint32_t tri, const glm::vec3& point) {
// --- Brush ---
-bool TexturePainter::begin(Mesh& mesh) {
+bool TexturePainter::begin(Mesh& mesh, uint32_t channels) {
active_ = false;
tiles_.clear();
dab_ = 0;
@@ -587,7 +738,10 @@ bool TexturePainter::begin(Mesh& mesh) {
const PaintTexture& t = *mesh.texture;
layer_ = t.layers.empty() ? -1 : std::clamp(t.activeLayer, -1, int(t.layers.size()) - 1);
if (!textureLayerEditable(t, layer_)) return false;
+ channels_ = channels & enabledChannelMask(t);
+ if (!channels_) return false;
PaintTexture& tex = mutableTexture(mesh);
+ syncLayerChannels(tex); // every layer has an image for every enabled channel
ensureCoverage(mesh, tex);
tilesX_ = (tex.width + kTextureTile - 1) / kTextureTile;
tilesY_ = (tex.height + kTextureTile - 1) / kTextureTile;
@@ -598,7 +752,18 @@ bool TexturePainter::begin(Mesh& mesh) {
return true;
}
-TexturePainter::Tile& TexturePainter::tile(uint32_t index, const std::vector<uint8_t>& target, int width, int height) {
+TileImage* TexturePainter::channelTarget(PaintTexture& tex, int c) const {
+ if (c <= 0 || c >= kChannelCount || !(channels_ & (1u << c)) || !channelEnabled(tex, Channel(c))) return nullptr;
+ if (layer_ >= 0) {
+ if (layer_ >= int(tex.layers.size())) return nullptr;
+ TileImage& img = tex.layers[size_t(layer_)].channels[size_t(c)].image;
+ return img.valid() && img.width() == tex.width && img.height() == tex.height ? &img : nullptr;
+ }
+ return &tex.channels[size_t(c)].base;
+}
+
+TexturePainter::Tile& TexturePainter::tile(uint32_t index, const std::vector<uint8_t>& target, int width, int height,
+ PaintTexture& tex) {
if (Tile* made = tilePtr_[index].load(std::memory_order_acquire)) return *made;
std::lock_guard<std::mutex> lock(tileMutex_);
std::unique_ptr<Tile>& slot = tiles_[index];
@@ -614,6 +779,22 @@ TexturePainter::Tile& TexturePainter::tile(uint32_t index, const std::vector<uin
for (int y = 0; y < ch; ++y)
std::memcpy(&t.original[size_t(y) * kTextureTile * 4], &target[(size_t(ty + y) * size_t(width) + size_t(tx)) * 4],
size_t(cw) * 4);
+ // The material channels: keep the old tile for undo and make the image's tile writable.
+ for (int c = 1; c < kChannelCount; ++c) {
+ TileImage* img = channelTarget(tex, c);
+ if (!img) continue;
+ ChannelTile& ct = t.channels[size_t(c)];
+ ct.original = img->tilePtr(index);
+ if (ct.original && !ct.original->uniform) {
+ ct.origTexels = ct.original->data.data();
+ ct.origStride = img->texelBytes();
+ } else {
+ img->texel(tx, ty, ct.origValue); // the uniform value or the fill, as one raw texel
+ ct.origTexels = ct.origValue;
+ ct.origStride = 0;
+ }
+ ct.texels = img->writableTile(index);
+ }
tilePtr_[index].store(&t, std::memory_order_release);
return t;
}
@@ -623,11 +804,38 @@ TexturePainter::Tile& TexturePainter::tile(uint32_t index, const std::vector<uin
// texel lies in one band, so it sees exactly the writes it would get serially: the result doesn't depend on
// the thread count.
size_t TexturePainter::dab(Mesh& mesh, const BVH& bvh, const DabParams& p, const glm::vec3& color, Symmetry sym) {
+ BrushMaterial m;
+ m.color = color;
+ m.channels = channelBit(Channel::BaseColor);
+ return dab(mesh, bvh, p, m, sym);
+}
+
+size_t TexturePainter::dab(Mesh& mesh, const BVH& bvh, const DabParams& p, const BrushMaterial& material, Symmetry sym) {
if (!active_ || p.radius <= 0.0f || !hasTexture(mesh)) return 0;
PaintTexture& tex = mutableTexture(mesh);
if (!textureLayerEditable(tex, layer_) || (layer_ >= 0 && layer_ >= int(tex.layers.size()))) return 0;
std::vector<uint8_t>& target = tex.target(layer_);
const bool onLayer = layer_ >= 0;
+ const glm::vec3 color = material.color;
+ const uint32_t painted = channels_ & material.channels;
+ const bool paintColor = painted & 1u;
+ // The material channels this dab writes, with the brush's value and the channel's default (for erasing).
+ struct ChanJob {
+ int c, n, bits, tb;
+ bool normal;
+ float val[4], def[4];
+ };
+ std::vector<ChanJob> jobs;
+ for (int c = 1; c < kChannelCount; ++c) {
+ if (!(painted & (1u << c)) || !channelTarget(tex, c)) continue;
+ const ChannelFormat& f = channelFormat(c);
+ ChanJob j{c, f.components, f.bits, f.components * (f.bits == 16 ? 2 : 1) + (onLayer ? (f.bits == 16 ? 2 : 1) : 0),
+ c == int(Channel::Normal), {}, {}};
+ const std::array<float, 4> v = material.encoded(Channel(c));
+ for (int k = 0; k < 4; ++k) j.val[k] = v[size_t(k)], j.def[k] = f.defaultValue[size_t(k)];
+ jobs.push_back(j);
+ }
+ if (!paintColor && jobs.empty()) return 0;
const int w = tex.width, h = tex.height;
const float s = std::clamp(p.strength, 0.0f, 1.0f) * std::clamp(p.pressure, 0.0f, 1.0f);
if (s <= 0.0f) return 0;
@@ -745,7 +953,7 @@ size_t TexturePainter::dab(Mesh& mesh, const BVH& bvh, const DabParams& p, const
if (wgt <= 0.0f) return;
const uint32_t ti2 = uint32_t(y / kTextureTile) * uint32_t(tilesX_) + uint32_t(x / kTextureTile);
if (ti2 != cachedIndex) {
- cached = &tile(ti2, target, w, h);
+ cached = &tile(ti2, target, w, h, tex);
cachedIndex = ti2;
}
Tile& t = *cached;
@@ -754,14 +962,20 @@ size_t TexturePainter::dab(Mesh& mesh, const BVH& bvh, const DabParams& p, const
t.stamp[li] = mi.stamp;
float& acc = t.coverage[li];
acc += std::min(wgt, 1.0f) * (1.0f - acc);
- paintTexel(&target[(size_t(y) * size_t(w) + size_t(x)) * 4], &t.original[li * 4], onLayer, color, acc, p.invert);
+ if (paintColor)
+ paintTexel(&target[(size_t(y) * size_t(w) + size_t(x)) * 4], &t.original[li * 4], onLayer, color, acc, p.invert);
+ for (const ChanJob& j : jobs) {
+ const ChannelTile& ct = t.channels[size_t(j.c)];
+ paintChannelTexel(ct.texels + li * size_t(j.tb), ct.origTexels + li * size_t(ct.origStride), j.n, j.bits,
+ onLayer, j.val, j.def, acc, p.invert, j.normal);
+ }
res.lo = glm::min(res.lo, glm::ivec2(x, y));
res.hi = glm::max(res.hi, glm::ivec2(x + 1, y + 1));
++res.changed;
});
}
// With layers, the band recomposites its own changed rows (in parallel with the other bands).
- if (res.changed && !tex.layers.empty() && tex.base.size() == tex.pixels.size())
+ if (paintColor && res.changed && !tex.layers.empty() && tex.base.size() == tex.pixels.size())
for (int y = res.lo.y; y < res.hi.y; ++y)
for (int x = res.lo.x; x < res.hi.x; ++x) {
const size_t i = size_t(y) * size_t(w) + size_t(x);
@@ -773,6 +987,8 @@ size_t TexturePainter::dab(Mesh& mesh, const BVH& bvh, const DabParams& p, const
for (const BandResult& res : results)
if (res.changed) {
changed += res.changed;
+ if (!tex.layers.empty())
+ for (const ChanJob& j : jobs) compositeChannel(tex, Channel(j.c), res.lo.x, res.lo.y, res.hi.x, res.hi.y);
tex.markDirty(res.lo.x, res.lo.y, res.hi.x, res.hi.y);
}
return changed;
@@ -783,12 +999,31 @@ void TexturePainter::end(UndoRecord& record) {
auto u = std::make_unique<TextureTileUndo>();
u->layer = layer_;
u->texels.offsets.push_back(0);
- for (uint32_t i = 0; i < uint32_t(tiles_.size()); ++i)
- if (tiles_[i]) {
- u->texels.tiles.push_back(i);
- appendTile(u->texels, tiles_[i]->original.data(), size_t(kTextureTile) * 4, kTextureTile, kTextureTile);
+ bool any = false;
+ if (channels_ & 1u)
+ for (uint32_t i = 0; i < uint32_t(tiles_.size()); ++i)
+ if (tiles_[i]) {
+ u->texels.tiles.push_back(i);
+ appendTile(u->texels, tiles_[i]->original.data(), size_t(kTextureTile) * 4, kTextureTile, kTextureTile);
+ any = true;
+ }
+ // Material channels: one entry per (layer, channel) holding the tiles before the stroke.
+ for (int c = 1; c < kChannelCount; ++c) {
+ if (!(channels_ & (1u << c))) continue;
+ TextureChannelTiles ct;
+ ct.layer = layer_;
+ ct.channel = uint8_t(c);
+ for (uint32_t i = 0; i < uint32_t(tiles_.size()); ++i)
+ if (tiles_[i] && tiles_[i]->channels[size_t(c)].texels) {
+ ct.tiles.push_back(i);
+ ct.old.push_back(tiles_[i]->channels[size_t(c)].original);
+ }
+ if (!ct.tiles.empty()) {
+ u->channels.push_back(std::move(ct));
+ any = true;
}
- if (!u->texels.tiles.empty()) record.textureTiles = std::move(u);
+ }
+ if (any) record.textureTiles = std::move(u);
}
active_ = false;
tiles_.clear();
@@ -798,9 +1033,42 @@ void TexturePainter::end(UndoRecord& record) {
bandTris_.clear();
}
+size_t TextureChannelTiles::bytes() const {
+ size_t n = tiles.size() * sizeof(uint32_t) + old.size() * sizeof(old[0]);
+ for (const auto& t : old)
+ if (t) n += sizeof(*t) + t->data.size(); // shared with nothing once the image has moved on
+ return n;
+}
+
+size_t TextureTileUndo::bytes() const {
+ size_t n = texels.bytes();
+ for (const auto& c : channels) n += c.bytes();
+ return n;
+}
+
void TextureTileUndo::swapWith(Mesh& mesh) {
if (!mesh.texture) return;
PaintTexture& t = mutableTexture(mesh);
+ // Material channels: swap the tile pointers with the image's (the inverse step).
+ for (TextureChannelTiles& ct : channels) {
+ const Channel c = Channel(ct.channel);
+ if (ct.channel == 0 || ct.channel >= kChannelCount || !channelEnabled(t, c)) continue;
+ if (ct.layer >= 0) syncLayerChannels(t);
+ TileImage* img = ct.layer < 0 ? &t.channels[ct.channel].base
+ : ct.layer < int(t.layers.size()) ? &t.layers[size_t(ct.layer)].channels[ct.channel].image
+ : nullptr;
+ if (!img || !img->valid()) continue;
+ for (size_t i = 0; i < ct.tiles.size() && i < ct.old.size(); ++i) {
+ if (ct.tiles[i] >= img->tileCount()) continue;
+ TileImage::TilePtr now = img->tilePtr(ct.tiles[i]);
+ img->setTilePtr(ct.tiles[i], std::move(ct.old[i]));
+ ct.old[i] = std::move(now);
+ const int tx = int(ct.tiles[i] % uint32_t(img->tilesX())) * kTextureTile, ty = int(ct.tiles[i] / uint32_t(img->tilesX())) * kTextureTile;
+ if (!t.layers.empty()) compositeChannel(t, c, tx, ty, tx + kTextureTile, ty + kTextureTile);
+ t.markDirty(tx, ty, tx + kTextureTile, ty + kTextureTile);
+ }
+ }
+ if (texels.tiles.empty()) return;
if (!validTexLayer(t, layer) || (layer >= 0 && t.layers.empty())) return;
std::vector<uint8_t>& target = t.target(layer);
if (target.size() != t.texelCount() * 4) return;
@@ -844,7 +1112,12 @@ size_t TextureStackUndo::bytes() const {
if (!texture) return 0;
if (!committed) return texture->bytes();
size_t n = sizeof(PaintTexture);
- for (const auto& l : texture->layers) n += sizeof(TextureLayer) + l.name.size();
+ for (const auto& l : texture->layers) {
+ n += sizeof(TextureLayer) + l.name.size();
+ for (int c = 1; c < kChannelCount; ++c) n += l.channels[size_t(c)].image.uniqueBytes();
+ }
+ for (int c = 1; c < kChannelCount; ++c)
+ n += texture->channels[size_t(c)].base.uniqueBytes() + texture->channels[size_t(c)].composite.uniqueBytes();
for (const auto& p : planes) n += p.bytes() + sizeof(PackedTexels);
return n;
}
@@ -957,11 +1230,17 @@ bool loadTextureImage(PaintTexture& t, const Image& img, std::string& error) {
error = "The image is larger than 16384 pixels";
return false;
}
+ const uint32_t channels = enabledChannelMask(t);
t.width = img.width;
t.height = img.height;
t.layers.clear();
t.base.clear();
t.activeLayer = -1;
+ // The material channels start again at their defaults at the new size.
+ for (int c = 1; c < kChannelCount; ++c) {
+ t.channels[size_t(c)] = ChannelPlane();
+ if (channels & (1u << c)) setChannelEnabled(t, Channel(c), true);
+ }
t.coverage.clear();
t.coverageUvs = 0;
t.pixels.resize(img.rgba.size());
@@ -1007,6 +1286,8 @@ int addTextureLayer(PaintTexture& t, std::string name, int above) {
above = std::clamp(above, -1, int(t.layers.size()) - 1);
t.layers.insert(t.layers.begin() + (above + 1), std::move(l));
t.activeLayer = above + 1;
+ syncLayerChannels(t); // transparent material channels (null tiles: no texel memory)
+ compositeChannels(t, 0, 0, t.width, t.height);
return above + 1;
}
@@ -1018,6 +1299,8 @@ int duplicateTextureLayer(PaintTexture& t, int layer) {
copy.name = "Base";
copy.rgba = t.base;
for (size_t i = 3; i < copy.rgba.size(); i += 4) copy.rgba[i] = 255;
+ for (int c = 1; c < kChannelCount; ++c)
+ if (channelEnabled(t, Channel(c))) copy.channels[size_t(c)].image = layerImageFromBase(t.channels[size_t(c)].base);
} else {
copy = t.layers[size_t(layer)];
copy.id = newTextureLayerId();
@@ -1025,6 +1308,7 @@ int duplicateTextureLayer(PaintTexture& t, int layer) {
}
copy.name = uniqueTextureLayerName(t, copy.name + " copy");
t.layers.insert(t.layers.begin() + (layer + 1), std::move(copy));
+ syncLayerChannels(t);
t.activeLayer = layer + 1;
compositeTextureAll(t);
return layer + 1;
@@ -1060,6 +1344,23 @@ bool mergeTextureLayerDown(PaintTexture& t, int layer, std::string& error) {
return false;
}
const size_t n = t.texelCount();
+ // Material channels first (the colour merge below changes `low`'s opacity).
+ for (int c = 1; c < kChannelCount; ++c) {
+ if (!channelEnabled(t, Channel(c))) continue;
+ const LayerChannel& uc = up.channels[size_t(c)];
+ if (!up.visible || !uc.enabled || !uc.image.valid()) continue;
+ const bool normal = c == int(Channel::Normal);
+ if (layer == 0) {
+ mergeChannelIntoBase(t.channels[size_t(c)].base, uc.image, up.opacity * uc.opacity, uc.blend, normal);
+ } else {
+ TextureLayer& low = t.layers[size_t(layer - 1)];
+ if (low.locked || !low.visible) break; // refused below
+ LayerChannel& lc = low.channels[size_t(c)];
+ if (!lc.image.valid()) continue;
+ mergeChannelIntoLayer(lc.image, low.opacity * lc.opacity, uc.image, up.opacity * uc.opacity, uc.blend, normal);
+ lc.opacity = 1.0f;
+ }
+ }
if (layer == 0) {
if (up.visible)
parallelRows(t.height, n, [&](int b, int e) {
@@ -1112,12 +1413,22 @@ bool mergeTextureLayerDown(PaintTexture& t, int layer, std::string& error) {
void flattenTextureLayers(PaintTexture& t) {
if (t.layers.empty()) return;
compositeTextureAll(t);
+ for (int c = 1; c < kChannelCount; ++c)
+ if (channelEnabled(t, Channel(c))) t.channels[size_t(c)].base = channelImage(t, Channel(c));
t.layers.clear();
t.base = t.pixels;
dropStackIfEmpty(t);
}
void clearTextureLayer(PaintTexture& t, int layer) {
+ // Material channels go back to their default (Base) or to transparent (a layer) too.
+ for (int c = 1; c < kChannelCount; ++c) {
+ if (!channelEnabled(t, Channel(c))) continue;
+ TileImage* img = layer < 0 ? &t.channels[size_t(c)].base
+ : layer < int(t.layers.size()) ? &t.layers[size_t(layer)].channels[size_t(c)].image
+ : nullptr;
+ if (img && img->valid()) img->reset(img->width(), img->height(), img->components(), img->bits(), img->fill());
+ }
if (t.layers.empty()) {
std::fill(t.pixels.begin(), t.pixels.end(), uint8_t(255));
t.markAllDirty();
diff --git a/src/core/Texture.h b/src/core/Texture.h
index 1229300a..c8987969 100644
--- a/src/core/Texture.h
+++ b/src/core/Texture.h
@@ -31,6 +31,7 @@
#include "core/Mesh.h"
#include "core/PaintLayer.h"
#include "core/Sculpt.h"
+#include "core/TextureChannels.h"
#include <cstdint>
#include <atomic>
@@ -60,6 +61,7 @@ struct TextureLayer {
BlendMode blend = BlendMode::Normal;
bool visible = true;
bool locked = false; // locked layers can't be painted, filled, cleared or merged
+ LayerChannels channels; // material channels (core/TextureChannels.h); [BaseColor] only says whether colour shows
};
struct PaintTexture {
@@ -69,6 +71,18 @@ struct PaintTexture {
std::vector<uint8_t> base; // the Base layer while `layers` is not empty
std::vector<TextureLayer> layers;
int activeLayer = -1; // the layer painting writes into (-1 = Base)
+ // Material channels (core/TextureChannels.h): Roughness, Metallic, Normal, Height, AO, Emissive, Opacity.
+ ChannelPlanes channels;
+ float heightNormalStrength = 4.0f; // how steep the Height channel's normal is (heightNormalAt)
+ // Solo channel view (syncChannelView): what the renderer uploads instead of `pixels` while viewChannel is
+ // not BaseColor. A cache: not saved or undone.
+ std::vector<uint8_t> viewPixels;
+ Channel viewChannel = Channel::BaseColor;
+ uint64_t viewRevision = 0;
+ // The RGBA8 texels the viewport shows: the composite, or the solo channel.
+ const std::vector<uint8_t>& shown() const {
+ return viewChannel != Channel::BaseColor && viewPixels.size() == pixels.size() ? viewPixels : pixels;
+ }
// GPU sync (see Renderer): `revision` counts changes; texels changed since `dirtyFrom` lie in
// [dirtyMin, dirtyMax), inside the kTextureTile tiles flagged in `dirtyTiles`. A view that last uploaded
@@ -141,22 +155,42 @@ glm::vec3 sampleTextureAt(const Mesh& mesh, uint32_t triangle, const glm::vec3&
class TexturePainter {
public:
// False (and nothing starts) when the mesh doesn't paint into a texture or the target layer is locked/hidden.
- bool begin(Mesh& mesh);
+ // `channels`: channelBit(...) of what the stroke may paint (BaseColor and/or material channels; those the
+ // texture doesn't enable are dropped).
+ bool begin(Mesh& mesh, uint32_t channels = 1u);
+ uint32_t channels() const { return channels_; }
bool active() const { return active_; }
// Paints `color` (linear) under the brush, `p.invert` paints Base back to white / erases a layer.
// Returns the number of texels changed.
size_t dab(Mesh& mesh, const BVH& bvh, const DabParams& p, const glm::vec3& color, Symmetry sym);
+ // The same with a material: every channel the brush has and the texture enables gets its value (BaseColor
+ // only when `material.channels` has it), with the same falloff, coverage and undo.
+ size_t dab(Mesh& mesh, const BVH& bvh, const DabParams& p, const BrushMaterial& material, Symmetry sym);
// Ends the stroke: the touched tiles become `record.textureTiles` (nothing when no texel changed).
void end(UndoRecord& record);
private:
+ // A material channel the stroke paints in one tile: the tile before the stroke (kept for undo; null = the
+ // image's fill) and the writable texels.
+ struct ChannelTile {
+ TileImage::TilePtr original;
+ const uint8_t* origTexels = nullptr; // dense original texels, or one texel (origStride 0)
+ int origStride = 0; // bytes between texels of `origTexels` (0: uniform)
+ uint8_t origValue[8] = {}; // the original's texel when uniform / null
+ uint8_t* texels = nullptr; // the image's writable tile
+ };
struct Tile {
std::vector<uint8_t> original; // the tile before the stroke (kTextureTile^2 RGBA)
std::vector<float> coverage; // stroke coverage per texel
std::vector<uint32_t> stamp; // last dab that wrote the texel
+ std::array<ChannelTile, kChannelCount> channels; // [c] valid when the stroke paints channel c
};
+ // The images material channel c paints into (the target layer's or Base), null when the stroke doesn't paint c.
+ TileImage* channelTarget(PaintTexture& tex, int c) const;
+ uint32_t channels_ = 1u; // what the stroke paints (channelBit; BaseColor = bit 0)
// The tile's stroke record, made on first touch (thread-safe).
- Tile& tile(uint32_t index, const std::vector<uint8_t>& target, int width, int height);
+ // Also makes the tile of every material channel the stroke paints writable.
+ Tile& tile(uint32_t index, const std::vector<uint8_t>& target, int width, int height, PaintTexture& tex);
struct DabTri { // a triangle under the brush (mirror `mirror`), with the texel box the dab can reach
uint32_t tri = 0;
int mirror = 0;
diff --git a/src/core/TextureChannelCommands.cpp b/src/core/TextureChannelCommands.cpp
new file mode 100644
index 00000000..9f835a23
--- /dev/null
+++ b/src/core/TextureChannelCommands.cpp
@@ -0,0 +1,315 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Commands for material texture painting (core/TextureChannels.h): texture_channels, paint_material,
+// channel_view and texture_layer_channel.
+#include "core/Document.h"
+#include "core/Polypaint.h"
+#include "core/Texture.h"
+#include "core/TextureChannels.h"
+#include "core/Undo.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <sstream>
+
+namespace sf {
+
+namespace {
+
+using T = ParamSpec::Type;
+
+const char* kNoTexture = "The SubTool has no texture: create one first (Tool > Texture Map > New, or texture_create)";
+
+std::string channelList() {
+ std::string s;
+ for (int c = 0; c < kChannelCount; ++c) s += std::string(c ? ", " : "") + channelFormat(c).id;
+ return s;
+}
+
+// Splits "a, b c" into words.
+std::vector<std::string> words(const std::string& text) {
+ std::vector<std::string> out;
+ std::string cur;
+ for (char ch : text) {
+ if (ch == ',' || ch == ' ' || ch == ';') {
+ if (!cur.empty()) out.push_back(cur);
+ cur.clear();
+ } else {
+ cur += ch;
+ }
+ }
+ if (!cur.empty()) out.push_back(cur);
+ return out;
+}
+
+// Parses a channel list ("roughness,metallic", "all"); false + error for an unknown name.
+bool parseChannels(const std::string& text, uint32_t& mask, std::string& error) {
+ mask = 0;
+ for (const std::string& w : words(text)) {
+ if (w == "all") {
+ mask |= (1u << kChannelCount) - 1;
+ continue;
+ }
+ if (w == "none") continue;
+ Channel c;
+ if (!parseChannel(w, c)) {
+ error = "Unknown channel '" + w + "' (use " + channelList() + ")";
+ return false;
+ }
+ mask |= channelBit(c);
+ }
+ return true;
+}
+
+std::string megabytes(size_t bytes) {
+ char buf[32];
+ std::snprintf(buf, sizeof buf, "%.1f MB", double(bytes) / (1024.0 * 1024.0));
+ return buf;
+}
+
+std::string describeChannels(const PaintTexture& t) {
+ std::string s;
+ for (int c = 0; c < kChannelCount; ++c) {
+ if (!channelEnabled(t, Channel(c))) continue;
+ s += std::string(s.empty() ? "" : ", ") + channelFormat(c).label;
+ if (c > 0) {
+ const TileImage& img = t.channels[size_t(c)].base;
+ if (img.denseTiles()) s += " (" + std::to_string(img.denseTiles()) + " painted tiles)";
+ }
+ }
+ return s;
+}
+
+std::string describeMaterial(const Document& doc) {
+ const BrushMaterial& m = doc.paintMaterial;
+ std::ostringstream o;
+ o.setf(std::ios::fixed);
+ o.precision(2);
+ bool first = true;
+ auto add = [&](Channel c, const std::string& v) {
+ if (!(m.channels & channelBit(c))) return;
+ o << (first ? "" : ", ") << channelFormat(c).label << " " << v;
+ first = false;
+ };
+ add(Channel::BaseColor, colorToHex(doc.paintColor));
+ auto num = [](float x) {
+ char b[16];
+ std::snprintf(b, sizeof b, "%.2f", double(x));
+ return std::string(b);
+ };
+ add(Channel::Roughness, num(m.roughness));
+ add(Channel::Metallic, num(m.metallic));
+ add(Channel::Normal, "(" + num(m.normal.x) + ", " + num(m.normal.y) + ", " + num(m.normal.z) + ")");
+ add(Channel::Height, num(m.height));
+ add(Channel::AO, num(m.ao));
+ add(Channel::Emissive, colorToHex(m.emissive));
+ add(Channel::Opacity, num(m.opacity));
+ return first ? std::string("nothing (no channels)") : o.str();
+}
+
+// The texture layer named by "layer" / "index" (the active one by default); -2 + error if none.
+int layerArg(const PaintTexture& t, const Args& a, std::string& error) {
+ if (a.contains("layer")) {
+ const std::string name = argString(a, "layer");
+ const int i = findTextureLayer(t, name);
+ if (i == -2) error = "No texture layer called '" + name + "'";
+ return i;
+ }
+ if (a.contains("index")) {
+ const int i = int(argNumber(a, "index", -1));
+ if (i < -1 || i >= int(t.layers.size())) {
+ error = "No texture layer " + std::to_string(i);
+ return -2;
+ }
+ return i;
+ }
+ return t.activeLayer >= -1 && t.activeLayer < int(t.layers.size()) ? t.activeLayer : -1;
+}
+
+} // namespace
+
+void registerTextureChannelCommands(CommandRegistry& reg) {
+ reg.add({"texture_channels",
+ "Turn material channels of the active SubTool's texture on or off (PBR texture painting). Base colour is "
+ "always there; roughness, metallic, normal, height, ambient occlusion (ao), emissive and opacity can be "
+ "added. A new channel starts at its default everywhere and costs no memory until it is painted. Turning "
+ "one off discards what was painted in it (undoable). Without arguments, lists the channels.",
+ {{"enable", T::String, "Channels to turn on, e.g. \"roughness,metallic,normal\" or \"all\".", false},
+ {"disable", T::String, "Channels to turn off (their paint is discarded; undoable).", false},
+ {"height_normal_strength", T::Number,
+ "How steep the normal made from the height channel is (default 4; 0 = height adds no normal).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Mesh& m = doc.mesh;
+ if (!hasTexture(m)) return {false, kNoTexture};
+ uint32_t on = 0, off = 0;
+ std::string err;
+ if (!parseChannels(argString(a, "enable"), on, err) || !parseChannels(argString(a, "disable"), off, err))
+ return {false, err};
+ if ((off & 1u) && a.contains("disable")) return {false, "Base colour can't be turned off"};
+ const bool strength = a.contains("height_normal_strength");
+ if (!on && !off && !strength)
+ return {true, "Texture channels: " + describeChannels(*m.texture) + " (" +
+ megabytes(channelBytes(*m.texture)) + " of channel memory)"};
+ UndoRecord r = captureTexture(m, "Texture Channels");
+ PaintTexture& t = *m.texture;
+ bool changed = false;
+ for (int c = 1; c < kChannelCount; ++c) {
+ if (on & (1u << c)) changed |= setChannelEnabled(t, Channel(c), true);
+ if (off & (1u << c)) changed |= setChannelEnabled(t, Channel(c), false);
+ }
+ if (strength) {
+ const float s = std::clamp(float(argNumber(a, "height_normal_strength", 4.0)), 0.0f, 100.0f);
+ changed |= s != t.heightNormalStrength;
+ t.heightNormalStrength = s;
+ t.markAllDirty();
+ }
+ if (!changed) return {true, "Texture channels unchanged: " + describeChannels(t)};
+ if (!channelEnabled(t, doc.channelView)) doc.channelView = Channel::BaseColor;
+ finishTextureUndo(r, m);
+ doc.undo.push(std::move(r));
+ doc.modified = true;
+ return {true, "Texture channels: " + describeChannels(t)};
+ }});
+
+ reg.add({"paint_material",
+ "Set what the Paint brush lays down on a material texture: a value per channel. Giving a channel's value "
+ "adds that channel to the brush; `channels` says exactly which ones it paints (\"all\", \"none\", or a "
+ "list). Channels the texture hasn't turned on (texture_channels) are skipped when painting. Without "
+ "arguments, shows the brush material.",
+ {{"channels", T::String, "Exactly the channels the brush paints, e.g. \"base_color,roughness\" or \"all\".", false},
+ {"color", T::String, "Base colour (as set_color: #rrggbb, r,g,b or a name).", false},
+ {"roughness", T::Number, "0 (glossy) - 1 (rough).", false},
+ {"metallic", T::Number, "0 (dielectric) - 1 (metal).", false},
+ {"normal", T::String, "Tangent-space direction \"x,y,z\" (0,0,1 = flat).", false},
+ {"height", T::Number, "0 - 1 (0.5 = flat).", false},
+ {"ao", T::Number, "Ambient occlusion 0 (occluded) - 1 (open).", false},
+ {"emissive", T::String, "Emitted colour (#rrggbb...; black = none).", false},
+ {"opacity", T::Number, "0 (transparent) - 1 (opaque).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ BrushMaterial m = doc.paintMaterial;
+ glm::vec3 color = doc.paintColor;
+ uint32_t add = 0;
+ auto number = [&](const char* key, float& out, Channel c) {
+ if (!a.contains(key)) return;
+ out = std::clamp(float(argNumber(a, key, out)), 0.0f, 1.0f);
+ add |= channelBit(c);
+ };
+ if (a.contains("color")) {
+ if (!parseColor(argString(a, "color"), color)) return {false, "Unknown colour '" + argString(a, "color") + "'"};
+ add |= channelBit(Channel::BaseColor);
+ }
+ if (a.contains("emissive")) {
+ if (!parseColor(argString(a, "emissive"), m.emissive))
+ return {false, "Unknown colour '" + argString(a, "emissive") + "'"};
+ add |= channelBit(Channel::Emissive);
+ }
+ number("roughness", m.roughness, Channel::Roughness);
+ number("metallic", m.metallic, Channel::Metallic);
+ number("height", m.height, Channel::Height);
+ number("ao", m.ao, Channel::AO);
+ number("opacity", m.opacity, Channel::Opacity);
+ if (a.contains("normal")) {
+ float x = 0, y = 0, z = 1;
+ if (std::sscanf(argString(a, "normal").c_str(), "%f , %f , %f", &x, &y, &z) != 3 ||
+ glm::length(glm::vec3(x, y, z)) < 1e-6f)
+ return {false, "normal must be \"x,y,z\", e.g. 0,0,1"};
+ m.normal = glm::normalize(glm::vec3(x, y, z));
+ add |= channelBit(Channel::Normal);
+ }
+ m.channels |= add;
+ if (a.contains("channels")) {
+ std::string err;
+ if (!parseChannels(argString(a, "channels"), m.channels, err)) return {false, err};
+ }
+ doc.paintMaterial = m;
+ doc.paintColor = color;
+ doc.paintMaterial.color = color;
+ std::string note;
+ if (hasTexture(doc.mesh)) {
+ const uint32_t skipped = m.channels & ~enabledChannelMask(*doc.mesh.texture);
+ for (int c = 1; c < kChannelCount; ++c)
+ if (skipped & (1u << c)) note += std::string(note.empty() ? "" : ", ") + channelFormat(c).id;
+ if (!note.empty()) note = " (not on this texture: " + note + "; texture_channels enable=...)";
+ }
+ return {true, "Brush material: " + describeMaterial(doc) + note};
+ }});
+
+ reg.add({"channel_view",
+ "Show one material channel of the textures on its own in the viewport (roughness, metallic, ao, height "
+ "and opacity as greyscale, normal as its colours, emissive as colour), or go back to the normal view "
+ "(off / base_color). Only changes what the view shows.",
+ {{"channel", T::String, "A channel name, or off.", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const std::string name = argString(a, "channel");
+ Channel c = Channel::BaseColor;
+ if (name != "off" && name != "none" && !parseChannel(name, c))
+ return {false, "Unknown channel '" + name + "' (use " + channelList() + " or off)"};
+ if (c != Channel::BaseColor) {
+ if (!hasTexture(doc.mesh)) return {false, kNoTexture};
+ if (!channelEnabled(*doc.mesh.texture, c))
+ return {false, std::string("The texture has no ") + channelFormat(c).label +
+ " channel (texture_channels enable=" + channelFormat(c).id + ")"};
+ }
+ doc.channelView = c;
+ for (int i = 0; i < doc.subtoolCount(); ++i)
+ if (const Mesh& m = doc.subtoolMesh(i); m.texture) syncChannelView(*m.texture, c);
+ return {true, c == Channel::BaseColor ? std::string("Showing the textures as they are")
+ : std::string("Showing the ") + channelFormat(c).label + " channel"};
+ }});
+
+ reg.add({"texture_layer_channel",
+ "Per-channel settings of a texture layer: whether the layer affects a material channel, the channel's "
+ "blend mode (the paint layer modes, plus normal_combine for normals) and its opacity (multiplied by the "
+ "layer's). For base_color, enabled hides or shows the layer's colour only.",
+ {{"channel", T::String, "The channel (roughness, normal, base_color, ...).", true},
+ {"layer", T::String, "Layer name (default: the active layer).", false},
+ {"index", T::Number, "Layer index instead of a name (0 = lowest above Base).", false},
+ {"enabled", T::Bool, "The layer affects this channel.", false},
+ {"blend", T::String, "Blend mode: normal, multiply, screen, overlay, ..., normal_combine.", false},
+ {"opacity", T::Number, "0 - 1.", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ Mesh& m = doc.mesh;
+ if (!hasTexture(m)) return {false, kNoTexture};
+ Channel c;
+ if (!parseChannel(argString(a, "channel"), c)) return {false, "Unknown channel (use " + channelList() + ")"};
+ if (!channelEnabled(*m.texture, c))
+ return {false, std::string("The texture has no ") + channelFormat(c).label + " channel"};
+ std::string err;
+ const int i = layerArg(*m.texture, a, err);
+ if (i == -2) return {false, err};
+ if (i < 0) return {false, "Base has no channel settings; add a layer"};
+ uint8_t blend = layerChannelBlend(*m.texture, i, c);
+ if (a.contains("blend")) {
+ if (!parseChannelBlend(argString(a, "blend"), blend)) return {false, "Unknown blend mode"};
+ if (blend == kBlendNormalCombine && c != Channel::Normal)
+ return {false, "normal_combine is for the normal channel"};
+ if (c == Channel::BaseColor && blend >= kBlendModeCount) return {false, "Unknown blend mode"};
+ }
+ UndoRecord r = captureTexture(m, "Texture Layer Channel");
+ PaintTexture& t = *m.texture;
+ syncLayerChannels(t);
+ TextureLayer& l = t.layers[size_t(i)];
+ LayerChannel& lc = l.channels[size_t(c)];
+ lc.enabled = argBool(a, "enabled", lc.enabled);
+ const float opacity = std::clamp(float(argNumber(a, "opacity", layerChannelOpacity(t, i, c))), 0.0f, 1.0f);
+ if (c == Channel::BaseColor) {
+ l.blend = BlendMode(blend);
+ l.opacity = opacity;
+ } else {
+ lc.blend = blend;
+ lc.opacity = opacity;
+ }
+ compositeTextureAll(t);
+ finishTextureUndo(r, m);
+ doc.undo.push(std::move(r));
+ doc.modified = true;
+ char buf[160];
+ std::snprintf(buf, sizeof buf, "Layer '%s' %s: %s, %s, %d%%", l.name.c_str(), channelFormat(c).label,
+ lc.enabled ? "on" : "off", channelBlendLabel(blend), int(std::lround(opacity * 100.0f)));
+ return {true, buf};
+ }});
+}
+
+} // namespace sf
diff --git a/src/core/TextureChannels.cpp b/src/core/TextureChannels.cpp
new file mode 100644
index 00000000..4f5233ee
--- /dev/null
+++ b/src/core/TextureChannels.cpp
@@ -0,0 +1,464 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/TextureChannels.h"
+
+#include "core/Document.h"
+#include "core/Mesh.h"
+#include "core/Polypaint.h"
+#include "core/Texture.h"
+#include "core/ThreadPool.h"
+#include "core/Undo.h"
+
+#include <algorithm>
+#include <cctype>
+#include <cmath>
+#include <cstdio>
+#include <cstring>
+
+namespace sf {
+
+namespace {
+
+const ChannelFormat kFormats[kChannelCount] = {
+ {"base_color", "Base Color", "BC", 4, 8, true, {1, 1, 1, 1}},
+ {"roughness", "Roughness", "R", 1, 8, false, {0.65f, 0, 0, 0}},
+ {"metallic", "Metallic", "M", 1, 8, false, {0, 0, 0, 0}},
+ {"normal", "Normal", "N", 3, 8, false, {0.5f, 0.5f, 1.0f, 0}},
+ {"height", "Height", "H", 1, 16, false, {0.5f, 0, 0, 0}},
+ {"ao", "Ambient Occlusion", "AO", 1, 8, false, {1, 0, 0, 0}},
+ {"emissive", "Emissive", "E", 3, 8, true, {0, 0, 0, 0}},
+ {"opacity", "Opacity", "Op", 1, 8, false, {1, 0, 0, 0}},
+};
+
+std::string squash(const std::string& s) {
+ std::string out;
+ for (char c : s)
+ if (std::isalnum(static_cast<unsigned char>(c))) out += char(std::tolower(static_cast<unsigned char>(c)));
+ return out;
+}
+
+float srgbToLinear(float x) { return x <= 0.04045f ? x / 12.92f : std::pow((x + 0.055f) / 1.055f, 2.4f); }
+float linearToSrgbValue(float x) {
+ x = std::clamp(x, 0.0f, 1.0f);
+ return x <= 0.0031308f ? x * 12.92f : 1.055f * std::pow(x, 1.0f / 2.4f) - 0.055f;
+}
+
+// Format of a layer's channel image: the channel's components plus coverage.
+void resetLayerImage(TileImage& img, const PaintTexture& tex, Channel c) {
+ const ChannelFormat& f = channelFormat(c);
+ const auto d = f.defaultValue;
+ std::array<uint16_t, 4> fill = TileImage::toUnits(f.bits, d[0], d[1], d[2], d[3]);
+ fill[size_t(f.components)] = 0; // transparent
+ img.reset(tex.width, tex.height, f.components + 1, f.bits, fill);
+}
+
+void resetBaseImage(TileImage& img, const PaintTexture& tex, Channel c) {
+ const ChannelFormat& f = channelFormat(c);
+ const auto d = f.defaultValue;
+ img.reset(tex.width, tex.height, f.components, f.bits, TileImage::toUnits(f.bits, d[0], d[1], d[2], d[3]));
+}
+
+inline void readUnits(const uint8_t* p, int comps, int bits, float* out) {
+ if (bits == 16) {
+ for (int k = 0; k < comps; ++k) {
+ uint16_t v;
+ std::memcpy(&v, p + k * 2, 2);
+ out[k] = float(v) * (1.0f / 65535.0f);
+ }
+ } else {
+ for (int k = 0; k < comps; ++k) out[k] = float(p[k]) * (1.0f / 255.0f);
+ }
+}
+inline void writeUnits(uint8_t* p, int comps, int bits, const float* v) {
+ if (bits == 16) {
+ for (int k = 0; k < comps; ++k) {
+ const uint16_t u = uint16_t(std::lround(std::clamp(v[k], 0.0f, 1.0f) * 65535.0f));
+ std::memcpy(p + k * 2, &u, 2);
+ }
+ } else {
+ for (int k = 0; k < comps; ++k) p[k] = uint8_t(std::lround(std::clamp(v[k], 0.0f, 1.0f) * 255.0f));
+ }
+}
+
+// One layer of a channel blended over `v` (n components, 0..1) with weight a.
+inline void blendOver(float* v, const float* s, int n, uint8_t blend, float a, bool normal) {
+ if (normal && n == 3) {
+ const glm::vec3 b = glm::normalize(decodeNormal(v[0], v[1], v[2]));
+ const glm::vec3 d = glm::normalize(decodeNormal(s[0], s[1], s[2]));
+ const glm::vec3 r = blend == kBlendNormalCombine ? normalCombine(b, d) : d;
+ glm::vec3 m = b * (1.0f - a) + r * a;
+ const float len = glm::length(m);
+ m = len > 1e-6f ? m / len : glm::vec3(0, 0, 1);
+ v[0] = m.x * 0.5f + 0.5f, v[1] = m.y * 0.5f + 0.5f, v[2] = m.z * 0.5f + 0.5f;
+ return;
+ }
+ const BlendMode mode = blend < kBlendModeCount ? BlendMode(blend) : BlendMode::Normal;
+ if (n == 1) {
+ const float o = std::clamp(blendColors(mode, glm::vec3(v[0]), glm::vec3(s[0])).x, 0.0f, 1.0f);
+ v[0] += (o - v[0]) * a;
+ return;
+ }
+ const glm::vec3 o = glm::clamp(blendColors(mode, glm::vec3(v[0], v[1], v[2]), glm::vec3(s[0], s[1], s[2])), 0.0f, 1.0f);
+ for (int k = 0; k < 3; ++k) v[k] += (o[k] - v[k]) * a;
+}
+
+int tileOf(int x) { return x / kTileImageTile; }
+
+} // namespace
+
+// --- Formats and names ---
+
+const ChannelFormat& channelFormat(Channel c) { return kFormats[std::clamp(int(c), 0, kChannelCount - 1)]; }
+
+bool parseChannel(const std::string& text, Channel& out) {
+ const std::string s = squash(text);
+ static const struct {
+ const char* name;
+ Channel c;
+ } aliases[] = {{"color", Channel::BaseColor}, {"colour", Channel::BaseColor}, {"basecolour", Channel::BaseColor},
+ {"albedo", Channel::BaseColor}, {"bc", Channel::BaseColor}, {"rough", Channel::Roughness},
+ {"metal", Channel::Metallic}, {"metalness", Channel::Metallic}, {"occlusion", Channel::AO},
+ {"ambientocclusion", Channel::AO}, {"emission", Channel::Emissive}, {"emit", Channel::Emissive},
+ {"alpha", Channel::Opacity}, {"bump", Channel::Height}, {"displacement", Channel::Height},
+ {"normals", Channel::Normal}};
+ for (int i = 0; i < kChannelCount; ++i)
+ if (s == squash(kFormats[i].id) || s == squash(kFormats[i].label)) {
+ out = Channel(i);
+ return true;
+ }
+ for (const auto& a : aliases)
+ if (s == a.name) {
+ out = a.c;
+ return true;
+ }
+ return false;
+}
+
+const char* channelBlendId(uint8_t blend) {
+ return blend == kBlendNormalCombine ? "normal_combine" : blendModeId(BlendMode(std::min<int>(blend, kBlendModeCount - 1)));
+}
+const char* channelBlendLabel(uint8_t blend) {
+ return blend == kBlendNormalCombine ? "Normal Combine" : blendModeLabel(BlendMode(std::min<int>(blend, kBlendModeCount - 1)));
+}
+bool parseChannelBlend(const std::string& text, uint8_t& out) {
+ const std::string s = squash(text);
+ if (s == "normalcombine" || s == "rnm" || s == "combine") {
+ out = kBlendNormalCombine;
+ return true;
+ }
+ BlendMode m;
+ if (!parseBlendMode(text, m)) return false;
+ out = uint8_t(m);
+ return true;
+}
+
+std::array<float, 4> BrushMaterial::encoded(Channel c) const {
+ switch (c) {
+ case Channel::BaseColor:
+ return {linearToSrgbValue(color.x), linearToSrgbValue(color.y), linearToSrgbValue(color.z), 1.0f};
+ case Channel::Roughness: return {std::clamp(roughness, 0.0f, 1.0f), 0, 0, 0};
+ case Channel::Metallic: return {std::clamp(metallic, 0.0f, 1.0f), 0, 0, 0};
+ case Channel::Normal: {
+ const float len = glm::length(normal);
+ const glm::vec3 n = len > 1e-6f ? normal / len : glm::vec3(0, 0, 1);
+ return {n.x * 0.5f + 0.5f, n.y * 0.5f + 0.5f, n.z * 0.5f + 0.5f, 0};
+ }
+ case Channel::Height: return {std::clamp(height, 0.0f, 1.0f), 0, 0, 0};
+ case Channel::AO: return {std::clamp(ao, 0.0f, 1.0f), 0, 0, 0};
+ case Channel::Emissive:
+ return {linearToSrgbValue(emissive.x), linearToSrgbValue(emissive.y), linearToSrgbValue(emissive.z), 0};
+ case Channel::Opacity: return {std::clamp(opacity, 0.0f, 1.0f), 0, 0, 0};
+ }
+ return {0, 0, 0, 0};
+}
+
+// --- Texture-level state ---
+
+bool channelEnabled(const PaintTexture& t, Channel c) {
+ if (c == Channel::BaseColor) return true;
+ const ChannelPlane& p = t.channels[size_t(c)];
+ return p.enabled && p.base.valid() && p.base.width() == t.width && p.base.height() == t.height;
+}
+
+bool hasMaterialChannels(const PaintTexture& t) {
+ for (int c = 1; c < kChannelCount; ++c)
+ if (channelEnabled(t, Channel(c))) return true;
+ return false;
+}
+
+uint32_t enabledChannelMask(const PaintTexture& t) {
+ uint32_t m = 1;
+ for (int c = 1; c < kChannelCount; ++c)
+ if (channelEnabled(t, Channel(c))) m |= 1u << c;
+ return m;
+}
+
+const TileImage& channelImage(const PaintTexture& t, Channel c) {
+ const ChannelPlane& p = t.channels[size_t(c)];
+ if (!t.layers.empty() && p.composite.valid() && p.composite.width() == t.width && p.composite.height() == t.height)
+ return p.composite;
+ return p.base;
+}
+
+void syncLayerChannels(PaintTexture& t) {
+ for (TextureLayer& l : t.layers)
+ for (int c = 1; c < kChannelCount; ++c) {
+ LayerChannel& lc = l.channels[size_t(c)];
+ if (!channelEnabled(t, Channel(c))) {
+ lc.image.clear();
+ continue;
+ }
+ const ChannelFormat& f = channelFormat(c);
+ if (!lc.image.valid() || lc.image.width() != t.width || lc.image.height() != t.height ||
+ lc.image.components() != f.components + 1 || lc.image.bits() != f.bits)
+ resetLayerImage(lc.image, t, Channel(c));
+ }
+ for (int c = 1; c < kChannelCount; ++c) {
+ ChannelPlane& p = t.channels[size_t(c)];
+ if (t.layers.empty() || !channelEnabled(t, Channel(c))) p.composite.clear();
+ }
+}
+
+bool setChannelEnabled(PaintTexture& t, Channel c, bool on) {
+ if (c == Channel::BaseColor) return false;
+ ChannelPlane& p = t.channels[size_t(c)];
+ if (on == channelEnabled(t, c)) return false;
+ if (on) {
+ p.enabled = true;
+ resetBaseImage(p.base, t, c);
+ } else {
+ p = ChannelPlane();
+ }
+ syncLayerChannels(t);
+ compositeChannel(t, c, 0, 0, t.width, t.height);
+ t.markAllDirty();
+ return true;
+}
+
+uint8_t layerChannelBlend(const PaintTexture& t, int layer, Channel c) {
+ if (layer < 0 || layer >= int(t.layers.size())) return 0;
+ const TextureLayer& l = t.layers[size_t(layer)];
+ return c == Channel::BaseColor ? uint8_t(l.blend) : l.channels[size_t(c)].blend;
+}
+
+float layerChannelOpacity(const PaintTexture& t, int layer, Channel c) {
+ if (layer < 0 || layer >= int(t.layers.size())) return 1.0f;
+ const TextureLayer& l = t.layers[size_t(layer)];
+ return c == Channel::BaseColor ? l.opacity : l.channels[size_t(c)].opacity;
+}
+
+// --- Compositing ---
+
+void compositeChannel(PaintTexture& t, Channel c, int x0, int y0, int x1, int y1) {
+ if (c == Channel::BaseColor || !channelEnabled(t, c)) return;
+ ChannelPlane& p = t.channels[size_t(c)];
+ if (t.layers.empty()) {
+ p.composite.clear();
+ return;
+ }
+ x0 = std::max(x0, 0), y0 = std::max(y0, 0), x1 = std::min(x1, t.width), y1 = std::min(y1, t.height);
+ if (x0 >= x1 || y0 >= y1) return;
+ const ChannelFormat& f = channelFormat(c);
+ if (!p.composite.valid() || p.composite.width() != t.width || p.composite.height() != t.height) {
+ p.composite = p.base; // shares every tile; the covered ones are redone below
+ x0 = y0 = 0, x1 = t.width, y1 = t.height;
+ }
+ // The layers that can show in this channel.
+ struct Src {
+ const TileImage* img;
+ float opacity;
+ uint8_t blend;
+ };
+ std::vector<Src> srcs;
+ for (const TextureLayer& l : t.layers) {
+ const LayerChannel& lc = l.channels[size_t(c)];
+ const float o = l.opacity * lc.opacity;
+ if (!l.visible || !lc.enabled || o <= 0.0f || !lc.image.valid() || lc.image.width() != t.width) continue;
+ srcs.push_back({&lc.image, o, lc.blend});
+ }
+ const int tx0 = tileOf(x0), ty0 = tileOf(y0), tx1 = tileOf(x1 - 1), ty1 = tileOf(y1 - 1);
+ const int tw = tx1 - tx0 + 1, tilesX = p.base.tilesX();
+ const int n = f.components, bits = f.bits, tb = p.base.texelBytes(), lb = tb + (bits == 16 ? 2 : 1);
+ const bool normal = c == Channel::Normal;
+ poolFor(size_t(tw) * size_t(ty1 - ty0 + 1), [&](size_t b, size_t e) {
+ std::vector<const Src*> live;
+ for (size_t k = b; k < e; ++k) {
+ const int tx = tx0 + int(k % size_t(tw)), ty = ty0 + int(k / size_t(tw));
+ const size_t ti = size_t(ty) * size_t(tilesX) + size_t(tx);
+ live.clear();
+ for (const Src& s : srcs)
+ if (s.img->tile(ti)) live.push_back(&s); // null layer tiles are transparent
+ if (live.empty()) {
+ p.composite.setTilePtr(ti, p.base.tilePtr(ti));
+ continue;
+ }
+ uint8_t* out = p.composite.writableTile(ti);
+ const int ax = std::max(x0, tx * kTileImageTile), bx = std::min(x1, (tx + 1) * kTileImageTile);
+ const int ay = std::max(y0, ty * kTileImageTile), by = std::min(y1, (ty + 1) * kTileImageTile);
+ uint8_t scratch[8];
+ for (int y = ay; y < by; ++y)
+ for (int x = ax; x < bx; ++x) {
+ float v[4], s[5];
+ readUnits(p.base.texel(x, y, scratch), n, bits, v);
+ for (const Src* src : live) {
+ readUnits(src->img->texel(x, y, scratch), n + 1, bits, s);
+ const float a = std::min(s[n] * src->opacity, 1.0f);
+ if (a <= 0.0f) continue;
+ blendOver(v, s, n, src->blend, a, normal);
+ }
+ writeUnits(out + (size_t(y % kTileImageTile) * kTileImageTile + size_t(x % kTileImageTile)) * size_t(tb), n, bits, v);
+ }
+ (void)lb;
+ }
+ }, 1, 2);
+}
+
+void compositeChannels(PaintTexture& t, int x0, int y0, int x1, int y1) {
+ for (int c = 1; c < kChannelCount; ++c) compositeChannel(t, Channel(c), x0, y0, x1, y1);
+}
+
+// --- Normals ---
+
+glm::vec3 normalCombine(const glm::vec3& base, const glm::vec3& detail) {
+ // Reoriented normal mapping (Barré-Brisebois and Hill): rotate `detail` from the flat frame onto `base`.
+ const glm::vec3 t = base + glm::vec3(0, 0, 1);
+ const glm::vec3 u = detail * glm::vec3(-1, -1, 1);
+ if (t.z < 1e-4f) return detail; // base points straight down: nothing sensible to rotate by
+ const glm::vec3 r = t * glm::dot(t, u) / t.z - u;
+ const float len = glm::length(r);
+ return len > 1e-6f ? r / len : glm::vec3(0, 0, 1);
+}
+
+glm::vec3 heightNormalAt(const TileImage& h, int x, int y, float strength) {
+ if (!h.valid()) return {0, 0, 1};
+ const float dx = (h.value(x + 1, y) - h.value(x - 1, y)) * 0.5f;
+ const float dy = (h.value(x, y + 1) - h.value(x, y - 1)) * 0.5f;
+ // Scaled by the texture size, so a stroke looks the same at every resolution.
+ const float k = strength * float(h.width()) / 64.0f;
+ return glm::normalize(glm::vec3(-dx * k, -dy * k, 1.0f));
+}
+
+glm::vec3 effectiveNormalAt(const PaintTexture& t, int x, int y) {
+ glm::vec3 n(0, 0, 1);
+ if (channelEnabled(t, Channel::Normal)) {
+ float v[4];
+ channelImage(t, Channel::Normal).values(x, y, v);
+ n = decodeNormal(v[0], v[1], v[2]);
+ const float len = glm::length(n);
+ n = len > 1e-6f ? n / len : glm::vec3(0, 0, 1);
+ }
+ if (channelEnabled(t, Channel::Height))
+ n = normalCombine(n, heightNormalAt(channelImage(t, Channel::Height), x, y, t.heightNormalStrength));
+ return n;
+}
+
+// --- Sampling ---
+
+void sampleMaterial(const PaintTexture& t, const glm::vec2& uv, BrushMaterial& m) {
+ m.color = sampleTexture(t, uv);
+ m.channels = enabledChannelMask(t);
+ for (int c = 1; c < kChannelCount; ++c) {
+ if (!channelEnabled(t, Channel(c))) continue;
+ float v[4] = {0, 0, 0, 0};
+ channelImage(t, Channel(c)).sample(uv.x, uv.y, v);
+ switch (Channel(c)) {
+ case Channel::Roughness: m.roughness = v[0]; break;
+ case Channel::Metallic: m.metallic = v[0]; break;
+ case Channel::Normal: m.normal = glm::normalize(decodeNormal(v[0], v[1], v[2]) + glm::vec3(0, 0, 1e-6f)); break;
+ case Channel::Height: m.height = v[0]; break;
+ case Channel::AO: m.ao = v[0]; break;
+ case Channel::Emissive: m.emissive = glm::vec3(srgbToLinear(v[0]), srgbToLinear(v[1]), srgbToLinear(v[2])); break;
+ case Channel::Opacity: m.opacity = v[0]; break;
+ default: break;
+ }
+ }
+}
+
+bool sampleMaterialAt(const Mesh& mesh, uint32_t tri, const glm::vec3& point, BrushMaterial& m) {
+ if (!hasTexture(mesh) || tri >= mesh.triangleCount()) return false;
+ const glm::uvec3& tv = mesh.triangles[tri];
+ const glm::vec3 a = mesh.positions[tv.x], b = mesh.positions[tv.y], c = mesh.positions[tv.z];
+ const glm::vec3 v0 = b - a, v1 = c - a, v2 = point - a;
+ const float d00 = glm::dot(v0, v0), d01 = glm::dot(v0, v1), d11 = glm::dot(v1, v1);
+ const float d20 = glm::dot(v2, v0), d21 = glm::dot(v2, v1);
+ const float den = d00 * d11 - d01 * d01;
+ float v = 0.0f, w = 0.0f;
+ if (std::abs(den) > 1e-20f) {
+ v = (d11 * d20 - d01 * d21) / den;
+ w = (d00 * d21 - d01 * d20) / den;
+ }
+ const glm::vec2 uv = mesh.uvs[size_t(tri) * 3] * (1.0f - v - w) + mesh.uvs[size_t(tri) * 3 + 1] * v + mesh.uvs[size_t(tri) * 3 + 2] * w;
+ sampleMaterial(*mesh.texture, uv, m);
+ return true;
+}
+
+// --- Solo channel view ---
+
+void channelViewTexels(const PaintTexture& t, Channel c, int x0, int y0, int x1, int y1, std::vector<uint8_t>& out) {
+ x0 = std::max(x0, 0), y0 = std::max(y0, 0), x1 = std::min(x1, t.width), y1 = std::min(y1, t.height);
+ if (x0 >= x1 || y0 >= y1 || out.size() != t.texelCount() * 4) return;
+ const bool on = channelEnabled(t, c);
+ const TileImage* img = on ? &channelImage(t, c) : nullptr;
+ const ChannelFormat& f = channelFormat(c);
+ poolFor(size_t(y1 - y0), [&](size_t b, size_t e) {
+ for (int y = y0 + int(b); y < y0 + int(e); ++y)
+ for (int x = x0; x < x1; ++x) {
+ uint8_t* o = &out[(size_t(y) * size_t(t.width) + size_t(x)) * 4];
+ o[3] = 255;
+ if (c == Channel::Normal) {
+ const glm::vec3 n = effectiveNormalAt(t, x, y);
+ o[0] = uint8_t(std::lround((n.x * 0.5f + 0.5f) * 255.0f));
+ o[1] = uint8_t(std::lround((n.y * 0.5f + 0.5f) * 255.0f));
+ o[2] = uint8_t(std::lround(std::clamp(n.z * 0.5f + 0.5f, 0.0f, 1.0f) * 255.0f));
+ continue;
+ }
+ float v[4] = {f.defaultValue[0], f.defaultValue[1], f.defaultValue[2], 0};
+ if (img) img->values(x, y, v);
+ if (f.components == 1) v[1] = v[2] = v[0];
+ for (int k = 0; k < 3; ++k) o[k] = uint8_t(std::lround(std::clamp(v[k], 0.0f, 1.0f) * 255.0f));
+ }
+ }, 16, 4);
+}
+
+void syncChannelView(PaintTexture& t, Channel c) {
+ if (c == Channel::BaseColor || !channelEnabled(t, c)) {
+ if (t.viewChannel != Channel::BaseColor) {
+ t.viewChannel = Channel::BaseColor;
+ std::vector<uint8_t>().swap(t.viewPixels);
+ t.markAllDirty();
+ }
+ return;
+ }
+ const size_t n = t.texelCount() * 4;
+ if (t.viewChannel != c || t.viewPixels.size() != n || t.viewRevision > t.revision) {
+ t.viewPixels.assign(n, 255);
+ t.viewChannel = c;
+ channelViewTexels(t, c, 0, 0, t.width, t.height, t.viewPixels);
+ t.markAllDirty();
+ t.viewRevision = t.revision;
+ return;
+ }
+ if (t.viewRevision == t.revision) return;
+ // Redo the dirty tiles (one pixel wider for Normal: the height's normal reads the neighbours).
+ const int tilesX = (t.width + kTextureTile - 1) / kTextureTile, tilesY = (t.height + kTextureTile - 1) / kTextureTile;
+ const int pad = c == Channel::Normal ? 1 : 0;
+ for (int ty = 0; ty < tilesY; ++ty)
+ for (int tx = 0; tx < tilesX; ++tx)
+ if (t.tileDirty(tx, ty))
+ channelViewTexels(t, c, tx * kTextureTile - pad, ty * kTextureTile - pad, (tx + 1) * kTextureTile + pad,
+ (ty + 1) * kTextureTile + pad, t.viewPixels);
+ t.viewRevision = t.revision;
+}
+
+size_t channelBytes(const PaintTexture& t) {
+ size_t n = 0;
+ for (int c = 1; c < kChannelCount; ++c) {
+ const ChannelPlane& p = t.channels[size_t(c)];
+ n += p.base.bytes() + p.composite.bytes();
+ }
+ for (const TextureLayer& l : t.layers)
+ for (int c = 1; c < kChannelCount; ++c) n += l.channels[size_t(c)].image.bytes();
+ return n + t.viewPixels.size();
+}
+
+} // namespace sf
diff --git a/src/core/TextureChannels.h b/src/core/TextureChannels.h
new file mode 100644
index 00000000..f480a7a7
--- /dev/null
+++ b/src/core/TextureChannels.h
@@ -0,0 +1,161 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Material channels of a painted texture (PBR texture painting).
+//
+// A texture (core/Texture.h) always has its base colour: PaintTexture::pixels (and the colour of every
+// TextureLayer). It can also carry material channels, each turned on separately (texture_channels):
+//
+// Roughness, Metallic, AO, Opacity 1 x 8 bit linear data
+// Height 1 x 16 bit 0.5 = no displacement
+// Normal 3 x 8 bit tangent space, OpenGL convention (green up)
+// Emissive 3 x 8 bit sRGB colour
+//
+// Each enabled channel keeps a Base image (ChannelPlane::base) and, while the texture has layers, a composite
+// (ChannelPlane::composite). Every TextureLayer has a LayerChannel per channel: its own image (value plus
+// coverage in the last component), whether the layer affects that channel, a blend mode and an opacity.
+// Images are TileImages (core/TileImage.h): sparse and copy-on-write, so a channel nobody painted costs no
+// texel memory and an undo step keeps only the tiles a stroke changed.
+//
+// Compositing per texel and channel, bottom to top, as the colour does:
+// v = mix(v, blend(v, layer value), coverage * channel opacity * layer opacity)
+// Blend modes are the ten of core/PaintLayer.h applied per component, plus NormalCombine for normals
+// (reoriented normal mapping: the layer's detail is laid onto the normal below it instead of replacing it).
+// A layer tile nobody painted is skipped, and a composite tile no layer covers shares the Base tile.
+//
+// Height also yields a normal (heightToNormal): the effective normal shown and exported is the Normal channel
+// with the height's normal combined onto it (NormalCombine), at PaintTexture::heightNormalStrength.
+#pragma once
+
+#include "core/PaintLayer.h"
+#include "core/TileImage.h"
+
+#include <glm/glm.hpp>
+
+#include <array>
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace sf {
+
+class Mesh;
+struct PaintTexture;
+class CommandRegistry;
+
+enum class Channel : uint8_t { BaseColor, Roughness, Metallic, Normal, Height, AO, Emissive, Opacity };
+constexpr int kChannelCount = 8;
+
+struct ChannelFormat {
+ const char* id; // "base_color", "roughness", ... (commands, project files, export presets)
+ const char* label; // "Base Color", "Roughness", ...
+ const char* shortLabel; // two letters for layer rows: "BC", "R", "M", "N", "H", "AO", "E", "Op"
+ int components;
+ int bits;
+ bool srgb;
+ std::array<float, 4> defaultValue; // what an unpainted texel holds (0..1 per component)
+};
+const ChannelFormat& channelFormat(Channel c);
+inline const ChannelFormat& channelFormat(int c) { return channelFormat(Channel(c)); }
+// Accepts the id, the label, any case, and a few short forms ("color", "rough", "metal", "ao", "occlusion",
+// "emission", "alpha", "bump").
+bool parseChannel(const std::string& text, Channel& out);
+inline uint32_t channelBit(Channel c) { return 1u << uint32_t(c); }
+
+// Channel blend modes: the BlendMode values (0..kBlendModeCount-1), then NormalCombine.
+constexpr uint8_t kBlendNormalCombine = uint8_t(kBlendModeCount);
+constexpr int kChannelBlendCount = kBlendModeCount + 1;
+const char* channelBlendId(uint8_t blend); // "normal", ..., "normal_combine"
+const char* channelBlendLabel(uint8_t blend); // "Normal", ..., "Normal Combine"
+bool parseChannelBlend(const std::string& text, uint8_t& out);
+
+// One channel of one TextureLayer.
+struct LayerChannel {
+ bool enabled = true; // the layer affects this channel (BaseColor: the layer's colour shows)
+ uint8_t blend = 0; // channel blend (BaseColor uses TextureLayer::blend instead)
+ float opacity = 1.0f; // multiplies TextureLayer::opacity (BaseColor: unused)
+ TileImage image; // value + coverage (components + 1); empty until the texture enables the channel
+};
+using LayerChannels = std::array<LayerChannel, kChannelCount>;
+
+// One material channel of a texture.
+struct ChannelPlane {
+ bool enabled = false;
+ TileImage base; // the Base layer (components of the channel's format)
+ TileImage composite; // Base plus the layers (only while the texture has layers)
+};
+using ChannelPlanes = std::array<ChannelPlane, kChannelCount>; // [BaseColor] is unused: colour is `pixels`
+
+// What the Paint brush lays down on each channel (paint_material). `channels` says which ones it writes;
+// a channel is painted when the brush has it and the texture has it enabled (BaseColor always is).
+struct BrushMaterial {
+ glm::vec3 color{1.0f}; // linear RGB
+ float roughness = 0.5f;
+ float metallic = 0.0f;
+ glm::vec3 normal{0, 0, 1}; // tangent-space direction (normalised when painted)
+ float height = 0.5f; // 0..1, 0.5 = flat
+ float ao = 1.0f;
+ glm::vec3 emissive{0.0f}; // linear RGB
+ float opacity = 1.0f;
+ uint32_t channels = 1u; // channelBit(...) of the channels the brush paints; BaseColor only by default
+ // The brush value of channel c in 0..1 per component (Normal encoded 0..1, colours as stored: sRGB).
+ std::array<float, 4> encoded(Channel c) const;
+};
+
+// --- Texture-level queries (PaintTexture in core/Texture.h) ---
+bool channelEnabled(const PaintTexture& tex, Channel c); // BaseColor: always true
+// Any material channel besides base colour is enabled (the texture is a PBR texture; projects then need format 7).
+bool hasMaterialChannels(const PaintTexture& tex);
+uint32_t enabledChannelMask(const PaintTexture& tex); // includes BaseColor
+// The image shown and exported for channel c (the composite with layers, else Base). Not for BaseColor.
+const TileImage& channelImage(const PaintTexture& tex, Channel c);
+// Turns a channel on (its Base starts at the channel's default, every layer's channel transparent) or off
+// (drops its images). Returns true when something changed. BaseColor can't be turned off.
+bool setChannelEnabled(PaintTexture& tex, Channel c, bool on);
+// Makes the layers' channel images match the enabled channels (after adding / duplicating layers).
+void syncLayerChannels(PaintTexture& tex);
+
+// Settings of channel c on layer `layer` (BaseColor maps onto TextureLayer::blend / opacity / visible).
+uint8_t layerChannelBlend(const PaintTexture& tex, int layer, Channel c);
+float layerChannelOpacity(const PaintTexture& tex, int layer, Channel c);
+
+// --- Compositing ---
+// Recomputes the composites of every enabled material channel in [x0, x1) x [y0, y1) (tile granular; no-op
+// without layers). compositeTexture (core/Texture.h) calls it.
+void compositeChannels(PaintTexture& tex, int x0, int y0, int x1, int y1);
+void compositeChannel(PaintTexture& tex, Channel c, int x0, int y0, int x1, int y1);
+
+// --- Normals ---
+// Reoriented normal mapping: `detail` laid onto `base` (both unit tangent-space vectors).
+glm::vec3 normalCombine(const glm::vec3& base, const glm::vec3& detail);
+inline glm::vec3 decodeNormal(float r, float g, float b) { return glm::vec3(r, g, b) * 2.0f - 1.0f; }
+// The normal of a height image at texel (x, y): central differences, `strength` = height units per texel
+// slope scale (1 = a full 0..1 height step over one texel tilts 45 degrees at strength 1/1).
+glm::vec3 heightNormalAt(const TileImage& height, int x, int y, float strength);
+// The effective tangent-space normal at texel (x, y): the Normal channel (or flat) with the Height channel's
+// normal combined onto it when Height is enabled.
+glm::vec3 effectiveNormalAt(const PaintTexture& tex, int x, int y);
+
+// --- Picking (C) and sampling ---
+// The value of every enabled channel at texture coordinates uv (bilinear), into `m` (channels: the enabled ones).
+void sampleMaterial(const PaintTexture& tex, const glm::vec2& uv, BrushMaterial& m);
+// The same under a surface point of `triangle`.
+bool sampleMaterialAt(const Mesh& mesh, uint32_t triangle, const glm::vec3& point, BrushMaterial& m);
+
+// --- Solo channel view ---
+// RGBA8 texels showing channel c (greyscale for scalar channels, the effective normal, the emissive colour)
+// at texel rows [y0, y1) x [x0, x1) of `out` (width * height * 4, rows bottom-up).
+void channelViewTexels(const PaintTexture& tex, Channel c, int x0, int y0, int x1, int y1, std::vector<uint8_t>& out);
+// Brings PaintTexture::viewPixels up to date for showing channel c (BaseColor: stops showing a channel).
+// Called once per frame before the renderer uploads: only the tiles changed since the last call are redone;
+// a change of channel redoes everything and marks the texture dirty.
+void syncChannelView(PaintTexture& tex, Channel c);
+
+// --- Memory ---
+// Bytes of material channel images (bases, composites and layer channels).
+size_t channelBytes(const PaintTexture& tex);
+
+// texture_channels, paint_material, channel_view, texture_layer_channel.
+void registerTextureChannelCommands(CommandRegistry& registry);
+
+} // namespace sf
diff --git a/src/core/TileImage.cpp b/src/core/TileImage.cpp
new file mode 100644
index 00000000..ea0078f8
--- /dev/null
+++ b/src/core/TileImage.cpp
@@ -0,0 +1,234 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/TileImage.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstring>
+
+namespace sf {
+
+namespace {
+
+// Writes `value` (component units) as one raw texel of `comps` components of `bits`.
+void putTexel(uint8_t* out, const std::array<uint16_t, 4>& value, int comps, int bits) {
+ if (bits == 16) {
+ for (int c = 0; c < comps; ++c) std::memcpy(out + c * 2, &value[size_t(c)], 2);
+ } else {
+ for (int c = 0; c < comps; ++c) out[c] = uint8_t(value[size_t(c)]);
+ }
+}
+
+std::array<uint16_t, 4> readTexel(const uint8_t* p, int comps, int bits) {
+ std::array<uint16_t, 4> v{};
+ if (bits == 16) {
+ for (int c = 0; c < comps; ++c) std::memcpy(&v[size_t(c)], p + c * 2, 2);
+ } else {
+ for (int c = 0; c < comps; ++c) v[size_t(c)] = p[c];
+ }
+ return v;
+}
+
+} // namespace
+
+std::array<uint16_t, 4> TileImage::toUnits(int bits, float r, float g, float b, float a) {
+ const float m = bits == 16 ? 65535.0f : 255.0f;
+ auto u = [m](float x) { return uint16_t(std::lround(std::clamp(x, 0.0f, 1.0f) * m)); };
+ return {u(r), u(g), u(b), u(a)};
+}
+
+void TileImage::reset(int width, int height, int components, int bits, std::array<uint16_t, 4> fill) {
+ width_ = std::max(width, 0);
+ height_ = std::max(height, 0);
+ components_ = std::clamp(components, 1, 4);
+ bits_ = bits == 16 ? 16 : 8;
+ tilesX_ = (width_ + kTileImageTile - 1) / kTileImageTile;
+ tilesY_ = (height_ + kTileImageTile - 1) / kTileImageTile;
+ fill_ = fill;
+ tiles_.assign(size_t(tilesX_) * size_t(tilesY_), nullptr);
+}
+
+uint8_t* TileImage::writableTile(size_t index) {
+ TilePtr& t = tiles_[index];
+ const size_t n = size_t(kTileImageTexels) * size_t(texelBytes());
+ if (t && !t->uniform && t.use_count() == 1) return t->data.data();
+ auto made = std::make_shared<Tile>();
+ if (t && !t->uniform) {
+ made->data = t->data; // shared dense tile: copy on write
+ } else {
+ made->data.resize(n);
+ uint8_t px[8];
+ putTexel(px, t ? t->value : fill_, components_, bits_);
+ const int tb = texelBytes();
+ for (size_t i = 0; i < size_t(kTileImageTexels); ++i) std::memcpy(&made->data[i * size_t(tb)], px, size_t(tb));
+ }
+ t = std::move(made);
+ return t->data.data();
+}
+
+void TileImage::fillTile(size_t index, const std::array<uint16_t, 4>& value) {
+ bool isFill = true;
+ for (int c = 0; c < components_; ++c) isFill = isFill && value[size_t(c)] == fill_[size_t(c)];
+ if (isFill) {
+ tiles_[index] = nullptr;
+ return;
+ }
+ auto t = std::make_shared<Tile>();
+ t->uniform = true;
+ t->value = value;
+ tiles_[index] = std::move(t);
+}
+
+void TileImage::compactTile(size_t index) {
+ const TilePtr& t = tiles_[index];
+ if (!t) return;
+ if (t->uniform) {
+ fillTile(index, t->value); // nulls it when it equals the fill
+ return;
+ }
+ const int tb = texelBytes();
+ const uint8_t* d = t->data.data();
+ // Only the texels inside the image count (edge tiles).
+ const int tx = int(index % size_t(tilesX_)) * kTileImageTile, ty = int(index / size_t(tilesX_)) * kTileImageTile;
+ const int cw = std::min(kTileImageTile, width_ - tx), ch = std::min(kTileImageTile, height_ - ty);
+ for (int y = 0; y < ch; ++y)
+ for (int x = 0; x < cw; ++x)
+ if (std::memcmp(d + (size_t(y) * kTileImageTile + size_t(x)) * size_t(tb), d, size_t(tb)) != 0) return;
+ fillTile(index, readTexel(d, components_, bits_));
+}
+
+void TileImage::compact() {
+ for (size_t i = 0; i < tiles_.size(); ++i) compactTile(i);
+}
+
+const uint8_t* TileImage::texel(int x, int y, uint8_t* scratch) const {
+ const Tile* t = tiles_[tileIndex(x, y)].get();
+ if (t && !t->uniform)
+ return &t->data[(size_t(y % kTileImageTile) * kTileImageTile + size_t(x % kTileImageTile)) * size_t(texelBytes())];
+ putTexel(scratch, t ? t->value : fill_, components_, bits_);
+ return scratch;
+}
+
+void TileImage::values(int x, int y, float out[4]) const {
+ uint8_t s[8];
+ const uint8_t* p = texel(std::clamp(x, 0, width_ - 1), std::clamp(y, 0, height_ - 1), s);
+ if (bits_ == 16) {
+ for (int c = 0; c < components_; ++c) {
+ uint16_t v;
+ std::memcpy(&v, p + c * 2, 2);
+ out[c] = float(v) / 65535.0f;
+ }
+ } else {
+ for (int c = 0; c < components_; ++c) out[c] = float(p[c]) / 255.0f;
+ }
+}
+
+float TileImage::value(int x, int y, int c) const {
+ float v[4] = {0, 0, 0, 0};
+ values(x, y, v);
+ return v[std::clamp(c, 0, 3)];
+}
+
+void TileImage::setValues(int x, int y, const float* v) {
+ if (x < 0 || y < 0 || x >= width_ || y >= height_) return;
+ uint8_t* d = writableTile(tileIndex(x, y));
+ uint8_t* p = d + (size_t(y % kTileImageTile) * kTileImageTile + size_t(x % kTileImageTile)) * size_t(texelBytes());
+ putTexel(p, toUnits(bits_, v[0], components_ > 1 ? v[1] : 0, components_ > 2 ? v[2] : 0, components_ > 3 ? v[3] : 0),
+ components_, bits_);
+}
+
+void TileImage::sample(float u, float v, float out[4]) const {
+ const float fx = std::clamp(u, 0.0f, 1.0f) * float(width_) - 0.5f, fy = std::clamp(v, 0.0f, 1.0f) * float(height_) - 0.5f;
+ const float flx = std::floor(fx), fly = std::floor(fy);
+ const int x0 = std::clamp(int(flx), 0, width_ - 1), y0 = std::clamp(int(fly), 0, height_ - 1);
+ const int x1 = std::min(x0 + 1, width_ - 1), y1 = std::min(y0 + 1, height_ - 1);
+ const float ax = std::clamp(fx - flx, 0.0f, 1.0f), ay = std::clamp(fy - fly, 0.0f, 1.0f);
+ float a[4] = {}, b[4] = {}, c[4] = {}, d[4] = {};
+ values(x0, y0, a);
+ values(x1, y0, b);
+ values(x0, y1, c);
+ values(x1, y1, d);
+ for (int k = 0; k < components_; ++k)
+ out[k] = (a[k] * (1 - ax) + b[k] * ax) * (1 - ay) + (c[k] * (1 - ax) + d[k] * ax) * ay;
+}
+
+std::vector<uint8_t> TileImage::dense() const {
+ const size_t tb = size_t(texelBytes());
+ std::vector<uint8_t> out(size_t(width_) * size_t(height_) * tb);
+ uint8_t px[8];
+ for (int ty = 0; ty < tilesY_; ++ty)
+ for (int tx = 0; tx < tilesX_; ++tx) {
+ const Tile* t = tiles_[size_t(ty) * size_t(tilesX_) + size_t(tx)].get();
+ const int x0 = tx * kTileImageTile, y0 = ty * kTileImageTile;
+ const int cw = std::min(kTileImageTile, width_ - x0), ch = std::min(kTileImageTile, height_ - y0);
+ if (t && !t->uniform) {
+ for (int y = 0; y < ch; ++y)
+ std::memcpy(&out[(size_t(y0 + y) * size_t(width_) + size_t(x0)) * tb], &t->data[size_t(y) * kTileImageTile * tb],
+ size_t(cw) * tb);
+ continue;
+ }
+ putTexel(px, t ? t->value : fill_, components_, bits_);
+ for (int y = 0; y < ch; ++y)
+ for (int x = 0; x < cw; ++x) std::memcpy(&out[(size_t(y0 + y) * size_t(width_) + size_t(x0 + x)) * tb], px, tb);
+ }
+ return out;
+}
+
+void TileImage::assignDense(const std::vector<uint8_t>& data) {
+ const size_t tb = size_t(texelBytes());
+ if (data.size() != size_t(width_) * size_t(height_) * tb) return;
+ for (int ty = 0; ty < tilesY_; ++ty)
+ for (int tx = 0; tx < tilesX_; ++tx) {
+ const size_t i = size_t(ty) * size_t(tilesX_) + size_t(tx);
+ tiles_[i] = nullptr;
+ uint8_t* d = writableTile(i);
+ const int x0 = tx * kTileImageTile, y0 = ty * kTileImageTile;
+ const int cw = std::min(kTileImageTile, width_ - x0), ch = std::min(kTileImageTile, height_ - y0);
+ for (int y = 0; y < ch; ++y)
+ std::memcpy(&d[size_t(y) * kTileImageTile * tb], &data[(size_t(y0 + y) * size_t(width_) + size_t(x0)) * tb], size_t(cw) * tb);
+ compactTile(i);
+ }
+}
+
+bool TileImage::empty() const {
+ for (const auto& t : tiles_)
+ if (t) return false;
+ return true;
+}
+
+size_t TileImage::denseTiles() const {
+ size_t n = 0;
+ for (const auto& t : tiles_) n += t && !t->uniform;
+ return n;
+}
+
+size_t TileImage::bytes() const {
+ size_t n = tiles_.size() * sizeof(TilePtr);
+ for (const auto& t : tiles_)
+ if (t) n += sizeof(Tile) + t->data.size();
+ return n;
+}
+
+size_t TileImage::uniqueBytes() const {
+ size_t n = tiles_.size() * sizeof(TilePtr);
+ for (const auto& t : tiles_)
+ if (t && t.use_count() == 1) n += sizeof(Tile) + t->data.size();
+ return n;
+}
+
+bool TileImage::sameTexels(const TileImage& o) const {
+ if (width_ != o.width_ || height_ != o.height_ || components_ != o.components_ || bits_ != o.bits_) return false;
+ const size_t tb = size_t(texelBytes());
+ uint8_t a[8], b[8];
+ for (size_t i = 0; i < tiles_.size(); ++i) {
+ if (tiles_[i] == o.tiles_[i]) continue;
+ const int x0 = int(i % size_t(tilesX_)) * kTileImageTile, y0 = int(i / size_t(tilesX_)) * kTileImageTile;
+ const int cw = std::min(kTileImageTile, width_ - x0), ch = std::min(kTileImageTile, height_ - y0);
+ for (int y = 0; y < ch; ++y)
+ for (int x = 0; x < cw; ++x)
+ if (std::memcmp(texel(x0 + x, y0 + y, a), o.texel(x0 + x, y0 + y, b), tb) != 0) return false;
+ }
+ return true;
+}
+
+} // namespace sf
diff --git a/src/core/TileImage.h b/src/core/TileImage.h
new file mode 100644
index 00000000..cca41aa5
--- /dev/null
+++ b/src/core/TileImage.h
@@ -0,0 +1,114 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// TileImage: a sparse, copy-on-write image made of 64x64 tiles (kTileImageTile), used for the material
+// channels of a painted texture (core/TextureChannels.h).
+//
+// Every tile is one of three kinds:
+// - null: no tile at all; every texel is the image's fill value (a fresh channel costs nothing),
+// - uniform: one texel value for the whole tile,
+// - dense: 64 x 64 texels (edge tiles are stored whole too; texels outside the image are ignored).
+// A texel has 1-4 components of 8 or 16 bits (16-bit values are stored native-endian as uint16_t).
+//
+// Copies share their tiles (std::shared_ptr): copying an image costs one pointer per tile, and an edit makes
+// the tile it writes unique first (writableTile). Undo keeps the old tile pointers of the tiles a stroke
+// touched, so a stroke's undo record costs nothing beyond the tiles it changed. Rows are bottom-up, like
+// PaintTexture's (row 0 is v = 0).
+//
+// Reads and writes of different tiles may run on different threads; making a tile writable must not race with
+// another thread doing the same for the same tile (callers make tiles writable under a lock, then write texels).
+#pragma once
+
+#include <array>
+#include <cstddef>
+#include <cstdint>
+#include <memory>
+#include <vector>
+
+namespace sf {
+
+constexpr int kTileImageTile = 64;
+constexpr int kTileImageTexels = kTileImageTile * kTileImageTile;
+
+class TileImage {
+public:
+ struct Tile {
+ bool uniform = false;
+ std::array<uint16_t, 4> value{}; // the uniform tile's texel (in component units: 0-255 or 0-65535)
+ std::vector<uint8_t> data; // a dense tile: kTileImageTexels * texelBytes(), rows of 64 texels
+ };
+ using TilePtr = std::shared_ptr<Tile>;
+
+ TileImage() = default;
+ // An image of `width` x `height` texels with `components` (1-4) of `bits` (8 or 16), every texel `fill`
+ // (component units). Drops any old tiles.
+ void reset(int width, int height, int components, int bits, std::array<uint16_t, 4> fill);
+ void clear() { *this = TileImage(); }
+
+ bool valid() const { return width_ > 0 && height_ > 0; }
+ int width() const { return width_; }
+ int height() const { return height_; }
+ int components() const { return components_; }
+ int bits() const { return bits_; }
+ int texelBytes() const { return components_ * (bits_ == 16 ? 2 : 1); }
+ int tilesX() const { return tilesX_; }
+ int tilesY() const { return tilesY_; }
+ size_t tileCount() const { return tiles_.size(); }
+ float maxValue() const { return bits_ == 16 ? 65535.0f : 255.0f; }
+ const std::array<uint16_t, 4>& fill() const { return fill_; }
+ // Changes the fill (what null tiles read as). Null tiles take the new value.
+ void setFill(std::array<uint16_t, 4> fill) { fill_ = fill; }
+
+ // --- Tiles ---
+ uint32_t tileIndex(int x, int y) const { return uint32_t(y / kTileImageTile) * uint32_t(tilesX_) + uint32_t(x / kTileImageTile); }
+ const Tile* tile(size_t index) const { return index < tiles_.size() ? tiles_[index].get() : nullptr; }
+ const TilePtr& tilePtr(size_t index) const { return tiles_[index]; }
+ void setTilePtr(size_t index, TilePtr tile) { tiles_[index] = std::move(tile); }
+ // The tile's texels for writing: a dense tile that no copy shares (made from the null / uniform / shared tile
+ // first). Not thread-safe for the same tile.
+ uint8_t* writableTile(size_t index);
+ // Sets every texel of the tile to `value` (a uniform tile; the fill becomes a null tile).
+ void fillTile(size_t index, const std::array<uint16_t, 4>& value);
+ // Turns dense tiles whose texels are all equal into uniform ones, and uniform tiles equal to the fill into
+ // null ones (after big edits; keeps memory proportional to what was painted).
+ void compactTile(size_t index);
+ void compact();
+
+ // --- Texels (component units) ---
+ // Pointer to texel (x, y)'s components: inside a dense tile, a uniform tile's value or the fill, as raw
+ // bytes of texelBytes() (uniform and fill values are converted into `scratch`, which must hold 8 bytes).
+ const uint8_t* texel(int x, int y, uint8_t* scratch) const;
+ // Component `c` of texel (x, y) in 0..1.
+ float value(int x, int y, int c = 0) const;
+ // All components of texel (x, y) in 0..1 (out[components()..3] are left alone).
+ void values(int x, int y, float out[4]) const;
+ // Sets texel (x, y) from values in 0..1 (makes its tile writable).
+ void setValues(int x, int y, const float* v);
+ // Bilinear sample at uv (0..1, texel centres at (x + 0.5) / w), components in 0..1.
+ void sample(float u, float v, float out[4]) const;
+
+ // --- Whole image ---
+ // Every texel as one array, rows bottom-up, texelBytes() per texel.
+ std::vector<uint8_t> dense() const;
+ // Replaces the texels with `data` (width * height * texelBytes(), rows bottom-up), compacted.
+ void assignDense(const std::vector<uint8_t>& data);
+ // True when every tile is null (the whole image is the fill value).
+ bool empty() const;
+ size_t denseTiles() const;
+ // Bytes of tile memory (dense tiles' texels, uniform tiles' values) plus the tile table.
+ size_t bytes() const;
+ // Of those, the bytes of tiles no other image shares (what this copy alone keeps alive; undo accounting).
+ size_t uniqueBytes() const;
+ // Same size, format and texels (tiles compared by value).
+ bool sameTexels(const TileImage& other) const;
+
+ // A fill value from components in 0..1.
+ static std::array<uint16_t, 4> toUnits(int bits, float r, float g = 0, float b = 0, float a = 0);
+
+private:
+ int width_ = 0, height_ = 0, components_ = 1, bits_ = 8, tilesX_ = 0, tilesY_ = 0;
+ std::array<uint16_t, 4> fill_{};
+ std::vector<TilePtr> tiles_;
+};
+
+} // namespace sf
diff --git a/src/core/Undo.h b/src/core/Undo.h
index 2f3e4de0..225a5c8e 100644
--- a/src/core/Undo.h
+++ b/src/core/Undo.h
@@ -7,6 +7,7 @@
#include "core/Mesh.h"
#include "core/Multires.h"
#include "core/ThreadPool.h"
+#include "core/TileImage.h"
#include <deque>
#include <memory>
@@ -67,11 +68,21 @@ struct PackedTexels {
// Old texels of the 64x64 tiles a texture-paint stroke touched in one layer (core/Texture.h);
// applying swaps them with the texture.
+// Material channels (core/TextureChannels.h) are kept per (layer, channel) as the old tile pointers of the
+// channel's TileImage: nothing is copied, the tiles are shared with the image until it overwrites them.
+struct TextureChannelTiles {
+ int layer = -1; // -1 = Base
+ uint8_t channel = 0; // Channel
+ std::vector<uint32_t> tiles;
+ std::vector<std::shared_ptr<TileImage::Tile>> old; // per tile; null = the image's fill
+ size_t bytes() const;
+};
struct TextureTileUndo {
int layer = -1;
- PackedTexels texels;
+ PackedTexels texels; // base colour (no tiles when the stroke painted only material channels)
+ std::vector<TextureChannelTiles> channels;
void swapWith(Mesh& mesh);
- size_t bytes() const { return texels.bytes(); }
+ size_t bytes() const;
};
// The texture before a texture edit (create, delete, layer edits, conversions, fills). captureTexture
diff --git a/tests/test_texture_channels.cpp b/tests/test_texture_channels.cpp
new file mode 100644
index 00000000..f4cd6794
--- /dev/null
+++ b/tests/test_texture_channels.cpp
@@ -0,0 +1,486 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Material channels of a painted texture (core/TextureChannels.h, core/TileImage.h): sparse copy-on-write tiles,
+// enabling channels, material dabs on Base and on layers, per-(layer, channel) undo, per-channel blend modes
+// with Normal Combine, height-to-normal, the solo channel view, layer operations on channels, the commands, and
+// what a 5-channel dab costs next to a base-colour dab.
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/Primitives.h"
+#include "core/Texture.h"
+#include "core/TextureChannels.h"
+#include "core/TileImage.h"
+
+#include <chrono>
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+
+using namespace sf;
+
+namespace {
+
+void planarUvs(Mesh& m) {
+ const AABB b = m.bounds();
+ const glm::vec3 e = b.extent();
+ 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) / e.x, (p.z - b.min.z) / e.z);
+ }
+}
+
+void sphericalUvs(Mesh& m) {
+ 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 = glm::normalize(m.positions[m.triangles[t][c]]);
+ m.uvs[t * 3 + size_t(c)] = glm::vec2(0.5f + std::atan2(p.z, p.x) / 6.2831853f, 0.5f + std::asin(p.y) / 3.1415927f);
+ }
+}
+
+// A plane facing +Y with planar UVs and a texture.
+Mesh texturedPlane(int resolution, int size) {
+ Mesh m = makePlane(resolution);
+ planarUvs(m);
+ m.texture = makeTexture(size, size);
+ m.paintToTexture = true;
+ return m;
+}
+
+DabParams dab(const glm::vec3& center, float radius, float strength = 1.0f) {
+ DabParams p;
+ p.center = center;
+ p.viewDir = glm::vec3(0, -1, 0);
+ p.radius = radius;
+ p.strength = strength;
+ return p;
+}
+
+BrushMaterial rustyMetal() {
+ BrushMaterial m;
+ m.color = glm::vec3(0.6f, 0.2f, 0.05f);
+ m.roughness = 0.2f;
+ m.metallic = 1.0f;
+ m.height = 0.8f;
+ m.ao = 0.4f;
+ m.channels = channelBit(Channel::BaseColor) | channelBit(Channel::Roughness) | channelBit(Channel::Metallic) |
+ channelBit(Channel::Height) | channelBit(Channel::AO);
+ return m;
+}
+
+// Paints one dab of `m` at the plane's centre (one stroke) and returns its undo record.
+UndoRecord paintCentre(Mesh& mesh, const BVH& bvh, const BrushMaterial& m, float radius = 0.4f) {
+ TexturePainter painter;
+ CHECK(painter.begin(mesh, m.channels));
+ CHECK(painter.dab(mesh, bvh, dab(glm::vec3(0, 0, 0), radius), m, Symmetry{}) > 0);
+ UndoRecord r;
+ r.label = "Paint";
+ painter.end(r);
+ return r;
+}
+
+float centreValue(const PaintTexture& t, Channel c, int comp = 0) {
+ return channelImage(t, c).value(t.width / 2, t.height / 2, comp);
+}
+
+} // namespace
+
+TEST(tile_image_is_sparse_and_copy_on_write) {
+ TileImage img;
+ img.reset(256, 256, 1, 8, TileImage::toUnits(8, 0.5f));
+ CHECK(img.tilesX() == 4 && img.tilesY() == 4);
+ CHECK(img.empty());
+ CHECK(img.denseTiles() == 0);
+ CHECK(std::abs(img.value(10, 10) - 0.5f) < 0.01f);
+ const float v[1] = {1.0f};
+ img.setValues(70, 3, v);
+ CHECK(img.denseTiles() == 1);
+ CHECK(img.value(70, 3) == 1.0f);
+ CHECK(std::abs(img.value(71, 3) - 0.5f) < 0.01f);
+ // A copy shares the tile until one side writes.
+ TileImage copy = img;
+ CHECK(copy.tilePtr(1) == img.tilePtr(1));
+ const float z[1] = {0.0f};
+ copy.setValues(70, 3, z);
+ CHECK(copy.tilePtr(1) != img.tilePtr(1));
+ CHECK(img.value(70, 3) == 1.0f);
+ CHECK(copy.value(70, 3) == 0.0f);
+ // Compacting: a tile of one value becomes uniform, one equal to the fill becomes null.
+ for (int y = 0; y < 64; ++y)
+ for (int x = 64; x < 128; ++x) copy.setValues(x, y, z);
+ copy.compact();
+ CHECK(copy.denseTiles() == 0);
+ CHECK(!copy.empty());
+ CHECK(copy.value(100, 10) == 0.0f);
+ const float h[1] = {0.5f};
+ for (int y = 0; y < 64; ++y)
+ for (int x = 64; x < 128; ++x) copy.setValues(x, y, h);
+ copy.compact();
+ CHECK(copy.empty());
+ // 16 bits keep fine steps; dense() / assignDense() round trip.
+ TileImage h16;
+ h16.reset(100, 70, 2, 16, TileImage::toUnits(16, 0.5f, 0.0f));
+ const float fine[2] = {0.500015f, 1.0f};
+ h16.setValues(99, 69, fine);
+ CHECK(std::abs(h16.value(99, 69) - 0.500015f) < 2e-5f);
+ const std::vector<uint8_t> d = h16.dense();
+ CHECK(d.size() == size_t(100) * 70 * 4);
+ TileImage back;
+ back.reset(100, 70, 2, 16, h16.fill());
+ back.assignDense(d);
+ CHECK(back.sameTexels(h16));
+ CHECK(back.denseTiles() == 1);
+ // Bilinear sampling between two values.
+ TileImage s;
+ s.reset(2, 1, 1, 8, TileImage::toUnits(8, 0.0f));
+ s.setValues(1, 0, v);
+ float out[4] = {};
+ s.sample(0.5f, 0.5f, out);
+ CHECK(std::abs(out[0] - 0.5f) < 0.01f);
+}
+
+TEST(texture_channels_enable_and_cost_nothing_until_painted) {
+ Mesh m = texturedPlane(16, 1024);
+ PaintTexture& t = *m.texture;
+ CHECK(!hasMaterialChannels(t));
+ CHECK(enabledChannelMask(t) == 1u);
+ const size_t before = t.bytes();
+ for (Channel c : {Channel::Roughness, Channel::Metallic, Channel::Normal, Channel::Height, Channel::AO, Channel::Emissive,
+ Channel::Opacity})
+ CHECK(setChannelEnabled(t, c, true));
+ CHECK(!setChannelEnabled(t, Channel::Roughness, true)); // already on
+ CHECK(!setChannelEnabled(t, Channel::BaseColor, false));
+ CHECK(hasMaterialChannels(t));
+ CHECK(enabledChannelMask(t) == 0xFFu);
+ CHECK(t.bytes() - before < 64 * 1024); // tile tables only
+ CHECK(std::abs(centreValue(t, Channel::Roughness) - 0.65f) < 0.01f);
+ CHECK(centreValue(t, Channel::Metallic) == 0.0f);
+ CHECK(std::abs(centreValue(t, Channel::Height) - 0.5f) < 1e-4f);
+ CHECK(centreValue(t, Channel::AO) == 1.0f);
+ CHECK(channelImage(t, Channel::Height).bits() == 16);
+ CHECK(channelImage(t, Channel::Normal).components() == 3);
+ // Effective normal of an unpainted texture is flat.
+ const glm::vec3 n = effectiveNormalAt(t, 100, 100);
+ CHECK(std::abs(n.z - 1.0f) < 1e-3f);
+ CHECK(setChannelEnabled(t, Channel::Opacity, false));
+ CHECK(!channelEnabled(t, Channel::Opacity));
+}
+
+TEST(material_dab_paints_every_enabled_channel_and_undoes_per_channel) {
+ Document doc = makeDoc(texturedPlane(32, 1024));
+ Mesh& m = doc.mesh;
+ for (Channel c : {Channel::Roughness, Channel::Metallic, Channel::Height, Channel::AO}) setChannelEnabled(*m.texture, c, true);
+ doc.syncBvh();
+ BrushMaterial mat = rustyMetal();
+ mat.channels |= channelBit(Channel::Emissive); // not enabled on the texture: skipped
+ UndoRecord r = paintCentre(m, doc.bvh, mat);
+ const PaintTexture& t = *m.texture;
+ CHECK(std::abs(centreValue(t, Channel::Roughness) - 0.2f) < 0.02f);
+ CHECK(centreValue(t, Channel::Metallic) > 0.98f);
+ CHECK(std::abs(centreValue(t, Channel::Height) - 0.8f) < 0.01f);
+ CHECK(std::abs(centreValue(t, Channel::AO) - 0.4f) < 0.02f);
+ CHECK(!channelEnabled(t, Channel::Emissive));
+ const uint8_t* px = &t.pixels[(size_t(512) * 1024 + 512) * 4];
+ CHECK(px[0] > px[1] && px[1] > px[2]);
+ // Far from the dab nothing changed, and the images stay sparse.
+ CHECK(std::abs(channelImage(t, Channel::Roughness).value(5, 5) - 0.65f) < 0.01f);
+ CHECK(channelImage(t, Channel::Roughness).denseTiles() < channelImage(t, Channel::Roughness).tileCount() / 2);
+ // One record: base colour tiles plus one entry per (layer, channel).
+ CHECK(r.textureTiles != nullptr);
+ CHECK(!r.textureTiles->texels.tiles.empty());
+ CHECK(r.textureTiles->channels.size() == 4);
+ for (const auto& ct : r.textureTiles->channels) CHECK(ct.layer == -1);
+ doc.undo.push(std::move(r));
+ CHECK(doc.undo.undo(doc.mesh, doc.bvh));
+ CHECK(std::abs(centreValue(*m.texture, Channel::Roughness) - 0.65f) < 0.01f);
+ CHECK(centreValue(*m.texture, Channel::Metallic) == 0.0f);
+ CHECK(std::abs(centreValue(*m.texture, Channel::Height) - 0.5f) < 1e-4f);
+ CHECK(m.texture->pixels[(size_t(512) * 1024 + 512) * 4] == 255);
+ CHECK(doc.undo.redo(doc.mesh, doc.bvh));
+ CHECK(std::abs(centreValue(*m.texture, Channel::Roughness) - 0.2f) < 0.02f);
+ CHECK(std::abs(centreValue(*m.texture, Channel::Height) - 0.8f) < 0.01f);
+
+ // A stroke on roughness only leaves the colour (and its undo) alone.
+ BrushMaterial glossy;
+ glossy.roughness = 0.0f;
+ glossy.channels = channelBit(Channel::Roughness);
+ const std::vector<uint8_t> colour = m.texture->pixels;
+ UndoRecord r2 = paintCentre(m, doc.bvh, glossy, 0.2f);
+ CHECK(m.texture->pixels == colour);
+ CHECK(r2.textureTiles && r2.textureTiles->texels.tiles.empty() && r2.textureTiles->channels.size() == 1);
+ CHECK(centreValue(*m.texture, Channel::Roughness) < 0.02f);
+ doc.undo.push(std::move(r2));
+ CHECK(doc.undo.undo(doc.mesh, doc.bvh));
+ CHECK(std::abs(centreValue(*m.texture, Channel::Roughness) - 0.2f) < 0.02f);
+
+ // Erasing (invert) on Base paints back to the defaults.
+ {
+ TexturePainter p;
+ CHECK(p.begin(m, mat.channels));
+ DabParams d = dab(glm::vec3(0), 0.4f);
+ d.invert = true;
+ p.dab(m, doc.bvh, d, mat, Symmetry{});
+ UndoRecord e;
+ p.end(e);
+ CHECK(std::abs(centreValue(*m.texture, Channel::Roughness) - 0.65f) < 0.02f);
+ CHECK(std::abs(centreValue(*m.texture, Channel::Height) - 0.5f) < 0.01f);
+ }
+}
+
+TEST(material_layers_composite_per_channel_with_blend_modes) {
+ Document doc = makeDoc(texturedPlane(32, 512));
+ Mesh& m = doc.mesh;
+ PaintTexture& t0 = *m.texture;
+ setChannelEnabled(t0, Channel::Roughness, true);
+ setChannelEnabled(t0, Channel::Normal, true);
+ doc.syncBvh();
+ // Base roughness 0.8.
+ BrushMaterial rough;
+ rough.roughness = 0.8f;
+ rough.channels = channelBit(Channel::Roughness);
+ paintCentre(m, doc.bvh, rough, 2.0f);
+ CHECK(std::abs(centreValue(*m.texture, Channel::Roughness) - 0.8f) < 0.01f);
+ // A layer that multiplies roughness by 0.5.
+ const int li = addTextureLayer(*m.texture, "Wet");
+ CHECK(li == 0);
+ CHECK(m.texture->layers[0].channels[size_t(Channel::Roughness)].image.valid());
+ CHECK(m.texture->layers[0].channels[size_t(Channel::Roughness)].image.empty()); // transparent, no tiles
+ m.texture->layers[0].channels[size_t(Channel::Roughness)].blend = uint8_t(BlendMode::Multiply);
+ BrushMaterial half;
+ half.roughness = 0.5f;
+ half.channels = channelBit(Channel::Roughness);
+ UndoRecord r = paintCentre(m, doc.bvh, half, 0.3f);
+ CHECK(r.textureTiles && r.textureTiles->channels.size() == 1 && r.textureTiles->channels[0].layer == 0);
+ CHECK(std::abs(centreValue(*m.texture, Channel::Roughness) - 0.4f) < 0.02f);
+ // Base stays 0.8 under the layer; away from the stroke the composite shares Base's tiles.
+ CHECK(std::abs(m.texture->channels[size_t(Channel::Roughness)].base.value(256, 256) - 0.8f) < 0.01f);
+ const TileImage& comp = m.texture->channels[size_t(Channel::Roughness)].composite;
+ CHECK(comp.valid());
+ CHECK(comp.tilePtr(0) == m.texture->channels[size_t(Channel::Roughness)].base.tilePtr(0));
+ // Channel opacity and turning the channel off on the layer.
+ m.texture->layers[0].channels[size_t(Channel::Roughness)].opacity = 0.5f;
+ compositeTextureAll(*m.texture);
+ CHECK(std::abs(centreValue(*m.texture, Channel::Roughness) - 0.6f) < 0.02f);
+ m.texture->layers[0].channels[size_t(Channel::Roughness)].enabled = false;
+ compositeTextureAll(*m.texture);
+ CHECK(std::abs(centreValue(*m.texture, Channel::Roughness) - 0.8f) < 0.01f);
+ m.texture->layers[0].channels[size_t(Channel::Roughness)].enabled = true;
+ m.texture->layers[0].channels[size_t(Channel::Roughness)].opacity = 1.0f;
+ compositeTextureAll(*m.texture);
+ // Undo of the layer stroke.
+ doc.undo.push(std::move(r));
+ CHECK(doc.undo.undo(doc.mesh, doc.bvh));
+ CHECK(std::abs(centreValue(*m.texture, Channel::Roughness) - 0.8f) < 0.01f);
+ CHECK(doc.undo.redo(doc.mesh, doc.bvh));
+ CHECK(std::abs(centreValue(*m.texture, Channel::Roughness) - 0.4f) < 0.02f);
+
+ // Normal Combine: a tilted detail on a tilted base tilts further; Normal replaces.
+ const glm::vec3 base = glm::normalize(glm::vec3(0.3f, 0, 1)), detail = glm::normalize(glm::vec3(0.3f, 0, 1));
+ const glm::vec3 combined = normalCombine(base, detail);
+ CHECK(combined.x > base.x + 0.1f);
+ CHECK(std::abs(glm::length(combined) - 1.0f) < 1e-4f);
+ const glm::vec3 flat = normalCombine(glm::vec3(0, 0, 1), detail);
+ CHECK(glm::length(flat - detail) < 1e-4f);
+ BrushMaterial tilt;
+ tilt.normal = base;
+ tilt.channels = channelBit(Channel::Normal);
+ m.texture->activeLayer = -1;
+ paintCentre(m, doc.bvh, tilt, 2.0f);
+ m.texture->activeLayer = 0;
+ m.texture->layers[0].channels[size_t(Channel::Normal)].blend = kBlendNormalCombine;
+ paintCentre(m, doc.bvh, tilt, 0.3f);
+ float nv[4];
+ channelImage(*m.texture, Channel::Normal).values(256, 256, nv);
+ const glm::vec3 got = glm::normalize(decodeNormal(nv[0], nv[1], nv[2]));
+ CHECK(std::abs(got.x - combined.x) < 0.03f);
+ m.texture->layers[0].channels[size_t(Channel::Normal)].blend = uint8_t(BlendMode::Normal);
+ compositeTextureAll(*m.texture);
+ channelImage(*m.texture, Channel::Normal).values(256, 256, nv);
+ CHECK(std::abs(glm::normalize(decodeNormal(nv[0], nv[1], nv[2])).x - base.x) < 0.03f);
+
+ // Merge down keeps the look; flatten keeps it too.
+ const float before = centreValue(*m.texture, Channel::Roughness);
+ std::string err;
+ CHECK(mergeTextureLayerDown(*m.texture, 0, err));
+ CHECK(m.texture->layers.empty());
+ CHECK(std::abs(centreValue(*m.texture, Channel::Roughness) - before) < 0.02f);
+}
+
+TEST(height_makes_a_normal_and_the_solo_view_shows_channels) {
+ Document doc = makeDoc(texturedPlane(32, 512));
+ Mesh& m = doc.mesh;
+ setChannelEnabled(*m.texture, Channel::Height, true);
+ setChannelEnabled(*m.texture, Channel::Roughness, true);
+ doc.syncBvh();
+ BrushMaterial bump;
+ bump.height = 1.0f;
+ bump.roughness = 0.1f;
+ bump.channels = channelBit(Channel::Height) | channelBit(Channel::Roughness);
+ paintCentre(m, doc.bvh, bump, 0.3f);
+ const PaintTexture& t = *m.texture;
+ // On the bump's left flank the normal tilts left (-x), on the right flank right.
+ const int y = 256;
+ int left = -1, right = -1;
+ for (int x = 0; x < 512 && left < 0; ++x)
+ if (channelImage(t, Channel::Height).value(x, y) > 0.6f) left = x;
+ for (int x = 511; x >= 0 && right < 0; --x)
+ if (channelImage(t, Channel::Height).value(x, y) > 0.6f) right = x;
+ CHECK(left > 0 && right > left);
+ CHECK(effectiveNormalAt(t, left, y).x < -0.05f);
+ CHECK(effectiveNormalAt(t, right, y).x > 0.05f);
+ CHECK(std::abs(effectiveNormalAt(t, 5, 5).z - 1.0f) < 1e-3f);
+
+ // Solo view: roughness as grey.
+ PaintTexture& tex = *m.texture;
+ CHECK(&tex.shown() == &tex.pixels);
+ syncChannelView(tex, Channel::Roughness);
+ CHECK(tex.viewChannel == Channel::Roughness);
+ CHECK(&tex.shown() == &tex.viewPixels);
+ const uint8_t* c = &tex.shown()[(size_t(256) * 512 + 256) * 4];
+ CHECK(c[0] == c[1] && c[1] == c[2] && c[0] < 40);
+ const uint8_t* far = &tex.shown()[(size_t(5) * 512 + 5) * 4];
+ CHECK(std::abs(int(far[0]) - 166) <= 1); // 0.65
+ // Painting while the view shows roughness updates just the dirty tiles.
+ tex.clearDirty();
+ BrushMaterial glossy;
+ glossy.roughness = 1.0f;
+ glossy.channels = channelBit(Channel::Roughness);
+ TexturePainter p;
+ CHECK(p.begin(m, glossy.channels));
+ p.dab(m, doc.bvh, dab(glm::vec3(0), 0.1f), glossy, Symmetry{});
+ UndoRecord rec;
+ p.end(rec);
+ syncChannelView(*m.texture, Channel::Roughness);
+ CHECK(m.texture->shown()[(size_t(256) * 512 + 256) * 4] > 240);
+ // Normal view shows the height's normal; off goes back to the colour.
+ syncChannelView(*m.texture, Channel::Normal); // not enabled: back to colour
+ CHECK(&m.texture->shown() == &m.texture->pixels);
+ syncChannelView(*m.texture, Channel::Height);
+ CHECK(m.texture->viewChannel == Channel::Height);
+ syncChannelView(*m.texture, Channel::BaseColor);
+ CHECK(m.texture->viewPixels.empty());
+}
+
+TEST(material_picking_samples_every_channel) {
+ Document doc = makeDoc(texturedPlane(32, 512));
+ Mesh& m = doc.mesh;
+ for (Channel c : {Channel::Roughness, Channel::Metallic, Channel::Height, Channel::AO}) setChannelEnabled(*m.texture, c, true);
+ doc.syncBvh();
+ paintCentre(m, doc.bvh, rustyMetal(), 0.5f);
+ BrushMaterial picked;
+ CHECK(sampleMaterialAt(m, 0, m.positions[m.triangles[0].x], picked)); // a corner: defaults
+ CHECK(std::abs(picked.roughness - 0.65f) < 0.02f);
+ sampleMaterial(*m.texture, glm::vec2(0.5f, 0.5f), picked);
+ CHECK(std::abs(picked.roughness - 0.2f) < 0.02f);
+ CHECK(picked.metallic > 0.97f);
+ CHECK(std::abs(picked.height - 0.8f) < 0.01f);
+ CHECK(std::abs(picked.ao - 0.4f) < 0.02f);
+ CHECK(std::abs(picked.color.x - 0.6f) < 0.03f);
+ CHECK(picked.channels == (channelBit(Channel::BaseColor) | channelBit(Channel::Roughness) | channelBit(Channel::Metallic) |
+ channelBit(Channel::Height) | channelBit(Channel::AO)));
+}
+
+TEST(texture_channel_commands) {
+ Document doc = makeDoc(texturedPlane(16, 1024));
+ CommandRegistry reg;
+ CHECK(reg.execute(doc, "texture_channels").ok);
+ CHECK(reg.execute(doc, "texture_channels", {{"enable", std::string("roughness, metallic,normal")}}).ok);
+ CHECK(channelEnabled(*doc.mesh.texture, Channel::Normal));
+ CHECK(!reg.execute(doc, "texture_channels", {{"enable", std::string("sparkle")}}).ok);
+ CHECK(!reg.execute(doc, "texture_channels", {{"disable", std::string("base_color")}}).ok);
+ // Undo turns them off again.
+ CHECK(doc.undo.undo(doc.mesh, doc.bvh));
+ CHECK(!hasMaterialChannels(*doc.mesh.texture));
+ CHECK(doc.undo.redo(doc.mesh, doc.bvh));
+ CHECK(channelEnabled(*doc.mesh.texture, Channel::Metallic));
+
+ // paint_material: values add their channel; channels= sets exactly.
+ CommandResult r = reg.execute(doc, "paint_material", {{"roughness", 0.25}, {"metallic", 1.0}});
+ CHECK(r.ok);
+ CHECK(doc.paintMaterial.channels == (channelBit(Channel::BaseColor) | channelBit(Channel::Roughness) | channelBit(Channel::Metallic)));
+ CHECK(std::abs(doc.paintMaterial.roughness - 0.25f) < 1e-6f);
+ r = reg.execute(doc, "paint_material", {{"height", 0.7}});
+ CHECK(r.ok && r.message.find("not on this texture") != std::string::npos);
+ CHECK(reg.execute(doc, "paint_material", {{"channels", std::string("roughness")}}).ok);
+ CHECK(doc.paintMaterial.channels == channelBit(Channel::Roughness));
+ CHECK(reg.execute(doc, "paint_material", {{"normal", std::string("0.5,0,1")}}).ok);
+ CHECK(doc.paintMaterial.normal.x > 0.4f);
+ CHECK(!reg.execute(doc, "paint_material", {{"normal", std::string("x")}}).ok);
+ CHECK(!reg.execute(doc, "paint_material", {{"channels", std::string("glitter")}}).ok);
+ CHECK(reg.execute(doc, "paint_material", {{"color", std::string("#ff0000")}, {"emissive", std::string("#00ff00")}}).ok);
+ CHECK(doc.paintColor.x > 0.99f);
+
+ // channel_view needs an enabled channel.
+ CHECK(reg.execute(doc, "channel_view", {{"channel", std::string("roughness")}}).ok);
+ CHECK(doc.channelView == Channel::Roughness);
+ CHECK(doc.mesh.texture->viewChannel == Channel::Roughness);
+ CHECK(!reg.execute(doc, "channel_view", {{"channel", std::string("height")}}).ok);
+ CHECK(!reg.execute(doc, "channel_view", {{"channel", std::string("shiny")}}).ok);
+ CHECK(reg.execute(doc, "channel_view", {{"channel", std::string("off")}}).ok);
+ CHECK(doc.channelView == Channel::BaseColor);
+
+ // texture_layer_channel on a layer, undoable.
+ CHECK(reg.execute(doc, "paint_layer_add", {{"name", std::string("Grime")}}).ok);
+ CHECK(!reg.execute(doc, "texture_layer_channel", {{"channel", std::string("roughness")}, {"index", -1.0}}).ok);
+ CHECK(reg.execute(doc, "texture_layer_channel",
+ {{"channel", std::string("roughness")}, {"blend", std::string("multiply")}, {"opacity", 0.5}}).ok);
+ CHECK(doc.mesh.texture->layers[0].channels[size_t(Channel::Roughness)].blend == uint8_t(BlendMode::Multiply));
+ CHECK(!reg.execute(doc, "texture_layer_channel", {{"channel", std::string("roughness")}, {"blend", std::string("normal_combine")}}).ok);
+ CHECK(reg.execute(doc, "texture_layer_channel", {{"channel", std::string("normal")}, {"blend", std::string("normal_combine")}}).ok);
+ CHECK(reg.execute(doc, "texture_layer_channel", {{"channel", std::string("base_color")}, {"enabled", false}}).ok);
+ CHECK(!doc.mesh.texture->layers[0].channels[0].enabled);
+ CHECK(doc.undo.undo(doc.mesh, doc.bvh));
+ CHECK(doc.mesh.texture->layers[0].channels[0].enabled);
+ // Layer copies carry their channel settings; disabling a channel drops it from layers too.
+ CHECK(reg.execute(doc, "paint_layer_duplicate").ok);
+ CHECK(doc.mesh.texture->layers.size() == 2);
+ CHECK(doc.mesh.texture->layers[1].channels[size_t(Channel::Normal)].blend == kBlendNormalCombine);
+ CHECK(reg.execute(doc, "texture_channels", {{"disable", std::string("normal")}}).ok);
+ CHECK(!doc.mesh.texture->layers[0].channels[size_t(Channel::Normal)].image.valid());
+ // No texture: clear errors.
+ Document plain = makeDoc(makePlane(4));
+ CHECK(!reg.execute(plain, "texture_channels").ok);
+ CHECK(!reg.execute(plain, "channel_view", {{"channel", std::string("roughness")}}).ok);
+}
+
+TEST(material_dab_cost_against_base_colour_dab) {
+ // 4K texture on a dense sphere, a big brush with X symmetry (as texture_stroke_benchmark): the 5-channel dab
+ // (colour, roughness, metallic, height, AO) against the colour-only dab. Target: at most 2.5x.
+ Mesh base = makeIcosphere(7);
+ sphericalUvs(base);
+ BVH bvh;
+ bvh.build(base);
+ double ms[2] = {0, 0};
+ for (int pass = 0; pass < 2; ++pass) {
+ Mesh m = base;
+ m.texture = makeTexture(4096, 4096);
+ m.paintToTexture = true;
+ BrushMaterial mat = rustyMetal();
+ if (pass == 0) {
+ mat.channels = channelBit(Channel::BaseColor);
+ } else {
+ for (Channel c : {Channel::Roughness, Channel::Metallic, Channel::Height, Channel::AO}) setChannelEnabled(*m.texture, c, true);
+ }
+ TexturePainter painter;
+ CHECK(painter.begin(m, mat.channels));
+ DabParams p = dab(glm::vec3(0, 0, 1), 0.35f, 0.5f);
+ p.viewDir = glm::vec3(0, 0, -1);
+ for (int i = 0; i < 12; ++i) {
+ p.center = glm::normalize(glm::vec3(-0.15f + 0.025f * float(i), 0.2f, 1.0f));
+ const auto t0 = std::chrono::steady_clock::now();
+ painter.dab(m, bvh, p, mat, Symmetry{true, false, false});
+ ms[pass] += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
+ }
+ UndoRecord rec;
+ painter.end(rec);
+ ms[pass] /= 12.0;
+ if (pass == 1) std::printf(" 4K big dab: base colour %.2f ms, 5 channels %.2f ms (%.2fx); channel memory %.1f MB\n",
+ ms[0], ms[1], ms[1] / ms[0], double(channelBytes(*m.texture)) / 1048576.0);
+ }
+ CHECK(ms[0] > 0 && ms[1] > 0);
+ if (std::getenv("SF_BENCH_LIMITS")) CHECK(ms[1] <= 2.5 * ms[0]);
+}