Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
Parallel brush vertex query, cheaper normal gather, streamed project archives with ZIP64
islandmed07304d752120
diff --git a/src/core/BVH.cpp b/src/core/BVH.cppindex 6719d26a..3a357a7d 100644--- a/src/core/BVH.cpp+++ b/src/core/BVH.cpp@@ -54,7 +54,7 @@ void BVH::build(const Mesh& mesh) {triIndices_.resize(nt);triLeaf_.assign(nt, 0);vertStamp_.assign(mesh.vertexCount(), 0);- vertStampValue_ = 0;+ queryEpoch_ = 0;if (nt == 0) return;std::vector<glm::vec3> centroids(nt);@@ -252,30 +252,101 @@ void BVH::queryVertices(const Mesh& mesh, const glm::vec3& center, float radius,out.clear();if (nodes_.empty()) return;const float r2 = radius * radius;- const uint32_t s = nextStamp(vertStamp_, vertStampValue_);+ // vertStamp_ holds (epoch << 16) | code: kDone once a vertex is output in this query; while splitting+ // over threads, the code of the earliest subtree (in traversal order) holding it, kTaskCode - task.+ constexpr uint32_t kDone = 0xFFFF, kTaskCode = 0xFFFE;+ if (++queryEpoch_ == 0x10000) {+ std::fill(vertStamp_.begin(), vertStamp_.end(), 0);+ queryEpoch_ = 1;+ }+ const uint32_t epoch = queryEpoch_ << 16, done = epoch | kDone;+ auto inside = [&](uint32_t v) {+ const glm::vec3 d = mesh.positions[v] - center;+ return glm::dot(d, d) <= r2;+ };- stack_.clear();- stack_.push_back(0);- while (!stack_.empty()) {- const Node& n = nodes_[stack_.back()];- stack_.pop_back();+ // The subtrees the sphere touches at a fixed depth, in the order a depth-first traversal reaches them.+ constexpr int kTaskDepth = 9;+ std::vector<uint32_t>& tasks = queryTasks_;+ tasks.clear();+ std::vector<std::pair<uint32_t, int>> stack{{0u, 0}};+ while (!stack.empty()) {+ const auto [ni, depth] = stack.back();+ stack.pop_back();+ const Node& n = nodes_[ni];if (!sphereBox(n.box, center, r2)) continue;- if (n.count > 0) {+ if (n.count > 0 || depth == kTaskDepth) {+ tasks.push_back(ni);+ continue;+ }+ stack.push_back({n.first, depth + 1});+ stack.push_back({n.first + 1, depth + 1});+ }+ // Visits the vertices of the triangles under node `root` that the sphere's boxes touch, depth first.+ auto walk = [&](uint32_t root, std::vector<uint32_t>& nodeStack, auto&& visit) {+ nodeStack.assign(1, root);+ while (!nodeStack.empty()) {+ const Node& n = nodes_[nodeStack.back()];+ nodeStack.pop_back();+ if (!sphereBox(n.box, center, r2)) continue;+ if (n.count == 0) {+ nodeStack.push_back(n.first);+ nodeStack.push_back(n.first + 1);+ continue;+ }for (uint32_t i = n.first; i < n.first + n.count; ++i) {const auto& t = mesh.triangles[triIndices_[i]];- for (int c = 0; c < 3; ++c) {- uint32_t v = t[c];- if (vertStamp_[v] == s) continue;- vertStamp_[v] = s;- glm::vec3 d = mesh.positions[v] - center;- if (glm::dot(d, d) <= r2) out.push_back(v);- }+ visit(t.x);+ visit(t.y);+ visit(t.z);}- } else {- stack_.push_back(n.first);- stack_.push_back(n.first + 1);}+ };++ if (tasks.size() < 8 || tasks.size() > kTaskCode || ThreadPool::shared().serial()) {+ for (uint32_t root : tasks)+ walk(root, stack_, [&](uint32_t v) {+ if (vertStamp_[v] == done) return;+ vertStamp_[v] = done;+ if (inside(v)) out.push_back(v);+ });+ return;}+ // In parallel, with the serial order: each subtree lists the vertices inside the sphere and claims them+ // (the earliest subtree's code wins: an atomic max); then each lists the ones it owns, in the order it+ // first met them, and the lists are joined in subtree order.+ if (queryParts_.size() < tasks.size()) queryParts_.resize(tasks.size());+ poolFor(tasks.size(), [&](size_t b, size_t e) {+ std::vector<uint32_t> nodeStack;+ for (size_t k = b; k < e; ++k) {+ const uint32_t mine = epoch | (kTaskCode - uint32_t(k));+ std::vector<uint32_t>& found = queryParts_[k];+ found.clear();+ walk(tasks[k], nodeStack, [&](uint32_t v) {+ std::atomic_ref<uint32_t> owner(vertStamp_[v]);+ if (owner.load(std::memory_order_relaxed) == mine || !inside(v)) return;+ found.push_back(v);+ for (uint32_t cur = owner.load(std::memory_order_relaxed);+ cur < mine && !owner.compare_exchange_weak(cur, mine, std::memory_order_relaxed);) {+ }+ });+ }+ }, 1, 2);+ poolFor(tasks.size(), [&](size_t b, size_t e) {+ for (size_t k = b; k < e; ++k) {+ const uint32_t mine = epoch | (kTaskCode - uint32_t(k));+ std::vector<uint32_t>& found = queryParts_[k];+ size_t kept = 0;+ for (uint32_t v : found) {+ std::atomic_ref<uint32_t> owner(vertStamp_[v]);+ if (owner.load(std::memory_order_relaxed) != mine) continue;+ owner.store(done, std::memory_order_relaxed);+ found[kept++] = v;+ }+ found.resize(kept);+ }+ }, 1, 2);+ for (size_t k = 0; k < tasks.size(); ++k) out.insert(out.end(), queryParts_[k].begin(), queryParts_[k].end());}void BVH::refit(const Mesh& mesh, std::span<const uint32_t> movedVerts) {diff --git a/src/core/BVH.h b/src/core/BVH.hindex 46a3f39e..7d8a97a2 100644--- a/src/core/BVH.h+++ b/src/core/BVH.h@@ -52,8 +52,10 @@ private:std::vector<uint32_t> triIndices_;std::vector<uint32_t> triLeaf_;- mutable std::vector<uint32_t> vertStamp_;- mutable uint32_t vertStampValue_ = 0;+ mutable std::vector<uint32_t> vertStamp_; // queryVertices: (epoch << 16) | per-query code+ mutable uint32_t queryEpoch_ = 0;+ mutable std::vector<uint32_t> queryTasks_;+ mutable std::vector<std::vector<uint32_t>> queryParts_;std::vector<uint32_t> leafStamp_;uint32_t leafStampValue_ = 0;std::vector<uint32_t> scratchLeaves_;diff --git a/src/core/Mesh.cpp b/src/core/Mesh.cppindex 6c2ed10d..1d1de78a 100644--- a/src/core/Mesh.cpp+++ b/src/core/Mesh.cpp@@ -249,10 +249,10 @@ void Mesh::updateNormals(std::span<const uint32_t> verts) {const size_t nv = positions.size();if (vertStamp_.size() != nv) return; // no topologygrowDirtyBlocks((nv + kDirtyBlock - 1) / kDirtyBlock);- const uint32_t s = nextStamp();constexpr size_t kBlock = 4096;scratchVerts_.clear();- if (verts.size() <= kBlock) {+ if (verts.size() <= 4 * kBlock || ThreadPool::shared().serial()) {+ const uint32_t s = nextStamp();auto claim = [&](uint32_t u) {if (vertStamp_[u] == s) return;vertStamp_[u] = s;@@ -263,22 +263,35 @@ void Mesh::updateNormals(std::span<const uint32_t> verts) {for (uint32_t u : neighbors(v)) claim(u);}} else {- // Threads claim vertices with an atomic exchange of the stamp: which part lists a shared neighbour- // varies, but the gathered set and every normal computed from it don't.+ // In parallel: first the moved vertices themselves (stamp `own`), then the ring around them that isn't+ // one of them (stamp `ring`, claimed with an atomic exchange: only the ring is shared between blocks).+ // Which block lists a ring vertex varies, but the set, and every normal computed from it, doesn't.+ if (stamp_ >= 0xFFFFFFF0u) { // two stamps in a row: start over first, so they can't wrap in between+ std::fill(vertStamp_.begin(), vertStamp_.end(), 0);+ stamp_ = 0;+ }+ const uint32_t own = nextStamp(), ring = nextStamp();const size_t parts = (verts.size() + kBlock - 1) / kBlock;- if (scratchParts_.size() < parts) scratchParts_.resize(parts);+ if (scratchParts_.size() < 2 * parts) scratchParts_.resize(2 * parts);poolFor(verts.size(), [&](size_t b, size_t e) {std::vector<uint32_t>& out = scratchParts_[b / kBlock];out.clear();- auto claim = [&](uint32_t u) {- if (std::atomic_ref<uint32_t>(vertStamp_[u]).exchange(s, std::memory_order_relaxed) != s) out.push_back(u);- };- for (size_t i = b; i < e; ++i) {- claim(verts[i]);- for (uint32_t u : neighbors(verts[i])) claim(u);- }+ for (size_t i = b; i < e; ++i)+ if (std::atomic_ref<uint32_t>(vertStamp_[verts[i]]).exchange(own, std::memory_order_relaxed) != own)+ out.push_back(verts[i]);+ }, kBlock);+ poolFor(verts.size(), [&](size_t b, size_t e) {+ std::vector<uint32_t>& out = scratchParts_[parts + b / kBlock];+ out.clear();+ for (size_t i = b; i < e; ++i)+ for (uint32_t u : neighbors(verts[i])) {+ std::atomic_ref<uint32_t> stamp(vertStamp_[u]);+ const uint32_t seen = stamp.load(std::memory_order_relaxed);+ if (seen == own || seen == ring) continue;+ if (stamp.exchange(ring, std::memory_order_relaxed) != ring) out.push_back(u);+ }}, kBlock);- for (size_t p = 0; p < parts; ++p) scratchVerts_.insert(scratchVerts_.end(), scratchParts_[p].begin(), scratchParts_[p].end());+ for (size_t p = 0; p < 2 * parts; ++p) scratchVerts_.insert(scratchVerts_.end(), scratchParts_[p].begin(), scratchParts_[p].end());}const size_t n = scratchVerts_.size();diff --git a/src/core/Project.cpp b/src/core/Project.cppindex 6ae8b36f..c9d9aae6 100644--- a/src/core/Project.cpp+++ b/src/core/Project.cpp@@ -51,11 +51,37 @@ enum class Scalar { F32, U32, U8 };const char* scalarName(Scalar s) { return s == Scalar::F32 ? "f32" : s == Scalar::U32 ? "u32" : "u8"; }size_t scalarSize(Scalar s) { return s == Scalar::U8 ? 1 : 4; }-void put32(std::vector<uint8_t>& out, uint32_t v) {+[[maybe_unused]] void put32(std::vector<uint8_t>& out, uint32_t v) {for (int i = 0; i < 4; ++i) out.push_back(uint8_t(v >> (8 * i)));}uint32_t get32(const uint8_t* p) { return uint32_t(p[0]) | uint32_t(p[1]) << 8 | uint32_t(p[2]) << 16 | uint32_t(p[3]) << 24; }+// `n` 32-bit values as little-endian bytes (a plain copy on little-endian machines).+template <class T>+std::vector<uint8_t> littleEndian(const T* v, size_t n) {+ static_assert(sizeof(T) == 4);+ std::vector<uint8_t> data;+ if constexpr (std::endian::native == std::endian::little) {+ data.resize(n * 4);+ if (n) std::memcpy(data.data(), v, n * 4);+ } else {+ data.reserve(n * 4);+ for (size_t i = 0; i < n; ++i) put32(data, std::bit_cast<uint32_t>(v[i]));+ }+ return data;+}++// Reads `n` little-endian 32-bit values (a plain copy on little-endian machines).+template <class T>+void fromLittleEndian(const uint8_t* p, size_t n, T* out) {+ static_assert(sizeof(T) == 4);+ if constexpr (std::endian::native == std::endian::little) {+ if (n) std::memcpy(out, p, n * 4);+ } else {+ for (size_t i = 0; i < n; ++i) out[i] = std::bit_cast<T>(get32(p + 4 * i));+ }+}+class Writer {public:// Adds a blob and returns its manifest descriptor.@@ -69,19 +95,13 @@ public:return d;}Json floats(const std::string& file, const float* v, size_t count, int components) {- std::vector<uint8_t> data;- data.reserve(count * size_t(components) * 4);- for (size_t i = 0; i < count * size_t(components); ++i) put32(data, std::bit_cast<uint32_t>(v[i]));- return add(file, Scalar::F32, components, count, std::move(data));+ return add(file, Scalar::F32, components, count, littleEndian(v, count * size_t(components)));}Json vec3s(const std::string& file, const std::vector<glm::vec3>& v) {return floats(file, v.empty() ? nullptr : &v[0].x, v.size(), 3);}Json uints(const std::string& file, const uint32_t* v, size_t count, int components) {- std::vector<uint8_t> data;- data.reserve(count * size_t(components) * 4);- for (size_t i = 0; i < count * size_t(components); ++i) put32(data, v[i]);- return add(file, Scalar::U32, components, count, std::move(data));+ return add(file, Scalar::U32, components, count, littleEndian(v, count * size_t(components)));}Json bytes(const std::string& file, const std::vector<uint8_t>& v) { return add(file, Scalar::U8, 1, v.size(), v); }@@ -108,7 +128,7 @@ public:bool floats(const Json& desc, const char* what, size_t count, int components, float* out) {const uint8_t* p = blob(desc, what, Scalar::F32, components, count);if (!p) return false;- for (size_t i = 0; i < count * size_t(components); ++i) out[i] = std::bit_cast<float>(get32(p + 4 * i));+ fromLittleEndian(p, count * size_t(components), out);return true;}bool vec3s(const Json& desc, const char* what, size_t count, std::vector<glm::vec3>& out) {@@ -118,7 +138,7 @@ public:bool uints(const Json& desc, const char* what, size_t count, int components, uint32_t* out) {const uint8_t* p = blob(desc, what, Scalar::U32, components, count);if (!p) return false;- for (size_t i = 0; i < count * size_t(components); ++i) out[i] = get32(p + 4 * i);+ fromLittleEndian(p, count * size_t(components), out);return true;}diff --git a/src/core/ThreadPool.cpp b/src/core/ThreadPool.cppindex 623046b0..70443d7c 100644--- a/src/core/ThreadPool.cpp+++ b/src/core/ThreadPool.cpp@@ -40,6 +40,11 @@ void ThreadPool::workerLoop() {uint64_t seen = 0;std::unique_lock lock(mutex_);for (;;) {+ // Brush strokes run one job after another: spin a little before sleeping, so the next dab's job+ // doesn't wait for the thread to wake up.+ lock.unlock();+ for (int i = 0; i < 1000 && generation_.load(std::memory_order_relaxed) == seen; ++i) std::this_thread::yield();+ lock.lock();wake_.wait(lock, [&] { return stop_ || generation_ != seen; });if (stop_) return;seen = generation_;diff --git a/src/core/ThreadPool.h b/src/core/ThreadPool.hindex 45ebf15b..8aaa199d 100644--- a/src/core/ThreadPool.h+++ b/src/core/ThreadPool.h@@ -6,8 +6,7 @@//// poolFor() splits [0, n) into fixed-size blocks: which block a thread takes varies, but the blocks// themselves, and so any per-block partial results combined in block order, don't depend on the thread-// count, so results are deterministic. A range of one block runs inline on the calling thread, exactly as-// a plain loop would.+// count, so results are deterministic. Small ranges run inline on the calling thread.#pragma once#include <algorithm>@@ -58,20 +57,21 @@ private:std::mutex mutex_;std::condition_variable wake_, done_;Run* current_ = nullptr;- uint64_t generation_ = 0;+ std::atomic<uint64_t> generation_{0};bool stop_ = false;std::atomic<bool> serial_{false};};// Calls fn(begin, end) for the blocks [b * block, min(n, (b + 1) * block)) of [0, n) on the shared pool.-// Each block is one call, so per-block partial results indexed by begin / block are deterministic.+// Each block is one call, so per-block partial results indexed by begin / block are deterministic. Fewer than+// `minBlocks` blocks run inline, in order (waking threads would cost more than the work).template <class F>-void poolFor(size_t n, F&& fn, size_t block = 4096) {+void poolFor(size_t n, F&& fn, size_t block = 4096, size_t minBlocks = 4) {if (n == 0) return;block = std::max<size_t>(block, 1);const size_t blocks = (n + block - 1) / block;- if (blocks == 1) {- fn(size_t(0), n);+ if (blocks < std::max<size_t>(minBlocks, 2)) {+ for (size_t b = 0; b < blocks; ++b) fn(b * block, std::min(n, (b + 1) * block));return;}const std::function<void(size_t)> job = [&](size_t b) { fn(b * block, std::min(n, (b + 1) * block)); };diff --git a/src/io/Zip.cpp b/src/io/Zip.cppindex cba404c7..d8f900ca 100644--- a/src/io/Zip.cpp+++ b/src/io/Zip.cpp@@ -2,11 +2,13 @@// SPDX-License-Identifier: GPL-3.0-or-later#include "io/Zip.h"+#include "core/ThreadPool.h"++#include <algorithm>#include <array>#include <cstring>#include <filesystem>#include <fstream>-#include <iterator>namespace sf {@@ -20,90 +22,170 @@ void put32(std::vector<uint8_t>& out, uint32_t v) {put16(out, v & 0xFFFF);put16(out, v >> 16);}+void put64(std::vector<uint8_t>& out, uint64_t v) {+ put32(out, uint32_t(v));+ put32(out, uint32_t(v >> 32));+}uint32_t get16(const uint8_t* p) { return uint32_t(p[0]) | uint32_t(p[1]) << 8; }uint32_t get32(const uint8_t* p) { return get16(p) | get16(p + 2) << 16; }+uint64_t get64(const uint8_t* p) { return uint64_t(get32(p)) | uint64_t(get32(p + 4)) << 32; }-} // namespace+constexpr uint32_t kMax32 = 0xFFFFFFFFu;-uint32_t crc32(const uint8_t* data, size_t size) {- static const auto table = [] {- std::array<uint32_t, 256> t{};+// CRC-32 tables for slicing by 8 (eight bytes per step).+const std::array<std::array<uint32_t, 256>, 8>& crcTables() {+ static const auto tables = [] {+ std::array<std::array<uint32_t, 256>, 8> t{};for (uint32_t i = 0; i < 256; ++i) {uint32_t c = i;for (int k = 0; k < 8; ++k) c = (c & 1) ? 0xEDB88320u ^ (c >> 1) : c >> 1;- t[i] = c;+ t[0][i] = c;}+ for (uint32_t i = 0; i < 256; ++i)+ for (int s = 1; s < 8; ++s) t[size_t(s)][i] = (t[size_t(s) - 1][i] >> 8) ^ t[0][t[size_t(s) - 1][i] & 0xFF];return t;}();+ return tables;+}++std::filesystem::path fsPath(const std::string& p) { return std::filesystem::path(std::u8string(p.begin(), p.end())); }++} // namespace++uint32_t crc32(const uint8_t* data, size_t size) {+ const auto& t = crcTables();uint32_t c = 0xFFFFFFFFu;- for (size_t i = 0; i < size; ++i) c = table[(c ^ data[i]) & 0xFF] ^ (c >> 8);+ size_t i = 0;+ for (; i + 8 <= size; i += 8) {+ const uint32_t lo = c ^ (uint32_t(data[i]) | uint32_t(data[i + 1]) << 8 | uint32_t(data[i + 2]) << 16 |+ uint32_t(data[i + 3]) << 24);+ c = t[7][lo & 0xFF] ^ t[6][(lo >> 8) & 0xFF] ^ t[5][(lo >> 16) & 0xFF] ^ t[4][lo >> 24] ^ t[3][data[i + 4]] ^+ t[2][data[i + 5]] ^ t[1][data[i + 6]] ^ t[0][data[i + 7]];+ }+ for (; i < size; ++i) c = t[0][(c ^ data[i]) & 0xFF] ^ (c >> 8);return c ^ 0xFFFFFFFFu;}-bool writeStoredZip(const std::string& path, const std::vector<ZipEntry>& entries, size_t alignment, std::string& error) {- std::vector<uint8_t> out, central;- for (const auto& e : entries) {- if (e.data.size() > 0xFFFFFFFEu || out.size() > 0xFFFFFFFEu) {- error = "Archive too large (ZIP64 is not supported)";- return false;- }- const uint32_t crc = crc32(e.data.data(), e.data.size());- const uint32_t offset = uint32_t(out.size());+bool writeStoredZip(const std::string& path, const std::vector<ZipEntry>& entries, size_t alignment, std::string& error,+ bool forceZip64) {+ // CRCs first, in parallel (one entry per job: the big arrays of a project are separate entries).+ std::vector<uint32_t> crcs(entries.size());+ poolFor(entries.size(), [&](size_t b, size_t e) {+ for (size_t i = b; i < e; ++i) crcs[i] = crc32(entries[i].data.data(), entries[i].data.size());+ }, 1, 2);++ std::ofstream f(fsPath(path), std::ios::binary);+ if (!f) {+ error = "Cannot write " + path;+ return false;+ }+ // Entries go straight to the file (no copy of the archive in memory). Sizes and offsets that don't fit+ // 32 bits use ZIP64 extra fields; archives under 4 GB come out exactly as before.+ uint64_t offset = 0;+ std::vector<uint8_t> header, central;+ bool anyZip64 = forceZip64;+ for (size_t k = 0; k < entries.size(); ++k) {+ const ZipEntry& e = entries[k];+ const uint64_t size = e.data.size();+ const bool big = forceZip64 || size >= kMax32, farOff = forceZip64 || offset >= kMax32;+ anyZip64 = anyZip64 || big || farOff;+ header.clear();+ const size_t zip64Local = big ? 20 : 0; // id, length, uncompressed and compressed size// Pad with an extra field so the file data starts on an aligned offset.- size_t dataStart = offset + 30 + e.name.size();- size_t pad = alignment > 1 ? (alignment - dataStart % alignment) % alignment : 0;+ const uint64_t dataStart = offset + 30 + e.name.size() + zip64Local;+ size_t pad = alignment > 1 ? size_t((alignment - dataStart % alignment) % alignment) : 0;if (pad > 0 && pad < 4) pad += alignment; // an extra field needs at least its 4-byte header- put32(out, 0x04034B50);- put16(out, 20); // version needed- put16(out, 0); // flags- put16(out, 0); // stored- put16(out, 0); // time- put16(out, 0x21); // date (1980-01-01)- put32(out, crc);- put32(out, uint32_t(e.data.size()));- put32(out, uint32_t(e.data.size()));- put16(out, uint32_t(e.name.size()));- put16(out, uint32_t(pad));- out.insert(out.end(), e.name.begin(), e.name.end());+ put32(header, 0x04034B50);+ put16(header, big ? 45 : 20); // version needed+ put16(header, 0); // flags+ put16(header, 0); // stored+ put16(header, 0); // time+ put16(header, 0x21); // date (1980-01-01)+ put32(header, crcs[k]);+ put32(header, big ? kMax32 : uint32_t(size));+ put32(header, big ? kMax32 : uint32_t(size));+ put16(header, uint32_t(e.name.size()));+ put16(header, uint32_t(zip64Local + pad));+ header.insert(header.end(), e.name.begin(), e.name.end());+ if (big) {+ put16(header, 0x0001);+ put16(header, 16);+ put64(header, size);+ put64(header, size);+ }if (pad) {- put16(out, 0x1986); // padding extra field (same id as Pixar's usdzip)- put16(out, uint32_t(pad - 4));- out.insert(out.end(), pad - 4, 0);+ put16(header, 0x1986); // padding extra field (same id as Pixar's usdzip)+ put16(header, uint32_t(pad - 4));+ header.insert(header.end(), pad - 4, 0);+ }+ if (!f.write(reinterpret_cast<const char*>(header.data()), std::streamsize(header.size())) ||+ !f.write(reinterpret_cast<const char*>(e.data.data()), std::streamsize(size))) {+ error = "Cannot write " + path;+ return false;}- out.insert(out.end(), e.data.begin(), e.data.end());+ std::vector<uint8_t> extra; // ZIP64: the fields saturated below, in this order+ if (big) {+ put64(extra, size);+ put64(extra, size);+ }+ if (farOff) put64(extra, offset);put32(central, 0x02014B50);- put16(central, 20); // version made by- put16(central, 20);+ put16(central, big || farOff ? 45 : 20); // version made by+ put16(central, big || farOff ? 45 : 20);put16(central, 0);put16(central, 0);put16(central, 0);put16(central, 0x21);- put32(central, crc);- put32(central, uint32_t(e.data.size()));- put32(central, uint32_t(e.data.size()));+ put32(central, crcs[k]);+ put32(central, big ? kMax32 : uint32_t(size));+ put32(central, big ? kMax32 : uint32_t(size));put16(central, uint32_t(e.name.size()));- put16(central, 0); // extra+ put16(central, extra.empty() ? 0 : uint32_t(extra.size() + 4)); // extraput16(central, 0); // commentput16(central, 0); // diskput16(central, 0); // internal attributesput32(central, 0); // external attributes- put32(central, offset);+ put32(central, farOff ? kMax32 : uint32_t(offset));central.insert(central.end(), e.name.begin(), e.name.end());+ if (!extra.empty()) {+ put16(central, 0x0001);+ put16(central, uint32_t(extra.size()));+ central.insert(central.end(), extra.begin(), extra.end());+ }+ offset += header.size() + size;}- const uint32_t centralOffset = uint32_t(out.size());- out.insert(out.end(), central.begin(), central.end());- put32(out, 0x06054B50);- put16(out, 0);- put16(out, 0);- put16(out, uint32_t(entries.size()));- put16(out, uint32_t(entries.size()));- put32(out, uint32_t(central.size()));- put32(out, centralOffset);- put16(out, 0);-- std::ofstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);- if (!f || !f.write(reinterpret_cast<const char*>(out.data()), std::streamsize(out.size()))) {+ const uint64_t centralOffset = offset;+ std::vector<uint8_t> tail = std::move(central);+ anyZip64 = anyZip64 || centralOffset >= kMax32 || entries.size() >= 0xFFFF;+ if (anyZip64) {+ // ZIP64 end of central directory record and its locator.+ const uint64_t zip64Eocd = centralOffset + tail.size();+ put32(tail, 0x06064B50);+ put64(tail, 44);+ put16(tail, 45);+ put16(tail, 45);+ put32(tail, 0);+ put32(tail, 0);+ put64(tail, entries.size());+ put64(tail, entries.size());+ put64(tail, zip64Eocd - centralOffset);+ put64(tail, centralOffset);+ put32(tail, 0x07064B50);+ put32(tail, 0);+ put64(tail, zip64Eocd);+ put32(tail, 1);+ }+ const uint64_t centralSize = (anyZip64 ? tail.size() - 76 : tail.size());+ put32(tail, 0x06054B50);+ put16(tail, 0);+ put16(tail, 0);+ put16(tail, anyZip64 ? 0xFFFF : uint32_t(entries.size()));+ put16(tail, anyZip64 ? 0xFFFF : uint32_t(entries.size()));+ put32(tail, anyZip64 ? kMax32 : uint32_t(centralSize));+ put32(tail, anyZip64 ? kMax32 : uint32_t(centralOffset));+ put16(tail, 0);+ if (!f.write(reinterpret_cast<const char*>(tail.data()), std::streamsize(tail.size())) || !f.flush()) {error = "Cannot write " + path;return false;}@@ -111,58 +193,113 @@ bool writeStoredZip(const std::string& path, const std::vector<ZipEntry>& entrie}bool readStoredZip(const std::string& path, std::vector<ZipEntry>& entries, std::string& error) {- std::ifstream f(std::filesystem::path(std::u8string(path.begin(), path.end())), std::ios::binary);+ std::ifstream f(fsPath(path), std::ios::binary);if (!f) {error = "Cannot open " + path;return false;}- std::vector<uint8_t> z((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());- // Find the end-of-central-directory record.+ f.seekg(0, std::ios::end);+ const uint64_t fileSize = uint64_t(f.tellg());+ // Reads `n` bytes at `at` (false past the end).+ auto readAt = [&](uint64_t at, size_t n, void* out) {+ if (at > fileSize || n > fileSize - at) return false;+ f.clear();+ f.seekg(std::streamoff(at));+ return bool(f.read(static_cast<char*>(out), std::streamsize(n)));+ };+ // Find the end-of-central-directory record (in the last 64 KB + 22 bytes).+ const size_t tailSize = size_t(std::min<uint64_t>(fileSize, 65557));+ std::vector<uint8_t> tail(tailSize);+ if (!readAt(fileSize - tailSize, tailSize, tail.data())) {+ error = path + " is not a ZIP/USDZ archive";+ return false;+ }size_t eocd = std::string::npos;- for (size_t i = z.size() >= 22 ? z.size() - 22 : 0; i + 22 <= z.size(); --i) {- if (get32(&z[i]) == 0x06054B50) {+ for (size_t i = tailSize >= 22 ? tailSize - 22 + 1 : 0; i-- > 0;)+ if (get32(&tail[i]) == 0x06054B50) {eocd = i;break;}- if (i == 0 || z.size() - i > 65557) break;- }if (eocd == std::string::npos) {error = path + " is not a ZIP/USDZ archive";return false;}- const size_t count = get16(&z[eocd + 10]);- size_t p = get32(&z[eocd + 16]);+ uint64_t count = get16(&tail[eocd + 10]);+ uint64_t centralSize = get32(&tail[eocd + 12]);+ uint64_t centralOffset = get32(&tail[eocd + 16]);+ // ZIP64: the locator sits right before the record and points at the ZIP64 end of central directory.+ if (eocd >= 20 && get32(&tail[eocd - 20]) == 0x07064B50) {+ uint8_t rec[56];+ if (!readAt(get64(&tail[eocd - 12]), sizeof rec, rec) || get32(rec) != 0x06064B50) {+ error = "Corrupt ZIP64 end of central directory";+ return false;+ }+ count = get64(rec + 32);+ centralSize = get64(rec + 40);+ centralOffset = get64(rec + 48);+ }+ std::vector<uint8_t> z(size_t(std::min<uint64_t>(centralSize, fileSize)));+ if (!readAt(centralOffset, z.size(), z.data())) {+ error = "Corrupt ZIP central directory";+ return false;+ }+ size_t p = 0;entries.clear();- for (size_t k = 0; k < count; ++k) {+ for (uint64_t k = 0; k < count; ++k) {if (p + 46 > z.size() || get32(&z[p]) != 0x02014B50) {error = "Corrupt ZIP central directory";return false;}const uint32_t method = get16(&z[p + 10]);- const uint32_t size = get32(&z[p + 20]);+ uint64_t size = get32(&z[p + 20]);+ const uint64_t compressed = get32(&z[p + 24]);const size_t nameLen = get16(&z[p + 28]), extraLen = get16(&z[p + 30]), commentLen = get16(&z[p + 32]);- const size_t local = get32(&z[p + 42]);- if (p + 46 + nameLen > z.size()) {+ uint64_t local = get32(&z[p + 42]);+ if (p + 46 + nameLen + extraLen > z.size()) {error = "Corrupt ZIP central directory";return false;}ZipEntry e;e.name.assign(reinterpret_cast<const char*>(&z[p + 46]), nameLen);+ // ZIP64 extra field: 64-bit values for whichever of these were saturated, in this order.+ for (size_t x = p + 46 + nameLen; x + 4 <= p + 46 + nameLen + extraLen;) {+ const uint32_t id = get16(&z[x]), len = get16(&z[x + 2]);+ if (x + 4 + len > p + 46 + nameLen + extraLen) break;+ if (id == 0x0001) {+ size_t q = x + 4;+ auto take = [&](uint64_t& v) {+ if (v == kMax32 && q + 8 <= x + 4 + len) {+ v = get64(&z[q]);+ q += 8;+ }+ };+ uint64_t c = compressed;+ take(size);+ take(c);+ take(local);+ }+ x += 4 + len;+ }p += 46 + nameLen + extraLen + commentLen;if (method != 0) {error = "'" + e.name + "' is compressed; USDZ files must be uncompressed";return false;}- if (local + 30 > z.size() || get32(&z[local]) != 0x04034B50) {+ uint8_t lh[30];+ if (!readAt(local, sizeof lh, lh) || get32(lh) != 0x04034B50) {error = "Corrupt ZIP entry " + e.name;return false;}- const size_t data = local + 30 + get16(&z[local + 26]) + get16(&z[local + 28]);- if (data + size > z.size()) {+ const uint64_t data = local + 30 + get16(lh + 26) + get16(lh + 28);+ if (data > fileSize || size > fileSize - data) {+ error = "Truncated ZIP entry " + e.name;+ return false;+ }+ e.data.resize(size_t(size));+ if (size && !readAt(data, size_t(size), e.data.data())) {error = "Truncated ZIP entry " + e.name;return false;}- e.data.assign(z.begin() + std::ptrdiff_t(data), z.begin() + std::ptrdiff_t(data + size));entries.push_back(std::move(e));}return true;diff --git a/src/io/Zip.h b/src/io/Zip.hindex cb285872..6661c4e1 100644--- a/src/io/Zip.h+++ b/src/io/Zip.h@@ -18,10 +18,12 @@ struct ZipEntry {uint32_t crc32(const uint8_t* data, size_t size);-// Writes entries in order with each file's data aligned to `alignment` bytes.-bool writeStoredZip(const std::string& path, const std::vector<ZipEntry>& entries, size_t alignment, std::string& error);+// Writes entries in order with each file's data aligned to `alignment` bytes, streaming them to the file.+// Entries or archives past 4 GB use ZIP64 records (`forceZip64`: always, for tests).+bool writeStoredZip(const std::string& path, const std::vector<ZipEntry>& entries, size_t alignment, std::string& error,+ bool forceZip64 = false);-// Reads a ZIP whose entries are stored (uncompressed), as USDZ requires.+// Reads a ZIP (or ZIP64) whose entries are stored (uncompressed), as USDZ requires.bool readStoredZip(const std::string& path, std::vector<ZipEntry>& entries, std::string& error);} // namespace sfdiff --git a/tests/test_performance.cpp b/tests/test_performance.cppindex 6221293a..a961faf4 100644--- a/tests/test_performance.cpp+++ b/tests/test_performance.cpp@@ -3,7 +3,8 @@//// Performance work (docs/performance.md): the thread pool, brushes / normals / BVH refits that run on it give// the same result as running serially, partial GPU uploads (core/UploadOrder.h) cover every changed vertex, the-// parallel BVH build answers like the serial one, undo after a big stroke is exact, and the benchmark runs.+// parallel BVH build answers like the serial one, undo after a big stroke is exact, project archives stream+// (and use ZIP64 past 4 GB), and the benchmark runs.#include "TestHarness.h"#include "core/Benchmark.h"@@ -11,6 +12,7 @@#include "core/Primitives.h"#include "core/ThreadPool.h"#include "core/UploadOrder.h"+#include "io/Zip.h"#include <atomic>#include <cmath>@@ -296,3 +298,26 @@ TEST(benchmark_smoke) {const Mesh m = makeBenchSphere(50000);CHECK(m.triangleCount() > 40000 && m.triangleCount() < 60000);}++TEST(zip_round_trip_and_zip64) {+ // Stored ZIPs stream to disk; ZIP64 records (used past 4 GB) read back the same.+ std::vector<ZipEntry> entries;+ entries.push_back({"manifest.json", std::vector<uint8_t>{'{', '}'}});+ std::vector<uint8_t> big(300001);+ for (size_t i = 0; i < big.size(); ++i) big[i] = uint8_t(i * 7 + (i >> 9));+ entries.push_back({"data/big.bin", big});+ entries.push_back({"empty.bin", {}});+ CHECK(crc32(reinterpret_cast<const uint8_t*>("123456789"), 9) == 0xCBF43926u); // the standard check value+ for (bool zip64 : {false, true}) {+ const std::string path = tempPath(zip64 ? "sf-zip64.zip" : "sf-zip32.zip");+ std::string error;+ CHECK(writeStoredZip(path, entries, 64, error, zip64));+ std::vector<ZipEntry> back;+ CHECK(readStoredZip(path, back, error));+ CHECK(back.size() == entries.size());+ bool same = back.size() == entries.size();+ for (size_t i = 0; same && i < back.size(); ++i) same = back[i].name == entries[i].name && back[i].data == entries[i].data;+ CHECK(same);+ std::filesystem::remove(path);+ }+}