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.

Starter meshes in the Library, File > New from Starter Mesh and the welcome

islandmed174483cf93d5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f29c9447..0701ee93 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,16 @@ All notable changes to SculptForge are listed here. The format follows
## [Unreleased]
+### Added
+- Starter meshes (Discord #ideas): a human head with eye and mouth loops, a bust, a full body in A-pose, a hand, a
+ foot, an ear, an eye, a stylised head, a creature head blockout (skull, jaw and horns as Parts), a torso, and
+ bevelled rounded box, cylinder, capsule and ring primitives. All quads, centimetres, centred, standing on the
+ ground and symmetric where they should be; they open with subdivision levels over a small base cage (the whole
+ set adds 0.8 MB). **File > New from Starter Mesh**, a **Starter meshes** folder with thumbnails in Library > Tool,
+ **Start from a head** in the welcome, and `new_starter_mesh` for scripts. The human meshes are cut from the
+ MakeHuman base mesh (CC0); the rest are generated by `tools/starter/build_starter_meshes.py`
+ (docs/starter-meshes.md).
+
## [0.10.7] - 2026-11-01
### Changed
diff --git a/CMakeLists.txt b/CMakeLists.txt
index a54b9989..a40ddfba 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -149,6 +149,24 @@ embed_files(${CMAKE_CURRENT_BINARY_DIR}/EmbeddedFace.cpp sf::assets
faceTemplateData ${CMAKE_CURRENT_SOURCE_DIR}/assets/face/ict-arkit.sfface)
target_sources(sculptforge_core PRIVATE src/core/Face.cpp src/core/FaceCommands.cpp
${CMAKE_CURRENT_BINARY_DIR}/EmbeddedFace.cpp)
+# Starter meshes (core/StarterMeshes.h): base cages in compressed projects, built by tools/starter/build.sh from
+# scratch or from the MakeHuman base mesh (CC0; docs/starter-meshes.md).
+embed_files(${CMAKE_CURRENT_BINARY_DIR}/EmbeddedStarterMeshes.cpp sf::assets
+ starterHumanHead ${CMAKE_CURRENT_SOURCE_DIR}/assets/starter/human-head.sfproj.z
+ starterBust ${CMAKE_CURRENT_SOURCE_DIR}/assets/starter/bust.sfproj.z
+ starterFullBody ${CMAKE_CURRENT_SOURCE_DIR}/assets/starter/full-body.sfproj.z
+ starterHand ${CMAKE_CURRENT_SOURCE_DIR}/assets/starter/hand.sfproj.z
+ starterFoot ${CMAKE_CURRENT_SOURCE_DIR}/assets/starter/foot.sfproj.z
+ starterEar ${CMAKE_CURRENT_SOURCE_DIR}/assets/starter/ear.sfproj.z
+ starterEye ${CMAKE_CURRENT_SOURCE_DIR}/assets/starter/eye.sfproj.z
+ starterStylisedHead ${CMAKE_CURRENT_SOURCE_DIR}/assets/starter/stylised-head.sfproj.z
+ starterCreatureHead ${CMAKE_CURRENT_SOURCE_DIR}/assets/starter/creature-head.sfproj.z
+ starterTorso ${CMAKE_CURRENT_SOURCE_DIR}/assets/starter/torso.sfproj.z
+ starterRoundedBox ${CMAKE_CURRENT_SOURCE_DIR}/assets/starter/rounded-box.sfproj.z
+ starterCylinder ${CMAKE_CURRENT_SOURCE_DIR}/assets/starter/cylinder.sfproj.z
+ starterCapsule ${CMAKE_CURRENT_SOURCE_DIR}/assets/starter/capsule.sfproj.z
+ starterRing ${CMAKE_CURRENT_SOURCE_DIR}/assets/starter/ring.sfproj.z)
+target_sources(sculptforge_core PRIVATE src/core/StarterMeshes.cpp ${CMAKE_CURRENT_BINARY_DIR}/EmbeddedStarterMeshes.cpp)
# The PBR viewport's bundled environments (core/EnvironmentMath.h): CC0 HDRIs from Poly Haven, 512 x 256
# (THIRD_PARTY_NOTICES.md).
embed_files(${CMAKE_CURRENT_BINARY_DIR}/EmbeddedHdri.cpp sf::assets
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 61554651..032c5dfb 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -22,6 +22,7 @@ licenses require.
| [JetBrains Mono](https://github.com/JetBrains/JetBrainsMono) | 2.304 | SIL Open Font License 1.1 | The monospace font of the interface looks (Preferences > Interface > Look): labels, numbers and status bar. Regular and SemiBold, embedded in the desktop app. Vendored in assets/fonts. |
| Colour schemes of the Forge Terminal look: [Tokyo Night](https://github.com/enkia/tokyo-night-vscode-theme), [Catppuccin](https://github.com/catppuccin/catppuccin) (Mocha), [Gruvbox](https://github.com/morhetz/gruvbox) (dark), [Nord](https://github.com/nordtheme/nord), [Rosé Pine](https://github.com/rose-pine/rose-pine-theme), [Kanagawa](https://github.com/rebelot/kanagawa.nvim), [Everforest](https://github.com/sainnhe/everforest) (dark) | colour values only | MIT License (each) | The published colour values of each scheme, as data in src/app/LookSchemes.cpp. No code from these projects is included. Credited with thanks below. |
| [Poly Haven](https://polyhaven.com) HDRIs: Brown Photostudio 02, Studio Small 09 (Sergej Majboroda), Kloofendal 48d Partly Cloudy (Pure Sky) (Greg Zaal, sky edits by Jarod Guest) | 1K files, downsampled to 512 x 256 | CC0 1.0 (public domain) | Image-based lighting of the PBR viewport (Material > Viewport Shading). Vendored in assets/hdri and embedded. |
+| [MakeHuman](https://github.com/makehumancommunity/makehuman) base mesh hm08 | commit a8bc2d5 (base.obj, SHA-256 8e761e66...) | CC0 1.0 (public domain) | The human starter meshes (head, bust, full body, hand, foot, ear, stylised head, torso), cut and reshaped by tools/starter/build_starter_meshes.py into assets/starter (embedded). Only the CC0 mesh asset is used, no MakeHuman code (AGPL). See docs/starter-meshes.md. |
| [ICT-FaceKit](https://github.com/ICT-VGL/ICT-FaceKit) (ICT Face Model Light) | commit on master, 2020 | MIT License | The template head of Generate Facial Shapes (Tool > Facial Shapes): its neutral skin, mouth and eye sockets and its 53 ARKit-style expression shapes, converted by tools/face/build_ict_template.py into assets/face/ict-arkit.sfface (embedded). Not the separately licensed full ICT Face Model. |
| [libcurl](https://curl.se) | system library | curl License (MIT/X derivate) | HTTPS for optional AI features on Linux and macOS. Linked dynamically from the operating system; Windows uses the built-in WinHTTP instead. |
| [QR Code generator](https://github.com/nayuki/QR-Code-generator) | 1.8.0 | MIT License | The phone link's pairing QR code (File > Capture from phone). Vendored in third_party/qrcodegen. |
@@ -768,6 +769,17 @@ assets/hdri/kloofendal_48d_partly_cloudy_puresky.hdr (by Greg Zaal, sky edits by
downsampled to 512 x 256. CC0 needs no attribution; it is given here as thanks. No other environment is bundled:
the "Studio" environment is generated in code (src/core/EnvironmentMath.cpp).
+## MakeHuman base mesh
+
+https://github.com/makehumancommunity/makehuman — `makehuman/data/3dobjs/base.obj` (base mesh hm08) at commit
+a8bc2d54ff0ac92e78ff71431b1023eda42bf482, SHA-256 8e761e6624b8f54536409135d1636da63b32486a90d4897f84e121d144f6fb4c,
+downloaded 2026-11-01. The file's header reads: "This asset was explicitly released as CC0 in september 2020",
+copyright holders at the release: Data Collection AB, Joel Palmius, Jonas Hauquier. The repository's LICENSE.md
+(section C) releases the base mesh and the other assets under CC0 1.0 Universal; the full legal text is its
+LICENSE.ASSETS.md (https://creativecommons.org/publicdomain/zero/1.0/legalcode). CC0 needs no attribution; it is
+given here as thanks. The MakeHuman program code (AGPL) is not used. The starter meshes in assets/starter made from
+it are released under CC0 too.
+
## ICT-FaceKit
https://github.com/ICT-VGL/ICT-FaceKit — MIT License. The "ICT Face Model Light" (the repository's FaceXModel
diff --git a/assets/starter/bust.sfproj.z b/assets/starter/bust.sfproj.z
new file mode 100644
index 00000000..62528c27
Binary files /dev/null and b/assets/starter/bust.sfproj.z differ
diff --git a/assets/starter/capsule.sfproj.z b/assets/starter/capsule.sfproj.z
new file mode 100644
index 00000000..66b11a03
Binary files /dev/null and b/assets/starter/capsule.sfproj.z differ
diff --git a/assets/starter/creature-head.sfproj.z b/assets/starter/creature-head.sfproj.z
new file mode 100644
index 00000000..f71ea74a
Binary files /dev/null and b/assets/starter/creature-head.sfproj.z differ
diff --git a/assets/starter/cylinder.sfproj.z b/assets/starter/cylinder.sfproj.z
new file mode 100644
index 00000000..a7ca2ee9
Binary files /dev/null and b/assets/starter/cylinder.sfproj.z differ
diff --git a/assets/starter/ear.sfproj.z b/assets/starter/ear.sfproj.z
new file mode 100644
index 00000000..f3caacc6
Binary files /dev/null and b/assets/starter/ear.sfproj.z differ
diff --git a/assets/starter/eye.sfproj.z b/assets/starter/eye.sfproj.z
new file mode 100644
index 00000000..0b433538
Binary files /dev/null and b/assets/starter/eye.sfproj.z differ
diff --git a/assets/starter/foot.sfproj.z b/assets/starter/foot.sfproj.z
new file mode 100644
index 00000000..c7ac6c35
Binary files /dev/null and b/assets/starter/foot.sfproj.z differ
diff --git a/assets/starter/full-body.sfproj.z b/assets/starter/full-body.sfproj.z
new file mode 100644
index 00000000..d0f790d9
Binary files /dev/null and b/assets/starter/full-body.sfproj.z differ
diff --git a/assets/starter/hand.sfproj.z b/assets/starter/hand.sfproj.z
new file mode 100644
index 00000000..8fe8654e
Binary files /dev/null and b/assets/starter/hand.sfproj.z differ
diff --git a/assets/starter/human-head.sfproj.z b/assets/starter/human-head.sfproj.z
new file mode 100644
index 00000000..fd4825bf
Binary files /dev/null and b/assets/starter/human-head.sfproj.z differ
diff --git a/assets/starter/ring.sfproj.z b/assets/starter/ring.sfproj.z
new file mode 100644
index 00000000..97978563
Binary files /dev/null and b/assets/starter/ring.sfproj.z differ
diff --git a/assets/starter/rounded-box.sfproj.z b/assets/starter/rounded-box.sfproj.z
new file mode 100644
index 00000000..b484f1ec
Binary files /dev/null and b/assets/starter/rounded-box.sfproj.z differ
diff --git a/assets/starter/stylised-head.sfproj.z b/assets/starter/stylised-head.sfproj.z
new file mode 100644
index 00000000..e6d3c325
Binary files /dev/null and b/assets/starter/stylised-head.sfproj.z differ
diff --git a/assets/starter/torso.sfproj.z b/assets/starter/torso.sfproj.z
new file mode 100644
index 00000000..3870db5c
Binary files /dev/null and b/assets/starter/torso.sfproj.z differ
diff --git a/docs/guide/projects.md b/docs/guide/projects.md
index 04045104..275ef65f 100644
--- a/docs/guide/projects.md
+++ b/docs/guide/projects.md
@@ -52,6 +52,36 @@ original model file is left alone.
When you open a project, its saved camera, material and brush settings come back too.
+## Start from a starter mesh
+
+Instead of a sphere, start from a base mesh with clean, even quads: **File > New from Starter Mesh** lists them,
+the Library's **Tool** tab has a **Starter meshes** folder with a thumbnail of each, and the welcome's
+**Start from a head** opens the human head straight away.
+
+| Starter mesh | What it is |
+|---|---|
+| Human Head | A neutral head and neck with loops round the eyes and mouth, for portraits |
+| Bust | Head, neck, shoulders and upper chest |
+| Full Body | A human figure in A-pose, 167 cm tall |
+| Hand, Foot, Ear | A left hand (raised, palm to the front), a left foot and ankle, a left ear |
+| Eye | An eyeball 24 mm across, with the cornea and rings of quads round the pupil |
+| Stylised Head | A cartoon head: big cranium and eyes, small nose and jaw |
+| Creature Head | A dragon or creature blockout: skull, jaw and two horns, each its own [Part](parts.md) |
+| Torso | A human torso from the neck to the upper thighs |
+| Rounded Box, Cylinder, Capsule, Ring | Hard-surface primitives with bevelled edges and quad caps |
+
+Every starter mesh is life size in centimetres, centred, standing on the ground and looking down +Z, and the
+symmetric ones are exactly symmetric, so [X symmetry](sculpting.md) works from the first stroke. The Hand, Foot,
+Ear, Head, Bust and Torso are cut from a body, so they have open edges where they were cut.
+
+A starter mesh opens with subdivision levels (two, or one for the Full Body): block out the big forms at
+**SDiv 1**, the base cage, and step up for the detail (see [Geometry](geometry.md)). It opens as a new, unsaved
+scene: **Save** asks for a name. Double-click a tile to open it; <kbd>Shift</kbd>+double-click appends its base
+cage as a Part, for example an Eye next to a head.
+
+The human meshes come from the MakeHuman base mesh, which MakeHuman released into the public domain (CC0); the
+others are made by SculptForge's own build script. You may use them for anything, including commercial work.
+
## The unsaved-changes prompt
When the scene has unsaved changes, **New Sphere**, **New Plane**, **Open...**, **Open Recent**, dropping a model or
@@ -138,6 +168,7 @@ Double-click a tile to open it (you are asked about unsaved changes first). In t
| `open_project path=work/dragon.sfproj` | Open a project (`open` also recognises `.sfproj`) |
| `open path=scan.obj` | Open a model, splat capture or project |
| `new_sphere subdivisions=6` / `new_plane resolution=128` | Start a new scene |
+| `new_starter_mesh name=human-head` | Start from a starter mesh (`levels=0` for the bare base cage) |
Projects saved by `sculptforge-cli` or Python open in the app too. For the file layout, see
[docs/project-format.md](https://github.com/islandmed/SculptForge/blob/main/docs/project-format.md).
diff --git a/docs/guide/whats-new.md b/docs/guide/whats-new.md
index 83a50cb8..c624d399 100644
--- a/docs/guide/whats-new.md
+++ b/docs/guide/whats-new.md
@@ -5,6 +5,14 @@ chapter opens by itself the first time you start a new version; you can always f
**Help > What's New**. Every detail is in the
[changelog](https://github.com/islandmed/SculptForge/blob/main/CHANGELOG.md).
+## Version 0.10.8
+
+- **Starter meshes**: start a sculpt from a human head with eye and mouth loops, a bust, a full body in A-pose, a
+ hand, a foot, an ear, an eye, a stylised head, a creature head, a torso, or a bevelled box, cylinder, capsule or
+ ring, all clean quads at life size with subdivision levels ready. **File > New from Starter Mesh**, the Library's
+ **Tool > Starter meshes**, or **Start from a head** in the welcome. See
+ [Projects](projects.md#start-from-a-starter-mesh).
+
## Version 0.10.7
- **A clearer membership card**: the three memberships side by side with what each one gets you, in your look's
diff --git a/docs/starter-meshes.md b/docs/starter-meshes.md
new file mode 100644
index 00000000..d79f1399
--- /dev/null
+++ b/docs/starter-meshes.md
@@ -0,0 +1,49 @@
+# Starter meshes: provenance
+
+The starter meshes (File > New from Starter Mesh, Library > Tool > Starter meshes, `new_starter_mesh`;
+src/core/StarterMeshes.h) are the base cages in `assets/starter/*.sfproj.z`: SculptForge projects, zlib-compressed,
+embedded in the program. They open with subdivision levels added (Divide), so the files stay small (0.8 MB for the
+set; the budget is 15 MB, checked by `starter_meshes_set_and_budget`).
+
+**Licensing rule:** only meshes made by our own scripts, or CC0 / public-domain sources recorded here with URL,
+licence and date. Never ZBrush assets or output, nothing scraped.
+
+## Sources
+
+| Mesh | Source | Licence | How it is made |
+|---|---|---|---|
+| Human Head | MakeHuman hm08 base mesh | CC0 1.0 | The body above the neck |
+| Bust | MakeHuman hm08 base mesh | CC0 1.0 | Above the mid chest; arms cut a third of the way down the upper arm |
+| Full Body | MakeHuman hm08 base mesh | CC0 1.0 | The whole "body" group (helpers and joints dropped), A-pose |
+| Hand | MakeHuman hm08 base mesh | CC0 1.0 | The left hand past the wrist, stood up (fingers +Y, palm +Z) |
+| Foot | MakeHuman hm08 base mesh | CC0 1.0 | The left foot below 9 cm over the ankle |
+| Ear | MakeHuman hm08 base mesh | CC0 1.0 | The left ear and the skin round it, turned to face +Z |
+| Stylised Head | MakeHuman hm08 base mesh | CC0 1.0 | The Human Head through a scripted space warp (cranium, eyes, nose, jaw) |
+| Torso | MakeHuman hm08 base mesh | CC0 1.0 | Neck to upper thighs, arms off at the shoulder |
+| Eye | SculptForge (generated) | CC0 1.0 | Surface of revolution on cube topology with a cornea bulge |
+| Creature Head | SculptForge (generated) | CC0 1.0 | Box grids projected onto ellipsoids and warped (skull, jaw); revolved, bent horns |
+| Rounded Box, Cylinder, Capsule, Ring | SculptForge (generated) | CC0 1.0 | Rounded box from a box grid; revolved profiles on cube topology; a swept rounded rectangle |
+
+**MakeHuman hm08 base mesh**: https://github.com/makehumancommunity/makehuman/blob/a8bc2d54ff0ac92e78ff71431b1023eda42bf482/makehuman/data/3dobjs/base.obj,
+SHA-256 `8e761e6624b8f54536409135d1636da63b32486a90d4897f84e121d144f6fb4c`, downloaded 2026-11-01. Licence
+verified that day: the file's header says "This asset was explicitly released as CC0 in september 2020", and the
+repository's [LICENSE.md](https://github.com/makehumancommunity/makehuman/blob/master/LICENSE.md) (section C:
+"The base mesh and proxies ... have been released under CC0 1.0 Universal", full text in LICENSE.ASSETS.md). Only
+the mesh is used; MakeHuman's AGPL code is not. Credited in THIRD_PARTY_NOTICES.md.
+
+## Conventions
+
+Centimetres, Y up, looking down +Z, the character's left is +X. Centred on X and Z (Hand, Foot and Ear too, though
+they are one-sided, not symmetric), lowest point at Y = 0. All quads; edge-manifold; closed except where a
+piece was cut from the body. The symmetric meshes are exactly mirror-symmetric (MakeHuman's mesh is; the generated
+ones are built symmetric). `tests/test_starter_meshes.cpp` checks all of this for every mesh, and
+`tests/ui/starter_meshes.sfui` opens one from the Library.
+
+## Rebuilding
+
+ tools/starter/build.sh build/sculptforge-cli
+
+downloads base.obj at the pinned commit, checks its SHA-256, runs `tools/starter/build_starter_meshes.py`
+(deterministic), saves each OBJ as a project with sculptforge-cli and compresses it into assets/starter. A new mesh
+also needs its line in `starterMeshes()` (src/core/StarterMeshes.cpp) and in the `embed_files` list in
+CMakeLists.txt.
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 08c6194c..e9a003e2 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -2005,8 +2005,8 @@ void App::runCommand(const std::string& name, const Args& args) {
if (r.ok && name == "save_obj" && !doc_.mesh.layers.empty())
status_ += " (OBJ stores the current blend; export GLB to keep layers as blend shapes)";
if (!r.ok) SDL_Log("%s failed: %s", name.c_str(), r.message.c_str());
- if (r.ok && (name == "new_sphere" || name == "new_plane" || name == "new_head" || name == "open_obj" || name == "open" ||
- name == "image_relief" || name == "image_inflate" || name == "splat_to_mesh" ||
+ if (r.ok && (name == "new_sphere" || name == "new_plane" || name == "new_head" || name == "new_starter_mesh" ||
+ name == "open_obj" || name == "open" || name == "image_relief" || name == "image_inflate" || name == "splat_to_mesh" ||
(name == "splat_transform" && args.contains("fit"))))
camera_.frame(sceneBounds());
// A new SubTool lands beside the model: bring it into view only if it isn't already.
diff --git a/src/app/App.h b/src/app/App.h
index 34fbdfa2..efd82af5 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -1295,6 +1295,7 @@ private:
friend void drawMaterialGrid(App&, GridMode);
friend void drawStrokeGrid(App&, GridMode);
void initLightBox(); // end of init(): library folders, thumbnail cache, actions, project thumbnails
+ void showStarterMeshes(); // the Library at Tool > Starter meshes (File > New from Starter Mesh, the welcome)
void drawLightBoxUi(); // every frame from drawUi: thumbnails, the LightBox, pickers, size / strength pop-ups
// The LightBox / picker shortcuts (, B M S) until the action registry dispatches keys.
bool lightBoxKey(SDL_Keycode key, SDL_Keymod mod);
diff --git a/src/app/AssetLibrary.h b/src/app/AssetLibrary.h
index ee2e014a..ef97e333 100644
--- a/src/app/AssetLibrary.h
+++ b/src/app/AssetLibrary.h
@@ -67,6 +67,7 @@ AssetKind fileKindForTab(LibraryTab tab, const std::string& path);
struct LibraryRoots {
std::string builtin; // bundled assets (contains demo/); may be empty
std::string user; // Documents/SculptForge (created on first use)
+ std::string starter; // the starter meshes, unpacked (core/StarterMeshes.h); may be empty
};
// The bundled assets folder: "assets" next to the executable or up to three levels above it.
std::string findBuiltinAssets(const std::string& exeDir);
diff --git a/src/app/Config.cpp b/src/app/Config.cpp
index 7174c9cf..af9a5a48 100644
--- a/src/app/Config.cpp
+++ b/src/app/Config.cpp
@@ -441,6 +441,10 @@ void App::initActions() {
ICON_LC_FILE_PLUS, "new_sphere");
add("file.new_plane", "New Plane", "File", nullptr, [this] { confirmDiscard([this] { runCommand("new_plane"); }); }, nullptr,
"new_plane");
+ add("file.new_starter", "New from Starter Mesh...", "File", nullptr, [this] { showStarterMeshes(); }, nullptr, nullptr,
+ nullptr, nullptr,
+ "Start from a base mesh: human head, bust, full body, hand, foot, ear, eye, stylised and creature heads, "
+ "torso, or a bevelled box, cylinder, capsule or ring (Library > Tool > Starter meshes).");
add("file.open", "Open...", "File", "Ctrl+O", [this] { confirmDiscard([this] { openFileDialog(); }); }, ICON_LC_FOLDER_OPEN,
nullptr, nullptr, nullptr, "Open a project (.sfproj), a model (.obj, .glb, .fbx, .stl, .ply, .usd ...) or splats.");
add("file.save", "Save", "File", "Ctrl+S", [this] { saveProjectAs(false); }, ICON_LC_SAVE, nullptr, nullptr, nullptr,
diff --git a/src/app/LightBox.cpp b/src/app/LightBox.cpp
index 0f234bba..35f25984 100644
--- a/src/app/LightBox.cpp
+++ b/src/app/LightBox.cpp
@@ -10,6 +10,7 @@
#include "core/Matcap.h"
#include "core/Primitives.h"
#include "core/Project.h"
+#include "core/StarterMeshes.h"
#include "render/GL.h"
#include <IconsLucide.h>
@@ -29,6 +30,7 @@ namespace {
namespace fs = std::filesystem;
+constexpr const char* kStarterFolder = "Starter meshes"; // the Tool tab's folder of core/StarterMeshes.h
constexpr float kTile = 96.0f; // thumbnail size (logical px)
constexpr float kLabel = 22.0f; // label under it
constexpr float kGap = 8.0f; // between tiles
@@ -128,6 +130,17 @@ void LightBox::show(LibraryTab tab) {
}
}
+void LightBox::showFolder(LibraryTab tab, const std::string& folder) {
+ open_ = true;
+ Place to{tab, folder};
+ if (to == place_) return;
+ back_.push_back(place_);
+ forward_.clear();
+ place_ = std::move(to);
+ filter_[0] = 0;
+ scrollTo_ = 0.0f;
+}
+
void LightBox::folderChosen(const std::string& path) {
std::lock_guard lock(folderMutex_);
chosenFolder_ = path;
@@ -177,6 +190,7 @@ void LightBox::rootEntries(App& app, std::vector<AssetEntry>& out) {
if (folders) {
const bool builtinHasFiles = !builtinDir.empty() && (tab == LibraryTab::Tool || tab == LibraryTab::Image);
if (builtinHasFiles) folderTile("Built-in", builtinDir);
+ if (tab == LibraryTab::Tool && !roots.starter.empty()) folderTile(kStarterFolder, roots.starter);
if (!userDir.empty()) folderTile("User", userDir);
for (const std::string& r : extraRoots_)
folderTile(utf8(fsPath(r).filename()), r);
@@ -334,7 +348,16 @@ std::vector<AssetEntry> LightBox::entries(App& app) {
up.name = "..";
out.push_back(up);
const LibraryTab tab = place_.tab;
- if (const auto* list = app.libraryScanner_.get(
+ if (place_.folder == app.library_.starter) {
+ // In the set's order (heads first), named as the set names them.
+ for (const StarterMesh& m : starterMeshes()) {
+ AssetEntry e;
+ e.kind = AssetKind::Project;
+ e.name = m.name;
+ e.path = utf8(fsPath(place_.folder) / (std::string(m.id) + kProjectExtension));
+ out.push_back(std::move(e));
+ }
+ } else if (const auto* list = app.libraryScanner_.get(
place_.folder, libraryTabId(tab), [tab](const std::string& p) { return fileKindForTab(tab, p); },
tab == LibraryTab::QuickSave || tab == LibraryTab::Project))
out.insert(out.end(), list->begin(), list->end());
@@ -398,7 +421,7 @@ void LightBox::activate(App& app, const AssetEntry& e, bool append) {
// Leaving the folder a tab started in goes back to the tab's root.
const LibraryRoots& r = app.library_;
const std::string tabUser = r.user.empty() ? std::string() : r.user + "/" + libraryTabFolder(place_.tab);
- const bool atTop = place_.folder == tabUser || place_.folder == r.builtin + "/demo" ||
+ const bool atTop = place_.folder == tabUser || place_.folder == r.builtin + "/demo" || place_.folder == r.starter ||
std::find(extraRoots_.begin(), extraRoots_.end(), place_.folder) != extraRoots_.end();
navigate(app, {place_.tab, atTop ? std::string() : parent});
return;
@@ -426,6 +449,11 @@ void LightBox::activate(App& app, const AssetEntry& e, bool append) {
}
case AssetKind::Project:
case AssetKind::Mesh:
+ if (const StarterMesh* m = starterMeshForPath(app.library_.starter, e.path); m && !append) {
+ const std::string id = m->id;
+ app.confirmDiscard([&app, id] { app.runCommand("new_starter_mesh", {{"name", id}}); });
+ return;
+ }
if (append)
app.runCommand("subtool_append", {{"path", e.path}});
else
@@ -505,6 +533,7 @@ void LightBox::contextMenu(App& app, const AssetEntry& e) {
std::string LightBox::folderLabel(const App& app, const std::string& folder) const {
const LibraryRoots& r = app.library_;
if (!r.builtin.empty() && isUnder(folder, r.builtin)) return "Built-in";
+ if (!r.starter.empty() && isUnder(folder, r.starter)) return kStarterFolder;
if (!r.user.empty() && isUnder(folder, r.user)) return "User";
return utf8(fsPath(folder).filename());
}
@@ -959,6 +988,14 @@ void LightBox::drawPreferences(App& app) {
// App glue: library folders, actions, QuickSave, project thumbnails
// ---------------------------------------------------------------------------
+void App::showStarterMeshes() {
+ if (library_.starter.empty()) {
+ status_ = "The starter meshes could not be unpacked (see the log)";
+ return;
+ }
+ lightbox_.showFolder(LibraryTab::Tool, library_.starter);
+}
+
void App::initLightBox() {
if (const char* base = SDL_GetBasePath()) library_.builtin = findBuiltinAssets(base);
const bool recording = !options_.recordPath.empty() || !options_.renderPath.empty();
@@ -981,6 +1018,19 @@ void App::initLightBox() {
library_.user.clear();
}
}
+ // The starter meshes, unpacked where the thumbnails and the Tool tab's "Starter meshes" folder find them.
+ {
+ fs::path dir;
+ if (!options_.uiTest.empty())
+ dir = fsPath(library_.user).parent_path() / "starter-meshes";
+ else if (!prefDir_.empty())
+ dir = fsPath(prefDir_) / "starter-meshes";
+ std::string err;
+ if (!dir.empty() && writeStarterMeshes(utf8(dir), err))
+ library_.starter = utf8(dir);
+ else if (!dir.empty())
+ SDL_Log("Starter meshes: %s", err.c_str());
+ }
loadMatcapLibrary(); // custom MatCaps (PanelPolypaint.cpp): the library's MatCaps folder exists by now
// Thumbnails are cached on disk for the artist; tests and recordings render fresh ones.
if (interactive() && options_.uiTest.empty() && !prefDir_.empty()) thumbs_.setCacheDir(prefDir_ + "thumbs");
diff --git a/src/app/LightBox.h b/src/app/LightBox.h
index c383af72..21f7e46a 100644
--- a/src/app/LightBox.h
+++ b/src/app/LightBox.h
@@ -31,6 +31,8 @@ public:
void toggle() { open_ = !open_; }
// Shows `tab` (its root) and opens the LightBox.
void show(LibraryTab tab);
+ // Shows `folder` (absolute; "" = the root) in `tab` and opens the LightBox, e.g. the starter meshes.
+ void showFolder(LibraryTab tab, const std::string& folder);
// Preferences > LightBox (the shell's Preferences palette calls this).
void drawPreferences(App& app);
// Height the strip takes over the canvas at `rows` rows (logical px x scale).
diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cpp
index 36025693..3f93fc6f 100644
--- a/src/app/Palettes.cpp
+++ b/src/app/Palettes.cpp
@@ -16,6 +16,7 @@
#include "app/Ui.h"
#include "app/I18n.h"
#include "core/Matcap.h"
+#include "core/StarterMeshes.h"
#include <IconsLucide.h>
@@ -460,6 +461,18 @@ void App::drawPalette_Edit() {
void App::drawPalette_File() {
menuAction(*this, "file.new_sphere");
menuAction(*this, "file.new_plane");
+ if (ImGui::BeginMenu("New from Starter Mesh")) {
+ for (const StarterMesh& m : starterMeshes()) {
+ if (ImGui::MenuItem((std::string(m.name) + "##starter." + m.id).c_str())) {
+ const std::string id = m.id;
+ confirmDiscard([this, id] { runCommand("new_starter_mesh", {{"name", id}}); });
+ }
+ if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", m.description);
+ }
+ ImGui::Separator();
+ menuAction(*this, "file.new_starter");
+ ImGui::EndMenu();
+ }
ImGui::Separator();
menuAction(*this, "file.open");
drawFileMenuProjectItems(); // Open Recent, Save, Save As, autosave
diff --git a/src/app/PanelSupport.cpp b/src/app/PanelSupport.cpp
index 4ebbbcd4..bb76d46e 100644
--- a/src/app/PanelSupport.cpp
+++ b/src/app/PanelSupport.cpp
@@ -8,6 +8,7 @@
#include "app/LookSchemes.h"
#include "app/Theme.h"
+#include <IconsLucide.h>
#include <imgui.h>
#include <algorithm>
@@ -145,6 +146,22 @@ void App::drawSupportUi() {
if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled))
ImGui::SetTooltip("The alphabetical palette bar and the two-row top shelf. Preferences > Interface > Look "
"switches back to the SculptForge layout.");
+ // A base mesh to start from (core/StarterMeshes.h), instead of the sphere.
+ ImGui::Spacing();
+ if (ImGui::Button(ICON_LC_USER_ROUND " Start from a head##welcome")) {
+ confirmDiscard([this] { runCommand("new_starter_mesh", {{"name", std::string("human-head")}}); });
+ showWelcome_ = false;
+ }
+ if (ImGui::IsItemHovered())
+ ImGui::SetTooltip("A neutral human head with clean quads and eye and mouth loops, ready for a portrait.");
+ ImGui::SameLine();
+ if (ImGui::Button("More starter meshes##welcome")) {
+ showStarterMeshes();
+ showWelcome_ = false;
+ }
+ if (ImGui::IsItemHovered())
+ ImGui::SetTooltip("Bust, full body, hand, foot, ear, eye, stylised and creature heads, torso and "
+ "bevelled primitives: Library > Tool > Starter meshes.");
ImGui::Spacing();
if (ImGui::Button("Open the User Guide##welcome")) {
guide_.open();
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index 02ae0080..d28e67b1 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -33,6 +33,7 @@
#include "core/Deform.h"
#include "core/Sculptable.h"
#include "core/Splats.h"
+#include "core/StarterMeshes.h"
#include "core/TextureTransfer.h"
#include "core/Timeline.h"
#include "core/Voxel.h"
@@ -822,6 +823,7 @@ CommandRegistry::CommandRegistry() {
registerMayaCommands(*this); // maya_send/receive (io/MayaCommands.cpp)
registerBakeCommands(*this); // bake (core/Bake.cpp)
registerFaceCommands(*this); // face_shapes_generate, face_weights, ... (core/FaceCommands.cpp)
+ registerStarterMeshCommands(*this); // new_starter_mesh (core/StarterMeshes.h)
registerPackCommands(*this); // pack_install, pack_list, pack_remove, ... (core/Pack.h)
registerMacroCommands(*this); // macro_run, macro_list, macro_check (core/Macro.h)
registerProjectCommands(*this); // keep last (core/Project.cpp)
diff --git a/src/core/StarterMeshes.cpp b/src/core/StarterMeshes.cpp
new file mode 100644
index 00000000..92c26961
--- /dev/null
+++ b/src/core/StarterMeshes.cpp
@@ -0,0 +1,231 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/StarterMeshes.h"
+
+#include "core/Multires.h"
+#include "core/Project.h"
+
+#include <stb_image.h>
+
+#include <algorithm>
+#include <atomic>
+#include <cctype>
+#include <chrono>
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+#include <memory>
+
+// assets/starter/*.sfproj.z (tools/starter/build.sh), embedded by CMakeLists.txt.
+namespace sf::assets {
+#define SF_STARTER(sym) \
+ extern const unsigned char sym[]; \
+ extern const unsigned long long sym##_size;
+SF_STARTER(starterHumanHead)
+SF_STARTER(starterBust)
+SF_STARTER(starterFullBody)
+SF_STARTER(starterHand)
+SF_STARTER(starterFoot)
+SF_STARTER(starterEar)
+SF_STARTER(starterEye)
+SF_STARTER(starterStylisedHead)
+SF_STARTER(starterCreatureHead)
+SF_STARTER(starterTorso)
+SF_STARTER(starterRoundedBox)
+SF_STARTER(starterCylinder)
+SF_STARTER(starterCapsule)
+SF_STARTER(starterRing)
+#undef SF_STARTER
+} // namespace sf::assets
+
+namespace sf {
+
+namespace {
+
+namespace fs = std::filesystem;
+
+fs::path pathOf(const std::string& p) { return fs::path(std::u8string(p.begin(), p.end())); }
+std::string utf8Of(const fs::path& p) {
+ const std::u8string s = p.u8string();
+ return std::string(s.begin(), s.end());
+}
+
+std::string lowerAscii(std::string_view s) {
+ std::string out(s);
+ for (char& c : out) c = char(std::tolower(static_cast<unsigned char>(c)));
+ return out;
+}
+
+bool readFile(const fs::path& p, std::vector<uint8_t>& out) {
+ std::ifstream f(p, std::ios::binary);
+ if (!f) return false;
+ out.assign(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
+ return true;
+}
+
+bool writeFile(const fs::path& p, const std::vector<uint8_t>& data) {
+ std::ofstream f(p, std::ios::binary | std::ios::trunc);
+ return f && f.write(reinterpret_cast<const char*>(data.data()), std::streamsize(data.size())) && f.flush();
+}
+
+} // namespace
+
+const std::vector<StarterMesh>& starterMeshes() {
+ using namespace assets;
+#define SF_DATA(sym) sym, size_t(sym##_size)
+ static const std::vector<StarterMesh> all = {
+ {"human-head", "Human Head", "A neutral human head and neck with eye and mouth loops, for portraits.", 2, true,
+ false, SF_DATA(starterHumanHead)},
+ {"bust", "Bust", "Head, neck, shoulders and upper chest.", 2, true, false, SF_DATA(starterBust)},
+ {"full-body", "Full Body", "A full human figure in A-pose, 167 cm tall.", 1, true, true, SF_DATA(starterFullBody)},
+ {"hand", "Hand", "A left hand, raised with the palm to the front.", 2, false, false, SF_DATA(starterHand)},
+ {"foot", "Foot", "A left foot and ankle.", 2, false, false, SF_DATA(starterFoot)},
+ {"ear", "Ear", "A left ear with a little of the head round it, facing the front.", 2, false, false,
+ SF_DATA(starterEar)},
+ {"eye", "Eye", "An eyeball, 24 mm across, with the cornea and rings round the pupil.", 2, true, true,
+ SF_DATA(starterEye)},
+ {"stylised-head", "Stylised Head", "A cartoon head: big cranium and eyes, small nose and jaw.", 2, true, false,
+ SF_DATA(starterStylisedHead)},
+ {"creature-head", "Creature Head", "A dragon or creature head blockout: skull, jaw and two horns as Parts.", 2,
+ true, true, SF_DATA(starterCreatureHead)},
+ {"torso", "Torso", "A human torso from the neck to the upper thighs.", 2, true, false, SF_DATA(starterTorso)},
+ {"rounded-box", "Rounded Box", "A 20 cm box with rounded edges.", 2, true, true, SF_DATA(starterRoundedBox)},
+ {"cylinder", "Cylinder", "A 20 cm cylinder with bevelled rims and quad caps.", 2, true, true,
+ SF_DATA(starterCylinder)},
+ {"capsule", "Capsule", "A 30 cm capsule.", 2, true, true, SF_DATA(starterCapsule)},
+ {"ring", "Ring", "A ring with a bevelled, squared cross-section.", 2, true, true, SF_DATA(starterRing)},
+ };
+#undef SF_DATA
+ return all;
+}
+
+const StarterMesh* findStarterMesh(std::string_view idOrName) {
+ const std::string want = lowerAscii(idOrName);
+ if (want.empty()) return nullptr;
+ for (const StarterMesh& m : starterMeshes())
+ if (want == m.id || want == lowerAscii(m.name)) return &m;
+ if (want == "head") return findStarterMesh("human-head");
+ return nullptr;
+}
+
+bool unpackStarterMesh(const StarterMesh& mesh, std::vector<uint8_t>& project, std::string& error) {
+ int len = 0;
+ std::unique_ptr<char, decltype(&std::free)> out(
+ stbi_zlib_decode_malloc(reinterpret_cast<const char*>(mesh.data), int(mesh.size), &len), &std::free);
+ if (!out || len <= 0) {
+ error = std::string("The starter mesh ") + mesh.name + " is damaged";
+ return false;
+ }
+ project.assign(out.get(), out.get() + len);
+ return true;
+}
+
+bool writeStarterMeshes(const std::string& dir, std::string& error) {
+ std::error_code ec;
+ fs::create_directories(pathOf(dir), ec);
+ if (ec) {
+ error = "Cannot create " + dir + ": " + ec.message();
+ return false;
+ }
+ std::vector<uint8_t> data, existing;
+ for (const StarterMesh& m : starterMeshes()) {
+ if (!unpackStarterMesh(m, data, error)) return false;
+ const fs::path p = pathOf(dir) / (std::string(m.id) + kProjectExtension);
+ if (readFile(p, existing) && existing == data) continue;
+ // Written next to it and renamed, so a thumbnail worker never reads half a file.
+ const fs::path tmp = fs::path(p).concat(".part");
+ if (!writeFile(tmp, data)) {
+ error = "Cannot write " + utf8Of(p);
+ return false;
+ }
+ fs::rename(tmp, p, ec);
+ if (ec) {
+ fs::remove(tmp, ec);
+ error = "Cannot write " + utf8Of(p);
+ return false;
+ }
+ }
+ return true;
+}
+
+const StarterMesh* starterMeshForPath(const std::string& dir, const std::string& path) {
+ if (dir.empty() || path.empty()) return nullptr;
+ const fs::path p = pathOf(path);
+ if (p.parent_path().lexically_normal() != pathOf(dir).lexically_normal()) return nullptr;
+ if (lowerAscii(utf8Of(p.extension())) != kProjectExtension) return nullptr;
+ const std::string id = utf8Of(p.stem());
+ for (const StarterMesh& m : starterMeshes())
+ if (id == m.id) return &m;
+ return nullptr;
+}
+
+bool loadStarterMesh(const StarterMesh& mesh, Document& doc, int levels, std::string& error) {
+ std::vector<uint8_t> data;
+ if (!unpackStarterMesh(mesh, data, error)) return false;
+ // loadProject reads files: a private temporary copy, removed right after.
+ static std::atomic<unsigned> counter{0};
+ std::error_code ec;
+ const auto stamp = std::chrono::steady_clock::now().time_since_epoch().count();
+ const fs::path tmp = fs::temp_directory_path(ec) / ("sculptforge-starter-" + std::to_string(stamp) + "-" +
+ std::to_string(counter++) + kProjectExtension);
+ if (ec || !writeFile(tmp, data)) {
+ fs::remove(tmp, ec);
+ error = "Cannot write a temporary file for the starter mesh";
+ return false;
+ }
+ Document loaded;
+ const bool ok = loadProject(utf8Of(tmp), loaded, error);
+ fs::remove(tmp, ec);
+ if (!ok) return false;
+
+ if (levels < 0) levels = mesh.levels;
+ levels = std::clamp(levels, 0, 4);
+ struct Part {
+ Mesh mesh;
+ std::string name;
+ };
+ std::vector<Part> parts;
+ for (int i = 0; i < int(loaded.subtools.size()); ++i) {
+ Part p{std::move(loaded.subtoolMesh(i)), loaded.subtools[size_t(i)].name};
+ for (int l = 0; l < levels; ++l)
+ if (!subdivDivide(p.mesh, true, error)) return false;
+ parts.push_back(std::move(p));
+ }
+ if (parts.empty()) {
+ error = std::string("The starter mesh ") + mesh.name + " is empty";
+ return false;
+ }
+ if (parts.size() == 1) parts[0].name = mesh.name; // a one-object OBJ named its Part after the file
+ doc.setMesh(std::move(parts[0].mesh), parts[0].name);
+ for (size_t i = 1; i < parts.size(); ++i) doc.addSubtool(std::move(parts[i].mesh), parts[i].name, false);
+ doc.selectSubtool(0);
+ doc.path.clear();
+ return true;
+}
+
+void registerStarterMeshCommands(CommandRegistry& registry) {
+ using T = ParamSpec::Type;
+ std::string names;
+ for (const StarterMesh& m : starterMeshes()) names += std::string(names.empty() ? "" : ", ") + m.id;
+ registry.add({"new_starter_mesh",
+ "New scene from a starter mesh: an all-quad base mesh to sculpt on (centimetres, standing on the "
+ "ground), opened with subdivision levels so you can step down to the base cage. Names: " +
+ names + ".",
+ {{"name", T::String, "Which starter mesh, e.g. human-head, bust, full-body, creature-head.", true},
+ {"levels", T::Number, "Subdivision levels to add (0-4; default: the mesh's own, 1 or 2).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const std::string want = argString(a, "name");
+ const StarterMesh* m = findStarterMesh(want);
+ if (!m) return {false, "No starter mesh called \"" + want + "\""};
+ std::string error;
+ if (!loadStarterMesh(*m, doc, int(argNumber(a, "levels", -1)), error)) return {false, error};
+ size_t vertices = 0;
+ for (int i = 0; i < int(doc.subtools.size()); ++i) vertices += doc.subtoolMesh(i).vertexCount();
+ const std::string levels = subdivLevelText(doc.mesh);
+ return {true, std::string("New ") + m->name + " (" + std::to_string(vertices) + " vertices" +
+ (levels.empty() ? std::string() : ", " + levels) + ")"};
+ }});
+}
+
+} // namespace sf
diff --git a/src/core/StarterMeshes.h b/src/core/StarterMeshes.h
new file mode 100644
index 00000000..307492ca
--- /dev/null
+++ b/src/core/StarterMeshes.h
@@ -0,0 +1,51 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Starter meshes: base meshes to start a sculpt from (Library > Tool > Starter meshes, File > New from starter
+// mesh, the welcome's "Start from a head"). Each is a small all-quad base cage in a project file, compressed and
+// embedded in the program; opening one adds its subdivision levels (Divide), so the files stay small and the
+// artist can step down to the cage. Centimetres, Y up, looking down +Z, standing on the ground.
+//
+// Sources: made by tools/starter/build_starter_meshes.py, from scratch or cut from the MakeHuman base mesh (CC0);
+// docs/starter-meshes.md has the provenance.
+#pragma once
+
+#include "core/Commands.h"
+#include "core/Document.h"
+
+#include <cstdint>
+#include <string>
+#include <string_view>
+#include <vector>
+
+namespace sf {
+
+struct StarterMesh {
+ const char* id; // "human-head" (new_starter_mesh name=, the unpacked file's name)
+ const char* name; // "Human Head"
+ const char* description; // one line for tooltips
+ int levels; // Divide this many times on open
+ bool symmetric; // mirror-symmetric in X
+ bool closed; // no open edges (the cut pieces have one or more open borders)
+ const unsigned char* data;
+ size_t size; // compressed bytes
+};
+
+const std::vector<StarterMesh>& starterMeshes();
+// By id or name, case-insensitive ("head" finds Human Head too); null if none.
+const StarterMesh* findStarterMesh(std::string_view idOrName);
+// The project file's bytes (zlib-decompressed). False with `error` if the embedded data is damaged.
+bool unpackStarterMesh(const StarterMesh& mesh, std::vector<uint8_t>& project, std::string& error);
+// Writes every starter mesh's project to `dir`/<id>.sfproj (creating `dir`; files already identical are left
+// alone, so their thumbnails stay cached). False with `error` on the first failure.
+bool writeStarterMeshes(const std::string& dir, std::string& error);
+// The starter mesh `path` is a copy of (a file writeStarterMeshes wrote to `dir`), or null.
+const StarterMesh* starterMeshForPath(const std::string& dir, const std::string& path);
+// Replaces the scene with the starter mesh, divided `levels` times (-1 = its own count); every Part keeps its
+// name, doc.path stays empty (Save asks where). On failure `doc` is untouched.
+bool loadStarterMesh(const StarterMesh& mesh, Document& doc, int levels, std::string& error);
+
+// new_starter_mesh (called by the CommandRegistry constructor).
+void registerStarterMeshCommands(CommandRegistry& registry);
+
+} // namespace sf
diff --git a/tests/test_starter_meshes.cpp b/tests/test_starter_meshes.cpp
new file mode 100644
index 00000000..f15623dd
--- /dev/null
+++ b/tests/test_starter_meshes.cpp
@@ -0,0 +1,157 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Starter meshes (core/StarterMeshes.h): every one unpacks and loads, is all quads, edge-manifold (closed where
+// it should be), mirror-symmetric where it should be, centred and standing on the ground at a life-like size;
+// the set stays inside its size budget; new_starter_mesh adds the subdivision levels and leaves no path.
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/Multires.h"
+#include "core/Project.h"
+#include "core/StarterMeshes.h"
+
+#include <cmath>
+#include <cstdint>
+#include <filesystem>
+#include <map>
+#include <set>
+#include <tuple>
+
+using namespace sf;
+
+namespace {
+
+Document load(const StarterMesh& m, int levels) {
+ Document d;
+ std::string error;
+ CHECK(loadStarterMesh(m, d, levels, error));
+ if (!error.empty()) std::printf(" %s: %s\n", m.id, error.c_str());
+ return d;
+}
+
+} // namespace
+
+TEST(starter_meshes_set_and_budget) {
+ const auto& all = starterMeshes();
+ CHECK(all.size() == 14);
+ size_t total = 0;
+ std::set<std::string> ids;
+ for (const StarterMesh& m : all) {
+ total += m.size;
+ CHECK(ids.insert(m.id).second);
+ CHECK(findStarterMesh(m.id) == &m);
+ CHECK(findStarterMesh(m.name) == &m);
+ CHECK(m.levels >= 1 && m.levels <= 3);
+ }
+ CHECK(findStarterMesh("head") == findStarterMesh("human-head"));
+ CHECK(findStarterMesh("zsphere") == nullptr);
+ CHECK(total < size_t(15) * 1000 * 1000); // the brief's budget; the set is about 1 MB
+ std::printf(" starter meshes: %zu bytes compressed\n", total);
+}
+
+TEST(starter_meshes_topology_symmetry_and_placement) {
+ for (const StarterMesh& m : starterMeshes()) {
+ Document d = load(m, 0);
+ CHECK(!d.subtools.empty());
+ AABB box;
+ // Mirror check: every vertex of every Part has a partner at (-x, y, z) within 0.01 mm.
+ std::set<std::tuple<long, long, long>> points;
+ auto key = [](glm::vec3 p) {
+ return std::make_tuple(std::lround(p.x * 1000.0f), std::lround(p.y * 1000.0f), std::lround(p.z * 1000.0f));
+ };
+ for (int i = 0; i < int(d.subtools.size()); ++i) {
+ const Mesh& mesh = d.subtoolMesh(i);
+ CHECK(mesh.vertexCount() > 100);
+ // All quads: every triangle is paired.
+ CHECK(mesh.quadPartners.size() == mesh.triangleCount());
+ size_t unpaired = 0;
+ for (uint32_t q : mesh.quadPartners) unpaired += q == Mesh::kNoQuad;
+ CHECK(unpaired == 0);
+ std::map<std::pair<uint32_t, uint32_t>, int> edges;
+ for (const glm::uvec3& t : mesh.triangles)
+ for (int k = 0; k < 3; ++k) {
+ const uint32_t a = t[k], b = t[(k + 1) % 3];
+ ++edges[{std::min(a, b), std::max(a, b)}];
+ }
+ size_t open = 0, nonManifold = 0;
+ for (const auto& edge : edges) {
+ open += edge.second == 1;
+ nonManifold += edge.second > 2;
+ }
+ CHECK(nonManifold == 0);
+ if (m.closed) CHECK(open == 0);
+ else CHECK(open > 0);
+ for (const glm::vec3& p : mesh.positions) {
+ box.expand(p);
+ points.insert(key(p));
+ }
+ }
+ if (m.symmetric) {
+ size_t missing = 0;
+ for (int i = 0; i < int(d.subtools.size()); ++i)
+ for (const glm::vec3& p : d.subtoolMesh(i).positions) {
+ const auto [x, y, z] = key(glm::vec3(-p.x, p.y, p.z));
+ bool found = false;
+ for (long dx = -1; dx <= 1 && !found; ++dx)
+ for (long dy = -1; dy <= 1 && !found; ++dy)
+ for (long dz = -1; dz <= 1 && !found; ++dz)
+ found = points.count({x + dx, y + dy, z + dz}) > 0;
+ missing += !found;
+ }
+ if (missing) std::printf(" %s: %zu vertices without a mirror partner\n", m.id, missing);
+ CHECK(missing == 0);
+ }
+ // Standing on the ground, centred, between 2 cm (the eye) and 2 m (the figure).
+ CHECK(std::abs(box.min.y) < 0.01f);
+ CHECK(std::abs(box.min.x + box.max.x) < 0.01f);
+ CHECK(std::abs(box.min.z + box.max.z) < 0.01f);
+ const glm::vec3 size = box.max - box.min;
+ const float longest = std::max({size.x, size.y, size.z});
+ CHECK(longest > 2.0f && longest < 200.0f);
+ CHECK(d.path.empty());
+ }
+}
+
+TEST(starter_meshes_open_with_levels) {
+ CommandRegistry registry;
+ Document d;
+ CommandResult r = registry.execute(d, "new_starter_mesh", {{"name", std::string("human-head")}});
+ CHECK(r.ok);
+ CHECK(subdivLevelCount(d.mesh) == 3);
+ CHECK(subdivCurrentLevel(d.mesh) == 2);
+ CHECK(d.mesh.vertexCount() > 60000);
+ CHECK(d.path.empty());
+ CHECK(d.subtools.size() == 1 && d.subtools[0].name == "Human Head");
+ // Multi-Part: every Part gets its levels.
+ r = registry.execute(d, "new_starter_mesh", {{"name", std::string("Creature Head")}, {"levels", 1.0}});
+ CHECK(r.ok);
+ CHECK(d.subtools.size() == 4);
+ for (int i = 0; i < int(d.subtools.size()); ++i) CHECK(subdivLevelCount(d.subtoolMesh(i)) == 2);
+ CHECK(!registry.execute(d, "new_starter_mesh", {{"name", std::string("no-such-mesh")}}).ok);
+ CHECK(d.subtools.size() == 4); // a failure leaves the scene alone
+}
+
+TEST(starter_meshes_unpack_to_folder) {
+ namespace fs = std::filesystem;
+ const fs::path dir = fs::temp_directory_path() / "sculptforge-test-starter-meshes";
+ std::error_code ec;
+ fs::remove_all(dir, ec);
+ std::string error;
+ CHECK(writeStarterMeshes(dir.string(), error));
+ const fs::path head = dir / "human-head.sfproj";
+ CHECK(fs::exists(head));
+ const auto written = fs::last_write_time(head, ec);
+ CHECK(writeStarterMeshes(dir.string(), error)); // identical files stay as they are (cached thumbnails)
+ CHECK(fs::last_write_time(head, ec) == written);
+ CHECK(starterMeshForPath(dir.string(), head.string()) == findStarterMesh("human-head"));
+ CHECK(starterMeshForPath(dir.string(), (dir / "other.sfproj").string()) == nullptr);
+ CHECK(starterMeshForPath((dir / "x").string(), head.string()) == nullptr);
+ Document d;
+ CHECK(loadProject(head.string(), d, error)); // a plain project the thumbnails and Open read
+ CHECK(d.mesh.vertexCount() > 1000);
+ size_t files = 0;
+ for (const auto& e : fs::directory_iterator(dir)) files += e.path().extension() == ".sfproj";
+ CHECK(files == starterMeshes().size());
+ fs::remove_all(dir, ec);
+}
diff --git a/tests/ui/starter_meshes.sfui b/tests/ui/starter_meshes.sfui
new file mode 100644
index 00000000..27a848e2
--- /dev/null
+++ b/tests/ui/starter_meshes.sfui
@@ -0,0 +1,38 @@
+# Starter meshes (core/StarterMeshes.h): the Library's Tool tab has a "Starter meshes" folder with a thumbnail for
+# each; double-clicking one opens it as a new, unsaved scene with its subdivision levels, and File > New from
+# Starter Mesh opens the Library there.
+run new_plane resolution=8
+expect_value triangles == 128
+
+key ,
+expect_value lightbox_open == 1
+click "Library/Tool"
+expect "Library/Starter meshes"
+double_click "Library/Starter meshes"
+wait_idle 60
+expect "Library/Human Head"
+expect "Library/Bust"
+expect "Library/Full Body"
+expect_not "Library/Sphere"
+shot starter-meshes
+
+double_click "Library/Human Head"
+expect_status New Human Head
+expect_value subtools == 1
+expect_value vertices > 60000
+expect_value dirty == 0
+
+# Shift+double-click appends the base cage as a Part (an eye next to the head).
+hold shift
+double_click "Library/Eye"
+hold none
+expect_value subtools == 2
+
+# ".." goes back to the Tool tab's root.
+double_click "Library/.."
+expect "Library/Sphere"
+expect "Library/Starter meshes"
+
+# The command scripts and the File menu use.
+run new_starter_mesh name=creature-head levels=0
+expect_value subtools == 4
diff --git a/tests/ui/whats_new.sfui b/tests/ui/whats_new.sfui
index 6b70eb9d..8c91df6d 100644
--- a/tests/ui/whats_new.sfui
+++ b/tests/ui/whats_new.sfui
@@ -5,8 +5,9 @@ click "Help##palette.help"
click "What's New##help.whats_new"
expect_value guide_open == 1
expect_guide whats-new.md
+expect_text "Version 0.10.8"
+expect_text "Starter meshes"
expect_text "Version 0.10.7"
-expect_text "A new look"
expect_text "Version 0.10.6"
expect_text "Version 0.10.5"
expect_text "Version 0.10.4"
diff --git a/tools/starter/build.sh b/tools/starter/build.sh
new file mode 100755
index 00000000..c38dad43
--- /dev/null
+++ b/tools/starter/build.sh
@@ -0,0 +1,28 @@
+#!/bin/sh
+# SculptForge - open source digital sculpting
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# Rebuilds assets/starter/*.sfproj.z (the starter meshes, core/StarterMeshes.h) from scratch:
+# tools/starter/build.sh <sculptforge-cli>
+# Downloads the MakeHuman hm08 base mesh (CC0) at a pinned commit and checks its SHA-256 first
+# (docs/starter-meshes.md), builds the OBJ cages, saves each as a project and compresses it.
+set -eu
+CLI=${1:?usage: tools/starter/build.sh <sculptforge-cli>}
+ROOT=$(cd "$(dirname "$0")/../.." && pwd)
+WORK=${STARTER_WORK:-$ROOT/build/starter-meshes}
+MH_COMMIT=a8bc2d54ff0ac92e78ff71431b1023eda42bf482
+MH_SHA256=8e761e6624b8f54536409135d1636da63b32486a90d4897f84e121d144f6fb4c
+mkdir -p "$WORK/makehuman" "$WORK/obj"
+BASE="$WORK/makehuman/base.obj"
+if [ ! -f "$BASE" ]; then
+ curl -fsSL -o "$BASE" "https://raw.githubusercontent.com/makehumancommunity/makehuman/$MH_COMMIT/makehuman/data/3dobjs/base.obj"
+fi
+echo "$MH_SHA256 $BASE" | sha256sum -c -
+python3 -I "$ROOT/tools/starter/build_starter_meshes.py" "$BASE" "$WORK/obj"
+for obj in "$WORK"/obj/*.obj; do
+ id=$(basename "$obj" .obj)
+ "$CLI" -q -c "open_obj path=$obj; save_project path=$WORK/obj/$id.sfproj"
+ python3 -I -c 'import sys, zlib; open(sys.argv[2], "wb").write(zlib.compress(open(sys.argv[1], "rb").read(), 9))' \
+ "$WORK/obj/$id.sfproj" "$ROOT/assets/starter/$id.sfproj.z"
+done
+ls -l "$ROOT"/assets/starter/*.sfproj.z | awk '{ s += $5 } END { printf "assets/starter: %d files, %.2f MB\n", NR, s / 1e6 }'
diff --git a/tools/starter/build_starter_meshes.py b/tools/starter/build_starter_meshes.py
new file mode 100644
index 00000000..a5c6d3ea
--- /dev/null
+++ b/tools/starter/build_starter_meshes.py
@@ -0,0 +1,610 @@
+#!/usr/bin/env python3
+# SculptForge - open source digital sculpting
+# SPDX-License-Identifier: GPL-3.0-or-later
+#
+# Builds the starter meshes (Library > Tool > Starter meshes, File > New from starter mesh) as OBJ base cages.
+# Everything is either made here from scratch (the eye, the stylised and creature heads' extra Parts, the
+# bevelled primitives) or cut from the MakeHuman hm08 base mesh, which MakeHuman released under CC0 1.0
+# (docs/starter-meshes.md has the provenance). Deterministic: the same input gives the same bytes.
+#
+# Usage: build_starter_meshes.py <makehuman base.obj> <out dir>
+# tools/starter/build.sh runs this, then sculptforge-cli (OBJ -> .sfproj) and compresses the projects.
+#
+# Units are centimetres, Y up, looking down +Z, the character's left is +X; every mesh is centred on X and Z
+# and stands on the ground (lowest point at Y = 0). All faces are quads.
+
+import math
+import os
+import sys
+from collections import Counter, defaultdict
+
+# ---------------------------------------------------------------------------
+# Small vector helpers
+# ---------------------------------------------------------------------------
+
+
+def add(a, b): return (a[0] + b[0], a[1] + b[1], a[2] + b[2])
+def sub(a, b): return (a[0] - b[0], a[1] - b[1], a[2] - b[2])
+def mul(a, s): return (a[0] * s, a[1] * s, a[2] * s)
+def dot(a, b): return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
+def cross(a, b): return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
+def length(a): return math.sqrt(dot(a, a))
+def norm(a):
+ l = length(a)
+ return mul(a, 1.0 / l) if l > 1e-12 else (0.0, 0.0, 0.0)
+def lerp(a, b, t): return a + (b - a) * t
+def smoothstep(e0, e1, x):
+ t = min(1.0, max(0.0, (x - e0) / (e1 - e0)))
+ return t * t * (3 - 2 * t)
+
+
+class Mesh:
+ """Quads only: verts [(x,y,z)], faces [(a,b,c,d)], CCW seen from outside."""
+
+ def __init__(self, verts=None, faces=None):
+ self.verts = list(verts or [])
+ self.faces = list(faces or [])
+
+ def transformed(self, fn):
+ return Mesh([fn(v) for v in self.verts], self.faces)
+
+
+def bounds(meshes):
+ lo = [1e30] * 3
+ hi = [-1e30] * 3
+ for m in meshes:
+ for v in m.verts:
+ for k in range(3):
+ lo[k] = min(lo[k], v[k])
+ hi[k] = max(hi[k], v[k])
+ return lo, hi
+
+
+def place_on_ground(parts):
+ """Centres the Parts together on X and Z and puts the lowest point at Y = 0."""
+ lo, hi = bounds(parts)
+ off = (-(lo[0] + hi[0]) / 2, -lo[1], -(lo[2] + hi[2]) / 2)
+ return [m.transformed(lambda v: add(v, off)) for m in parts]
+
+
+# ---------------------------------------------------------------------------
+# Cube topology: six quad grids sharing their edges (no poles, every vertex valence 4 except the 8 corners)
+# ---------------------------------------------------------------------------
+
+
+def cube_grid(gx, gy, gz):
+ """gx, gy, gz: sorted coordinates along each axis (first = -extent, last = +extent).
+ Returns the surface of the box as a quad mesh whose vertices are (x, y, z) taken from the grids, plus each
+ vertex's index triple (to tell faces / edges apart)."""
+ grids = (gx, gy, gz)
+ index = {}
+ verts = []
+ keys = []
+
+ def vid(ijk):
+ if ijk not in index:
+ index[ijk] = len(verts)
+ verts.append(tuple(grids[k][ijk[k]] for k in range(3)))
+ keys.append(ijk)
+ return index[ijk]
+
+ faces = []
+ for axis in range(3):
+ b, c = (axis + 1) % 3, (axis + 2) % 3
+ for side in (0, len(grids[axis]) - 1):
+ sign = 1.0 if side else -1.0
+ for i in range(len(grids[b]) - 1):
+ for j in range(len(grids[c]) - 1):
+ def at(di, dj):
+ ijk = [0, 0, 0]
+ ijk[axis] = side
+ ijk[b] = i + di
+ ijk[c] = j + dj
+ return vid(tuple(ijk))
+ q = [at(0, 0), at(1, 0), at(1, 1), at(0, 1)]
+ # b x c points along +axis: CCW from outside on the + side, reversed on the - side.
+ if sign < 0:
+ q.reverse()
+ faces.append(tuple(q))
+ return verts, faces, keys
+
+
+def uniform(n, extent=1.0):
+ return [-extent + 2.0 * extent * i / n for i in range(n + 1)]
+
+
+def rounded_box(hx, hy, hz, r, cell):
+ """Box with half extents (hx, hy, hz) and every edge rounded with radius r; quads about `cell` across."""
+ def axis_grid(h):
+ flat = 2 * (h - r)
+ m = max(1, round(flat / cell))
+ bev = max(2, round((math.pi / 4) * r / cell)) # each face covers half of the quarter-round
+ g = []
+ for k in range(bev, 0, -1):
+ g.append(-(h - r) - r * math.tan(k / bev * math.pi / 4))
+ for k in range(m + 1):
+ g.append(-(h - r) + flat * k / m)
+ for k in range(1, bev + 1):
+ g.append((h - r) + r * math.tan(k / bev * math.pi / 4))
+ return g
+
+ gx, gy, gz = axis_grid(hx), axis_grid(hy), axis_grid(hz)
+ verts, faces, _ = cube_grid(gx, gy, gz)
+ inner = (hx - r, hy - r, hz - r)
+ h = (hx, hy, hz)
+ out = []
+ for q in verts:
+ # q is on the box surface; snap it onto the rounded box (flat faces stay flat).
+ qq = tuple(max(-h[k], min(h[k], q[k])) for k in range(3))
+ c = tuple(max(-inner[k], min(inner[k], qq[k])) for k in range(3))
+ out.append(add(c, mul(norm(sub(qq, c)), r)))
+ return Mesh(out, faces)
+
+
+def profile_sampler(points):
+ """points: a polyline (radius, height) from the bottom pole (radius 0) to the top pole (radius 0).
+ Returns f(t) -> (radius, height), t in [0, 1] by arc length."""
+ cum = [0.0]
+ for a, b in zip(points, points[1:]):
+ cum.append(cum[-1] + math.hypot(b[0] - a[0], b[1] - a[1]))
+ total = cum[-1]
+
+ def f(t):
+ s = t * total
+ lo, hi = 0, len(cum) - 1
+ while hi - lo > 1:
+ mid = (lo + hi) // 2
+ if cum[mid] <= s:
+ lo = mid
+ else:
+ hi = mid
+ seg = cum[hi] - cum[lo]
+ u = 0.0 if seg <= 0 else (s - cum[lo]) / seg
+ a, b = points[lo], points[hi]
+ return (lerp(a[0], b[0], u), lerp(a[1], b[1], u))
+
+ return f, total
+
+
+def arc(cx, cy, r, a0, a1, n):
+ return [(cx + r * math.cos(lerp(a0, a1, k / n)), cy + r * math.sin(lerp(a0, a1, k / n))) for k in range(n + 1)]
+
+
+def revolve(points, n):
+ """Surface of revolution about +Y on cube topology: the cube's top and bottom faces become the caps (rings
+ of quads round the poles, no triangle fans), its sides the band. n = quads along a cube edge (even);
+ 4n quads go round, 2n from pole to pole."""
+ f, _ = profile_sampler(points)
+ g = uniform(n)
+ verts, faces, keys = cube_grid(g, g, g)
+ out = []
+ for (ix, iy, iz) in keys:
+ ux, uy, uz = g[ix], g[iy], g[iz]
+ if iy == 0 or iy == n:
+ ring = max(abs(ux), abs(uz)) # 0 at the pole, 1 at the cube edge
+ m = ring * (n / 2) if iy == 0 else 2 * n - ring * (n / 2)
+ else:
+ m = n / 2 + (uy + 1) / 2 * n
+ r, h = f(m / (2 * n))
+ d = norm((math.tan(ux * math.pi / 4), 0.0, math.tan(uz * math.pi / 4)))
+ out.append((r * d[0], h, r * d[2]))
+ return Mesh(out, faces)
+
+
+def torus(points, n_major, major):
+ """Ring about +Y: the closed profile `points` (radius offset, height), CCW, swept round a circle of radius
+ `major`, sampled by arc length with as many quads as keep them about square."""
+ closed = points + [points[0]]
+ f, total = profile_sampler(closed)
+ n_minor = max(8, round(total / (2 * math.pi * major / n_major)))
+ n_minor += n_minor % 2
+ verts = []
+ for i in range(n_major):
+ a = 2 * math.pi * i / n_major
+ for j in range(n_minor):
+ dr, h = f(j / n_minor)
+ verts.append(((major + dr) * math.cos(a), h, (major + dr) * math.sin(a)))
+ faces = []
+ for i in range(n_major):
+ for j in range(n_minor):
+ a = i * n_minor + j
+ b = ((i + 1) % n_major) * n_minor + j
+ c = ((i + 1) % n_major) * n_minor + (j + 1) % n_minor
+ d = i * n_minor + (j + 1) % n_minor
+ faces.append((a, d, c, b))
+ return orient_outward(Mesh(verts, faces))
+
+
+def ellipsoid_box(hx, hy, hz, cell, n=2.0):
+ """An ellipsoid with semi-axes (hx, hy, hz) made by projecting a box grid (cells about `cell` across)
+ radially onto it: quads stay close to even even when the axes differ a lot. n > 2 makes it boxier
+ (a superellipsoid, |x|^n + |y|^n + |z|^n = 1)."""
+ gx = uniform(max(2, 2 * round(hx / cell)), 1.0)
+ gy = uniform(max(2, 2 * round(hy / cell)), 1.0)
+ gz = uniform(max(2, 2 * round(hz / cell)), 1.0)
+ verts, faces, _ = cube_grid(gx, gy, gz)
+ out = []
+ for (x, y, z) in verts:
+ # Equal-angle warp per axis keeps the projected quads square-ish.
+ p = (math.tan(x * math.pi / 4), math.tan(y * math.pi / 4), math.tan(z * math.pi / 4))
+ d = mul(p, 1.0 / (sum(abs(c) ** n for c in p) ** (1.0 / n)))
+ out.append((d[0] * hx, d[1] * hy, d[2] * hz))
+ return Mesh(out, faces)
+
+
+def orient_outward(m):
+ """Flips every face if the mesh's signed volume is negative (closed meshes)."""
+ vol = 0.0
+ for f in m.faces:
+ a = m.verts[f[0]]
+ for k in range(1, len(f) - 1):
+ vol += dot(a, cross(m.verts[f[k]], m.verts[f[k + 1]]))
+ if vol < 0:
+ m.faces = [tuple(reversed(f)) for f in m.faces]
+ return m
+
+
+# ---------------------------------------------------------------------------
+# MakeHuman hm08 (CC0): the "body" group, in decimetres -> centimetres
+# ---------------------------------------------------------------------------
+
+
+def load_makehuman(path):
+ verts, groups, g = [], {}, None
+ with open(path, encoding="utf-8") as fh:
+ for line in fh:
+ if line.startswith("v "):
+ verts.append(tuple(float(t) * 10.0 for t in line.split()[1:4]))
+ elif line.startswith("g "):
+ g = line.split()[1]
+ groups.setdefault(g, [])
+ elif line.startswith("f "):
+ groups[g].append(tuple(int(t.split("/")[0]) - 1 for t in line.split()[1:]))
+ body = groups["body"]
+ if any(len(f) != 4 for f in body):
+ sys.exit("expected an all-quad body group")
+ joints = {}
+ for name, fs in groups.items():
+ if name.startswith("joint-"):
+ ids = {i for f in fs for i in f}
+ joints[name[6:]] = mul(
+ tuple(sum(verts[i][k] for i in ids) for k in range(3)), 1.0 / len(ids))
+ ground = joints["ground"][1]
+ verts = [(v[0], v[1] - ground, v[2]) for v in verts]
+ joints = {k: (v[0], v[1] - ground, v[2]) for k, v in joints.items()}
+ used = sorted({i for f in body for i in f})
+ remap = {old: new for new, old in enumerate(used)}
+ return Mesh([verts[i] for i in used], [tuple(remap[i] for i in f) for f in body]), joints
+
+
+def centroid(m, f):
+ return mul(tuple(sum(m.verts[i][k] for i in f) for k in range(3)), 1.0 / len(f))
+
+
+def keep_faces(m, pred):
+ """The faces whose centroid passes `pred`, then the largest connected piece, then faces hanging on by
+ fewer than two edges peeled off (the cut stays a clean edge loop). Reindexed."""
+ faces = [f for f in m.faces if pred(centroid(m, f))]
+ while True:
+ edges = Counter()
+ for f in faces:
+ for a, b in zip(f, f[1:] + f[:1]):
+ edges[(min(a, b), max(a, b))] += 1
+ keep = []
+ for f in faces:
+ shared = sum(1 for a, b in zip(f, f[1:] + f[:1]) if edges[(min(a, b), max(a, b))] == 2)
+ if shared >= 2:
+ keep.append(f)
+ if len(keep) == len(faces):
+ break
+ faces = keep
+ # Largest piece by shared edges.
+ by_edge = defaultdict(list)
+ for fi, f in enumerate(faces):
+ for a, b in zip(f, f[1:] + f[:1]):
+ by_edge[(min(a, b), max(a, b))].append(fi)
+ seen = [False] * len(faces)
+ best = []
+ for s in range(len(faces)):
+ if seen[s]:
+ continue
+ stack, piece = [s], []
+ seen[s] = True
+ while stack:
+ fi = stack.pop()
+ piece.append(fi)
+ f = faces[fi]
+ for a, b in zip(f, f[1:] + f[:1]):
+ for o in by_edge[(min(a, b), max(a, b))]:
+ if not seen[o]:
+ seen[o] = True
+ stack.append(o)
+ if len(piece) > len(best):
+ best = piece
+ faces = [faces[i] for i in sorted(best)]
+ used = sorted({i for f in faces for i in f})
+ remap = {old: new for new, old in enumerate(used)}
+ return Mesh([m.verts[i] for i in used], [tuple(remap[i] for i in f) for f in faces])
+
+
+def plane_side(point, normal):
+ n = norm(normal)
+ return lambda p: dot(sub(p, point), n) > 0
+
+
+def mirror_x(p): return (-p[0], p[1], p[2])
+
+
+# ---------------------------------------------------------------------------
+# The set
+# ---------------------------------------------------------------------------
+
+
+def seg_dist(p, a, b):
+ ab = sub(b, a)
+ t = max(0.0, min(1.0, dot(sub(p, a), ab) / dot(ab, ab)))
+ return length(sub(p, add(a, mul(ab, t))))
+
+
+def human_parts(body, j):
+ out = {}
+ neck_y = j["neck"][1] + 2.0
+ out["human-head"] = [keep_faces(body, lambda p: p[1] > neck_y)]
+
+ # The left arm (mirrored with |x| for the right): past a plane across the upper arm and near the bones.
+ sh, el, wr = j["l-shoulder"], j["l-elbow"], j["l-hand"]
+ tip = j["l-finger-3-4"]
+ arm_dir = sub(el, sh)
+
+ def arm(p, along, radius):
+ q = (abs(p[0]), p[1], p[2])
+ if dot(sub(q, add(sh, mul(arm_dir, along))), norm(arm_dir)) <= 0:
+ return False
+ return min(seg_dist(q, sh, el), seg_dist(q, el, wr), seg_dist(q, wr, tip)) < radius
+
+ # Bust: head, neck, shoulders and upper chest; the arms cut a third of the way down the upper arm.
+ chest_y = j["spine-1"][1] - 4.0
+ out["bust"] = [keep_faces(body, lambda p: p[1] > chest_y and not arm(p, 0.33, 9.0))]
+
+ # Torso: neck to upper thighs, arms off at the shoulder.
+ top_y = j["neck"][1] - 1.0
+ hip_y = j["l-upper-leg"][1] - 9.0
+ out["torso"] = [keep_faces(body, lambda p: hip_y < p[1] < top_y and not arm(p, 0.1, 8.0))]
+
+ out["full-body"] = [body]
+
+ # Hand (left): past the wrist, then stood up: wrist down, fingers up, palm to the front.
+ wrist, fore = j["l-hand"], sub(j["l-hand"], j["l-elbow"])
+ cut = add(wrist, mul(norm(fore), -1.0))
+ hand = keep_faces(body, plane_side(cut, fore))
+ up = norm(sub(j["l-finger-3-1"], wrist))
+ thumb = sub(j["l-finger-1-3"], wrist)
+ side = norm(sub(thumb, mul(up, dot(thumb, up)))) # thumb direction, across the hand
+ front = cross(side, up)
+ # Rows of the rotation: thumb -> -X (a raised left hand, palm forward), fingers -> +Y.
+ xa, ya, za = mul(side, -1.0), up, mul(front, -1.0)
+ if dot(cross(xa, ya), za) < 0:
+ za = mul(za, -1.0)
+ out["hand"] = [hand.transformed(lambda v: (dot(sub(v, wrist), xa), dot(sub(v, wrist), ya), dot(sub(v, wrist), za)))]
+
+ ankle = j["l-ankle"]
+ out["foot"] = [keep_faces(body, lambda p: p[0] > 2.0 and p[1] < ankle[1] + 9.0)]
+
+ # Ear (left): centred on the vertices that stand out furthest from the side of the head.
+ side = [v for v in body.verts if abs(v[1] - (j["l-eye"][1] - 2.0)) < 6.0 and v[2] < j["l-eye"][2] - 4.0
+ and v[0] > 0.0]
+ xmax = max(v[0] for v in side)
+ tips = [v for v in side if v[0] > xmax - 1.2]
+ ear_c = mul(tuple(sum(v[k] for v in tips) for k in range(3)), 1.0 / len(tips))
+ ear_c = (ear_c[0] - 1.0, ear_c[1], ear_c[2])
+
+ def ear_pred(p):
+ d = sub(p, ear_c)
+ return p[0] > ear_c[0] - 1.2 and (d[1] / 4.0) ** 2 + (d[2] / 2.9) ** 2 < 1.0
+
+ ear = keep_faces(body, ear_pred)
+ # Ear lying open to the viewer: rotate the outward (+X) side to face +Z.
+ out["ear"] = [ear.transformed(lambda v: (-(v[2] - ear_c[2]), v[1], v[0] - ear_c[0]))]
+ return out
+
+
+def stylised_head(head, j):
+ """The human head pushed toward a cartoon: bigger cranium and eyes, smaller nose, mouth and jaw."""
+ eyes = [j["l-eye"], mirror_x(j["l-eye"])]
+ brow_y = j["l-eye"][1] + 1.0
+ jaw_y = j["jaw"][1]
+ nose = (0.0, j["l-eye"][1] - 3.0, j["l-eye"][2] + 2.0)
+ centre = (0.0, j["head"][1] + 2.0, j["head"][2])
+
+ def warp(v):
+ p = v
+ # Cranium: everything above the brows grows by up to 22 % about the head's centre.
+ s = 1.0 + 0.22 * smoothstep(brow_y - 3.0, brow_y + 6.0, p[1])
+ p = add(centre, mul(sub(p, centre), s))
+ # Eyes: a magnifying warp round each eye.
+ for e in eyes:
+ d = sub(v, e)
+ r = length(d)
+ w = 1.0 - smoothstep(0.0, 4.2, r)
+ p = add(p, mul(d, 0.55 * w))
+ # Nose: shrink toward the face.
+ d = sub(v, nose)
+ w = 1.0 - smoothstep(0.0, 3.5, length(d))
+ p = add(p, mul((d[0], d[1], d[2] - 1.0), -0.35 * w))
+ # Jaw and chin: narrower and shorter.
+ t = 1.0 - smoothstep(jaw_y - 6.0, jaw_y + 3.0, v[1])
+ p = (p[0] * (1.0 - 0.22 * t), p[1] + t * 0.18 * (jaw_y + 3.0 - v[1]), p[2] - 0.12 * t * (p[2] - centre[2]))
+ return p
+
+ return head.transformed(warp)
+
+
+def eye():
+ """Eyeball, 24 mm across, with the cornea bulging 2.6 mm at the front; rings of quads round the pupil."""
+ R = 1.2
+ pts = []
+ n = 96
+ for k in range(n + 1):
+ a = -math.pi / 2 + math.pi * k / n # back pole -> front pole, as (radius, height along the view axis)
+ r, h = R * math.cos(a), R * math.sin(a)
+ ang = math.pi / 2 - a # angle from the front pole
+ if ang < 0.62:
+ h += 0.26 * (1.0 - (ang / 0.62) ** 2) ** 2
+ pts.append((max(0.0, r), h))
+ m = revolve(pts, 16)
+ # The revolve axis (Y) becomes the view axis (+Z).
+ return m.transformed(lambda v: (v[0], -v[2], v[1]))
+
+
+def creature_head():
+ """Dragon / creature head blockout: a skull with a long, blunt snout, brow ridges over the eye sockets, cheek
+ bones and nostrils, a lower jaw tucked under it and two horns sweeping back (four Parts). About 37 cm long."""
+ skull = ellipsoid_box(1.0, 0.85, 2.0, 0.17, 2.6)
+
+ def bump(v, c, rad, amt):
+ out = (0.0, 0.0, 0.0)
+ for sx in ((1, -1) if c[0] else (1,)):
+ w = 1.0 - smoothstep(0.0, rad, length(sub(v, (c[0] * sx, c[1], c[2]))))
+ out = add(out, mul(norm(v), amt * w * w * (3 - 2 * w)))
+ return out
+
+ def shape(v):
+ x, y, z = v
+ t = smoothstep(-0.3, 2.0, z) # 0 at the back of the skull, 1 at the snout tip
+ p = (x * lerp(1.0, 0.55, t), y * lerp(1.0, 0.5, t) - 0.25 * t, z)
+ for (c, rad, amt) in (((0.5, 0.55, 0.55), 0.5, 0.30), # brow ridges
+ ((0.62, 0.22, 0.8), 0.32, -0.14), # eye sockets under them
+ ((0.85, -0.25, 0.1), 0.5, 0.12), # cheek bones
+ ((0.25, 0.3, 1.85), 0.25, 0.08), # nostrils
+ ((0.0, 0.8, -0.4), 0.6, 0.10)): # crest over the cranium
+ p = add(p, bump(v, c, rad, amt))
+ return mul(p, 9.0)
+
+ skull = skull.transformed(shape)
+ jaw = ellipsoid_box(0.7, 0.22, 1.7, 0.14, 2.4)
+
+ def jaw_shape(v):
+ x, y, z = v
+ t = smoothstep(-0.7, 1.7, z)
+ return mul((x * lerp(1.0, 0.5, t), y * lerp(1.0, 0.8, t) + lerp(-0.72, -0.62, t), z + 0.15), 9.0)
+
+ jaw = jaw.transformed(jaw_shape)
+ # Horn: a tapering tube along +Y, bent back as it grows, then pitched back, turned out and set on the skull.
+ L, R = 13.0, 1.5
+ pts = [(0.0, 0.0), (R, 0.0)] + [(R * (1.0 - (k / 40) ** 1.3) + 0.03, L * k / 40) for k in range(1, 41)] + \
+ [(0.0, L + 0.05)]
+ horn0 = revolve(pts, 8)
+ bend_angle, pitch, roll = 1.0, 0.55, 0.35
+
+ def place(v, sx):
+ x, y, z = v
+ a = bend_angle * y / L
+ rr = L / bend_angle
+ nrm = (0.0, -math.sin(a), -math.cos(a)) # across the bent axis, toward the back
+ p = add((x, rr * math.sin(a), -(rr - rr * math.cos(a))), mul(nrm, -z))
+ p = (p[0], p[1] * math.cos(pitch) + p[2] * math.sin(pitch), -p[1] * math.sin(pitch) + p[2] * math.cos(pitch))
+ p = (p[0] * math.cos(roll) + p[1] * math.sin(roll), -p[0] * math.sin(roll) + p[1] * math.cos(roll), p[2])
+ return (sx * (p[0] + 4.3), p[1] + 4.6, p[2] - 5.5)
+
+ horns = []
+ for sx in (1, -1):
+ h = horn0.transformed(lambda v, sx=sx: place(v, sx))
+ if sx < 0:
+ h.faces = [tuple(reversed(f)) for f in h.faces]
+ horns.append(h)
+ return [skull, jaw] + horns
+
+
+def primitives():
+ out = {}
+ out["rounded-box"] = [rounded_box(10.0, 10.0, 10.0, 1.5, 1.0)]
+ R, H, b = 10.0, 20.0, 1.5
+ pts = [(0.0, 0.0), (R - b, 0.0)] + arc(R - b, b, b, -math.pi / 2, 0.0, 12) + [(R, H - b)] + \
+ arc(R - b, H - b, b, 0.0, math.pi / 2, 12) + [(0.0, H)]
+ out["cylinder"] = [revolve(pts, 16)]
+ R, L = 7.5, 15.0
+ pts = arc(0.0, R, R, -math.pi / 2, 0.0, 24) + arc(0.0, R + L, R, 0.0, math.pi / 2, 24)
+ out["capsule"] = [revolve(pts, 16)]
+ w, h, b = 3.0, 2.4, 0.6 # cross-section: 3 cm wide, 2.4 cm tall, 6 mm bevels
+ sec = []
+ for (cx, cy, a0) in ((w / 2 - b, -h / 2 + b, -math.pi / 2), (w / 2 - b, h / 2 - b, 0.0),
+ (-w / 2 + b, h / 2 - b, math.pi / 2), (-w / 2 + b, -h / 2 + b, math.pi)):
+ sec += arc(cx, cy, b, a0, a0 + math.pi / 2, 8)
+ out["ring"] = [torus(sec, 64, 9.0)]
+ return out
+
+
+# (id, name, Part names, symmetric, closed, Divide levels at load)
+SET = [
+ ("human-head", "Human Head", ["Head"], True, False, 2),
+ ("bust", "Bust", ["Bust"], True, False, 2),
+ ("full-body", "Full Body (A-pose)", ["Body"], True, True, 1),
+ ("hand", "Hand", ["Hand"], False, False, 2),
+ ("foot", "Foot", ["Foot"], False, False, 2),
+ ("ear", "Ear", ["Ear"], False, False, 2),
+ ("eye", "Eye", ["Eye"], True, True, 2),
+ ("stylised-head", "Stylised Head", ["Head"], True, False, 2),
+ ("creature-head", "Creature Head", ["Skull", "Jaw", "Horn L", "Horn R"], True, True, 2),
+ ("torso", "Torso", ["Torso"], True, False, 2),
+ ("rounded-box", "Rounded Box", ["Rounded Box"], True, True, 2),
+ ("cylinder", "Cylinder", ["Cylinder"], True, True, 2),
+ ("capsule", "Capsule", ["Capsule"], True, True, 2),
+ ("ring", "Ring", ["Ring"], True, True, 2),
+]
+
+
+def check(mid, parts, closed):
+ nv = sum(len(m.verts) for m in parts)
+ nf = sum(len(m.faces) for m in parts)
+ lens = []
+ boundary = 0
+ for m in parts:
+ e = Counter()
+ for f in m.faces:
+ for a, b in zip(f, f[1:] + f[:1]):
+ e[(min(a, b), max(a, b))] += 1
+ lens.append(length(sub(m.verts[a], m.verts[b])))
+ if any(c > 2 for c in e.values()):
+ sys.exit(f"{mid}: non-manifold edge")
+ boundary += sum(1 for c in e.values() if c == 1)
+ if closed and boundary:
+ sys.exit(f"{mid}: expected closed, {boundary} boundary edges")
+ mean = sum(lens) / len(lens)
+ cv = math.sqrt(sum((l - mean) ** 2 for l in lens) / len(lens)) / mean
+ lo, hi = bounds(parts)
+ print(f"{mid:15s} {nv:6d} verts {nf:6d} quads edge cv {cv:.2f} boundary {boundary:4d} "
+ f"size {hi[0]-lo[0]:.1f} x {hi[1]-lo[1]:.1f} x {hi[2]-lo[2]:.1f} cm")
+
+
+def write_obj(path, names, parts):
+ with open(path, "w", encoding="utf-8", newline="\n") as fh:
+ fh.write("# SculptForge starter mesh (tools/starter/build_starter_meshes.py); docs/starter-meshes.md\n")
+ base = 1
+ for name, m in zip(names, parts):
+ fh.write(f"o {name}\n")
+ for v in m.verts:
+ fh.write("v %.4f %.4f %.4f\n" % tuple(0.0 if abs(c) < 5e-5 else c for c in v))
+ for f in m.faces:
+ fh.write("f " + " ".join(str(i + base) for i in f) + "\n")
+ base += len(m.verts)
+
+
+def main():
+ if len(sys.argv) != 3:
+ sys.exit(__doc__ if __doc__ else "usage: build_starter_meshes.py <makehuman base.obj> <out dir>")
+ body, joints = load_makehuman(sys.argv[1])
+ out_dir = sys.argv[2]
+ os.makedirs(out_dir, exist_ok=True)
+ meshes = human_parts(body, joints)
+ meshes["stylised-head"] = [stylised_head(meshes["human-head"][0], joints)]
+ meshes["eye"] = [eye()]
+ meshes["creature-head"] = creature_head()
+ meshes.update(primitives())
+ for (mid, name, part_names, symmetric, closed, levels) in SET:
+ parts = place_on_ground(meshes[mid])
+ check(mid, parts, closed)
+ write_obj(os.path.join(out_dir, mid + ".obj"), part_names, parts)
+
+
+if __name__ == "__main__":
+ main()