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.

Tube: draw clay tubes in 3D space like a 3D pen (Tool > Tube)

islandmed6e6c3e5f0fd7
diff --git a/CMakeLists.txt b/CMakeLists.txt
index bb8f101c..2d71c1cb 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -149,6 +149,7 @@ add_library(sculptforge_core STATIC
src/core/QRemesh2Param.cpp
src/core/QuadQuality.cpp
src/core/ForgeSpheres.cpp src/core/AgentTools.cpp
+ src/core/Tube.cpp
src/core/Projection.cpp
src/core/RetopoCommands.cpp
third_party/xatlas/xatlas.cpp
@@ -443,6 +444,7 @@ if(SCULPTFORGE_BUILD_APP)
src/app/FocusDetailApp.cpp
src/app/PanelRetopo.cpp
src/app/PanelForgeSpheres.cpp
+ src/app/PanelTube.cpp
src/app/PanelSplatTrain.cpp
src/app/PanelSculptable.cpp
src/app/PanelPerformance.cpp
diff --git a/changes/feat-curve-tube.md b/changes/feat-curve-tube.md
new file mode 100644
index 00000000..404dfa27
--- /dev/null
+++ b/changes/feat-curve-tube.md
@@ -0,0 +1,24 @@
+---
+whats_new: **Tube**: draw clay tubes in the air like a 3D pen. **Tool > Tube > Draw Tube**, then drag anywhere: on the
+ model, off it, or out of it. Pen pressure thins the tube; drag its points afterwards to reshape it, then **Bake** to
+ sculpt it, or draw straight into the active Part with **Merge** (even edges, ready for dynamic topology). Thanks to
+ GABO on Discord for the idea.
+highlight: Tube: draw clay tubes in 3D space
+added: **Tube** (Tool > Tube): draw tubes freely in 3D space, like a 3D pen. Strokes lie on a plane facing the view
+ (at the surface where the stroke starts, the pivot, or a fixed distance), optionally snapped onto surfaces; pen
+ pressure sets the radius and the stroke is smoothed into a curve. The tube is swept along it with rings placed
+ closer in bends and frames that never twist, round or flat ends, and Symmetry X. Each stroke is a Tube Part whose
+ points are dragged (Ctrl: thickness, Alt+click: delete), inserted and deleted until **Bake**, or goes straight into
+ the active Part with even edge lengths for dynamic topology; one undo step each. Script and AI commands `tube_new`,
+ `tube_list`, `tube_set_point`, `tube_insert_point`, `tube_delete_point`, `tube_set`, `tube_bake`. Guide chapter
+ "Tube: draw in 3D space". Requested by GABO on Discord.
+testers:
+ - Any OS, with a pen: Tool > Tube > Draw Tube, start a stroke on the model and pull it out into the air; a light
+ touch gives a thinner tube. Ctrl+Z removes it. Good: smooth tube, no twisting or pinching in bends.
+ - Drag a dot of the new tube: it selects the Tube Part and the tube follows the dot smoothly (also with long
+ strokes). Ctrl+drag a dot: thicker / thinner there. Bake, then sculpt it.
+ - Turn Symmetry X on and draw off-centre: the mirror copy appears. Result > Merge with dynamic topology on: draw over
+ the model, then sculpt across the join.
+---
+Clay tube drawn in the air (Discord #wip-and-feedback 1568627563562274836, GABO / gabrielabdala_). Profiles other than
+round (square, custom) are a later step.
diff --git a/docs/guide/images/tube-panel.jpg b/docs/guide/images/tube-panel.jpg
new file mode 100644
index 00000000..15e4a8b6
Binary files /dev/null and b/docs/guide/images/tube-panel.jpg differ
diff --git a/docs/guide/images/tube-steps.jpg b/docs/guide/images/tube-steps.jpg
new file mode 100644
index 00000000..6f8fba81
Binary files /dev/null and b/docs/guide/images/tube-steps.jpg differ
diff --git a/docs/guide/index.md b/docs/guide/index.md
index 2dae0028..8530c65f 100644
--- a/docs/guide/index.md
+++ b/docs/guide/index.md
@@ -45,6 +45,7 @@ Read it inside SculptForge (**Help > User Guide**, or <kbd>Shift</kbd>+<kbd>F1</
13. [Parts](parts.md)
- [Linked Duplicates](linked-duplicates.md)
14. [Forge Spheres](forge-spheres.md)
+ - [Tube: draw in 3D space](tube.md)
15. [Vertex Paint and materials](vertex-paint.md)
16. [Texture painting](texture-painting.md)
17. [UV Editor](uv-editor.md)
diff --git a/docs/guide/tube.md b/docs/guide/tube.md
new file mode 100644
index 00000000..47a0f658
--- /dev/null
+++ b/docs/guide/tube.md
@@ -0,0 +1,91 @@
+# Tube: draw in 3D space
+
+**Tube** draws clay tubes freely in the air, like a 3D pen: horns, vines, hair strands, tentacles, cables, piping
+or the wire of an armature, drawn where you want them instead of pulled out of a surface. Each stroke becomes a
+smooth curve with a tube swept along it, and its points stay editable until you bake it into a mesh to sculpt.
+
+![Drawing a tube from the model out into the air, the Tube Part it makes, a point dragged up, and a strap merged into the model](images/tube-steps.jpg)
+
+## Draw a tube
+
+1. Open **Tool > Tube** and press **Draw Tube**.
+2. Drag anywhere in the view: on the model, off it, or from one into the other. A trail shows the tube as you
+ draw; let go and it is made.
+3. <kbd>Ctrl</kbd>+<kbd>Z</kbd> takes the tube away again.
+
+While Draw Tube is on, <kbd>Alt</kbd>+drag still moves the view (and so do the right and middle buttons), so you can
+draw, turn the model, and draw again from another side. The brush ring is replaced by a circle as thick as the tube
+will be.
+
+![Tool > Tube with a Tube Part selected](images/tube-panel.jpg)
+
+| Setting | What it does |
+|---|---|
+| **Size** | How thick new tubes are: their radius on screen at the depth you draw at |
+| **Pressure** | How much a light touch of the pen thins the tube (0: the same thickness all along). A mouse draws at full size |
+| **Smoothing** | How much of the stroke's wobble is smoothed out before the tube is made |
+| **Depth** | Where in depth the stroke lies (below) |
+| **Snap to surfaces** | Where the pen is over a surface, the tube lies on it, half sunk in, instead of on the drawing plane |
+| **Ends** | **Round** or **Flat** |
+| **Result** | **New Part**: each stroke is a Tube Part you can edit. **Merge**: the stroke goes into the active Part |
+
+**Symmetry** (<kbd>X</kbd>) draws the mirror copy across the X plane too, and keeps it as you edit the tube.
+
+## Depth: where the stroke lies
+
+A stroke on a flat screen needs a depth. The tube's points lie on a plane facing you:
+
+- **Surface** (the default): through the surface under the pen where the stroke starts. A stroke that starts off
+ the model uses the depth where your last stroke ended, or the pivot. So a stroke started on a head and pulled out
+ sideways grows from that spot into the air.
+- **Pivot**: through the view's pivot, the point the camera turns around.
+- **Fixed**: at a set **Distance** from the camera. Orbit and draw again to build up a shape in 3D.
+
+Turn **Snap to surfaces** on to draw along a model: a strap round an arm, a seam, a vein.
+
+## Edit the points
+
+A Tube Part's control points show as dots joined by a thin line (with Draw Tube on, the dots of every visible Tube
+Part show, and pressing one selects that Part):
+
+- **Drag** a dot to move it across the screen; the tube follows as you drag.
+- <kbd>Ctrl</kbd>+drag a dot up or right to make the tube thicker there, down or left to make it thinner.
+- <kbd>Alt</kbd>+click a dot to delete it.
+- The dot you last dragged is selected (orange): **Radius** sets its thickness exactly, **Insert Point** adds a
+ point halfway to the next one, **Delete Point** removes it.
+- **Round** and **Flat** change the ends of the selected tube.
+
+Each drag and button is one undo step. A Tube Part isn't sculpted while its points are editable: brushes leave it
+alone until you bake it. If you move, mirror or otherwise change the Part's mesh, its points no longer fit it and
+editing them is refused (undo the change, or bake it as it is).
+
+## Bake and Merge
+
+**Bake** turns the active Tube Part into a plain mesh to sculpt, in quads, with one face group for the body and one
+for each end. Tick **Even edges** first to bake it in triangles of one size instead, ready for
+[dynamic topology](dynamic-topology.md). Undo brings the points back.
+
+**Result > Merge** skips the Tube Part: each stroke goes straight into the active Part as one undo step, with even
+edges close to that Part's own edge length, so dynamic topology carries on smoothly across it. A Part with
+subdivision levels or a micro level can't take a merged tube; draw a new Part and merge it with the
+[Parts](parts.md) list.
+
+> **Tip:** for clay-like strands, draw with Merge into a Part with dynamic topology on, then smooth and blend the
+> joins with the brushes.
+
+## From a script
+
+The `tube_*` commands do the same from the Console, scripts and AI assistants:
+
+```
+tube_new points="0,0,0 0.5,0.4,0,0.08 1,0.2,0.3" radius=0.05 caps=round symmetry=x
+tube_list
+tube_set_point index=1 position="0.5,0.6,0" radius=0.1
+tube_insert_point index=0
+tube_delete_point index=2
+tube_set caps=flat radius_scale=1.5
+tube_bake uniform=true
+```
+
+Each point is `x,y,z` or `x,y,z,radius`. With `smooth=0.5` the points are treated as raw pen samples: smoothed and
+simplified into control points, as a drawn stroke is. `merge=true` puts the tube into the active Part.
diff --git a/src/app/App.cpp b/src/app/App.cpp
index 835c0fdf..c7acc448 100644
--- a/src/app/App.cpp
+++ b/src/app/App.cpp
@@ -1782,6 +1782,7 @@ void App::onMouseDown(float x, float y, Uint8 button) {
if (button == SDL_BUTTON_LEFT) {
if (axisGizmoMouseDown(x, y)) return; // the axis gizmo's ends snap to a side view (#43)
if (forgesphereMouseDown(x, y, mod)) return; // a Forge Sphere Part takes clicks on it (PanelForge Spheres.cpp)
+ if (tubeMouseDown(x, y, mod)) return; // Draw Tube, a Tube Part's points (PanelTube.cpp)
if (stencilMouseDown(x, y, nav)) return; // Adjust Stencil: move, scale, turn it (StencilOverlay.cpp)
if (gradientMouseDown(x, y, nav)) return; // Line Gradient: a new line or an end handle (LineGradient.cpp)
if (facegroupMouseDown(x, y, mod)) return;
@@ -1965,6 +1966,7 @@ void App::onMouseMove(float x, float y, float dx, float dy, bool fromPen) {
case Drag::Gradient: gradientMouseMove(x, y); break;
case Drag::Stencil: stencilMouseMove(x, y); break;
case Drag::ForgeSphere: forgesphereDragTo(x, y); break;
+ case Drag::Tube: tubeDragTo(x, y); break;
case Drag::AirStroke: airStrokeTo(x, y); break;
case Drag::QuickRemesh: break; // (remeshes when let go)
case Drag::SizeScrub:
@@ -2112,6 +2114,7 @@ void App::onMouseUp() {
if (drag_ == Drag::Gradient) gradientMouseUp();
if (drag_ == Drag::Stencil) stencilMouseUp();
if (drag_ == Drag::ForgeSphere) forgesphereRelease();
+ if (drag_ == Drag::Tube) tubeRelease();
if (drag_ == Drag::AirStroke) airStrokeRelease();
gizmoRelease();
drag_ = Drag::None;
@@ -3066,6 +3069,7 @@ void App::drawUi() {
drawUvEditorOverlay(); // UV seams on the model, the Seam tool's cursor (PanelUvEditor.cpp)
drawForgeSphereOverlay(); // the sphere under the cursor (PanelForge Spheres.cpp)
drawForgeSphereMenu(); // a right click on a sphere
+ drawTubeOverlay(); // Draw Tube's trail and cursor, a Tube Part's points (PanelTube.cpp)
drawFaceOverlay(); // facial landmarks (PanelFace.cpp)
drawSplatTrainOverlay(); // splat training progress (PanelSplatTrain.cpp)
drawSculptableOverlay(); // Make sculptable: crop box, face landmarks (PanelSculptable.cpp)
@@ -3081,7 +3085,7 @@ void App::drawUi() {
}
// In Gizmo mode (and with the QRemesh Guides brush) the brush ring shows only while Ctrl masks or Shift smooths.
const bool ringOff = gizmoActive() || stencil_.adjust || (guidesMode_ && !(inputMods() & SDL_KMOD_SHIFT)) || sculptableHot() || forgesphereActive() ||
- uvToolActive();
+ uvToolActive() || tubeDraw_ || tubeActive();
// (The S / O pop-up holds the mouse, but its ring shows where it opened, #138.)
ImVec2 sliderOpened;
PickerUi::Slider sliderWhich;
diff --git a/src/app/App.h b/src/app/App.h
index c2d83209..54d2d540 100644
--- a/src/app/App.h
+++ b/src/app/App.h
@@ -174,7 +174,7 @@ public:
private:
enum class Drag { None, Stroke, Orbit, Pan, Zoom, Roll, MaskCanvas, PartClick, Select, Gizmo, Guide, Sculptable, ForgeSphere, Insert, Capture,
- AirStroke, UvTool, SizeScrub, QuickRemesh, Gradient, Stencil }; // AirStroke: a stroke begun off the model, waiting to reach it (#62)
+ AirStroke, UvTool, SizeScrub, QuickRemesh, Gradient, Stencil, Tube }; // AirStroke: a stroke begun off the model, waiting to reach it (#62)
void handleEvent(const SDL_Event& e); // the pen's mouse events first (penMouseEvents), then dispatchEvent
void dispatchEvent(const SDL_Event& e);
@@ -1388,6 +1388,49 @@ private:
int added = -1; // Draw: the new sphere's index
const char* label = "";
} zsDrag_;
+ // Tube (PanelTube.cpp, core/Tube.h): with Draw Tube on, a left-drag anywhere draws a clay tube in the air (on a
+ // plane facing the view, or snapped onto surfaces); a Tube Part's points are dragged to move them (Ctrl: resize,
+ // Alt+click: delete) until Bake. Each stroke or point drag is one undo step.
+ enum class TubeDepth { Surface, Pivot, Fixed };
+ void registerTubeUiActions();
+ void drawTubeContents(); // Tool > Tube
+ bool tubeMouseDown(float x, float y, SDL_Keymod mod); // true if it took the click
+ void tubeDragTo(float x, float y);
+ void tubeRelease();
+ void drawTubeOverlay(); // the stroke being drawn, the points, the cursor
+ bool tubeActive() const { return !doc_.mesh.tube.empty(); }
+ int tubePointAt(float x, float y, int* part = nullptr) const; // control point under the cursor (of `part`), or -1
+ int tubeSelection() const; // tubeSelected_ when it is still a point, else -1
+ glm::vec3 tubeViewDir() const; // into the screen
+ bool tubeDraw_ = false;
+ TubeDepth tubeDepth_ = TubeDepth::Surface;
+ float tubeFixedDepth_ = 0.0f; // Fixed: distance from the camera (0 = take the pivot's on first use)
+ float tubeSizePx_ = 14.0f; // tube radius on screen at the drawing depth
+ float tubePressure_ = 0.7f; // how much pen pressure thins the tube (0 = none)
+ float tubeSmoothing_ = 0.5f;
+ bool tubeSnap_ = false; // points over a surface sit on it
+ bool tubeFlatCaps_ = false;
+ bool tubeMerge_ = false; // into the active Part (even edges) instead of a new Tube Part
+ bool tubeBakeUniform_ = false; // Bake re-sweeps with even edges (dynamic topology)
+ int tubeSelected_ = -1;
+ float tubeRadiusEdit_ = -1.0f; // the selected point's Radius slider while it is held
+ int tubeRadiusEditPoint_ = -1;
+ bool tubeHaveAnchor_ = false; // the last stroke's end, the next stroke's depth when it starts off the model
+ glm::vec3 tubeAnchor_{0.0f};
+ struct TubeDrag {
+ bool drawing = false;
+ glm::vec3 planePoint{0.0f}, planeNormal{0.0f, 0.0f, -1.0f};
+ float radius = 0.0f; // world radius at full pressure
+ std::vector<TubePoint> samples;
+ std::vector<ImVec4> screen; // x, y, radius in pixels (the trail drawn while the pen moves)
+ int point = -1; // editing: the point dragged
+ bool resize = false;
+ TubeShape start, preview; // the curve when the drag began, and now
+ Mesh before;
+ glm::vec3 grab{0.0f};
+ float x = 0.0f, y = 0.0f;
+ bool changed = false;
+ } tubeDrag_;
const BrushRecipe* strokeRecipe() const; // recipe the current stroke sculpts with (none for Smooth / paint only)
// Bridge bridge and Bridge/STL files (PanelBridge.cpp).
void drawBridgeMenu();
diff --git a/src/app/Config.cpp b/src/app/Config.cpp
index 9485595d..c7abf7cd 100644
--- a/src/app/Config.cpp
+++ b/src/app/Config.cpp
@@ -803,6 +803,7 @@ void App::initActions() {
registerUvEditorActions(); // UV Editor (PanelUvEditor.cpp)
registerRetopoUiActions(); // Geometry > QRemesh, Part > ProjectAll (PanelRetopo.cpp)
registerForgeSphereUiActions(); // Tool > Forge Spheres (PanelForge Spheres.cpp)
+ registerTubeUiActions(); // Tool > Tube (PanelTube.cpp)
registerSplatTrainUi(); // Splats > Train from capture (PanelSplatTrain.cpp)
registerSculptableUiActions(); // Splats > Make sculptable (PanelSculptable.cpp)
registerVdmActions(); // Brush > Vector Displacement (PanelVdm.cpp)
diff --git a/src/app/I18nSimplifiedChinese.cpp b/src/app/I18nSimplifiedChinese.cpp
index 239c2c00..7f61645e 100644
--- a/src/app/I18nSimplifiedChinese.cpp
+++ b/src/app/I18nSimplifiedChinese.cpp
@@ -4376,6 +4376,52 @@ constexpr Entry kSimplifiedChinese[] = {
"旋转模板,以逆时针度数表示;Ctrl+点击以输入。"},
{"Centre the Stencil again, upright, 80% of the view's height.",
"将模板重新居中、摆正,高度为视图的 80%。"},
+ // --- Tube (Tool > Tube, PanelTube.cpp) ---
+ {"Delete Point", "删除点"},
+ {"Ends", "端部"},
+ {"Even edges", "均匀边长"},
+ {"Fixed", "固定"},
+ {"Insert Point", "插入点"},
+ {"Distance %.2f", "距离 %.2f"},
+ {"Merge", "合并"},
+ {"New Part", "新部件"},
+ {"(point %d selected)", "(已选中点 %d)"},
+ {"%d points", "%d 个点"},
+ {"Pressure %.2f", "压力 %.2f"},
+ {"Radius %.4g", "半径 %.4g"},
+ {"Draw Tube", "绘制 Tube"},
+ {"Result", "结果"},
+ {"Round", "圆形"},
+ {"Select a Tube Part to edit its points.", "选择一个 Tube 部件以编辑它的点。"},
+ {"Smoothing %.2f", "平滑 %.2f"},
+ {"Snap to surfaces", "吸附到表面"},
+ {"Add a point halfway between the selected point and the next one.", "在选中的点和下一个点的正中间添加一个点。"},
+ {"Bake re-sweeps the tube in triangles of one size (good for dynamic topology) instead of keeping its quads.",
+ "Bake 时用大小一致的三角形重新生成管子(适合动态拓扑),而不是保留四边形。"},
+ {"Delete the selected point (the one last dragged, in orange). Alt+click a point does the same.",
+ "删除选中的点(最后拖动的那个,橙色)。Alt+点击一个点也可以删除它。"},
+ {"Drag anywhere in the view to draw a clay tube in the air, like a 3D pen: on the model or off it. Pen pressure makes it thinner, Symmetry X draws the mirror copy. Alt+drag still moves the view.",
+ "在视图中任意位置拖动,像 3D 笔一样在空中画出粘土管子:在模型上或模型外都可以。笔压越轻管子越细,对称 X 会画出镜像副本。Alt+拖动仍然移动视图。"},
+ {"Each stroke goes into the active Part, with even edge lengths close to that Part's own, ready for dynamic topology.",
+ "每一笔都合并进当前部件,边长均匀并接近该部件自身的边长,适合动态拓扑。"},
+ {"Each stroke makes a Tube Part whose points stay editable until Bake.",
+ "每一笔生成一个 Tube 部件,它的点在 Bake 之前都可以编辑。"},
+ {"Flat ends (for new tubes, and the active Tube Part).", "平面端部(用于新管子和当前的 Tube 部件)。"},
+ {"How much a light touch of the pen thins the tube. 0: the same thickness all along.",
+ "笔的轻触让管子变细的程度。0:整条粗细相同。"},
+ {"How much the stroke's wobble is smoothed out before the tube is made.", "生成管子之前,笔画的抖动被平滑掉的程度。"},
+ {"How thick new tubes are, as a radius on screen at the depth you draw at.", "新管子的粗细:在你绘制的深度上,屏幕上的半径。"},
+ {"Make the active Tube Part a plain mesh to sculpt. Its points can't be edited after this (undo brings them back).",
+ "把当前的 Tube 部件变成普通网格以便雕刻。之后不能再编辑它的点(撤销可以恢复)。"},
+ {"Round ends (for new tubes, and the active Tube Part).", "圆形端部(用于新管子和当前的 Tube 部件)。"},
+ {"Smoothing", "平滑"},
+ {"Strokes are drawn at a fixed distance from the camera (Depth below); orbit to draw at another angle.",
+ "笔画画在离相机固定距离的位置(见下方的距离);环绕视图后可以从另一个角度绘制。"},
+ {"Strokes are drawn at the depth of the surface under the pen where they start; started off the model, at the depth where the last stroke ended (or the pivot).",
+ "笔画画在起笔处笔下表面的深度;如果在模型外起笔,则画在上一笔结束处的深度(或枢轴点)。"},
+ {"Strokes are drawn on the plane through the view's pivot, facing you.", "笔画画在穿过视图枢轴点、面向你的平面上。"},
+ {"Where the pen is over a surface, the tube lies on it (half sunk in) instead of on the drawing plane.",
+ "笔在表面上方时,管子贴在表面上(一半陷入),而不是画在绘制平面上。"},
};
} // namespace
diff --git a/src/app/I18nSpanish.cpp b/src/app/I18nSpanish.cpp
index 3dc741f0..597a0156 100644
--- a/src/app/I18nSpanish.cpp
+++ b/src/app/I18nSpanish.cpp
@@ -4854,6 +4854,58 @@ constexpr Entry kSpanish[] = {
"Barra superior"},
{"Status bar",
"Barra de estado"},
+ // --- Tube (Tool > Tube, PanelTube.cpp) ---
+ {"Delete Point", "Borrar punto"},
+ {"Ends", "Extremos"},
+ {"Even edges", "Aristas uniformes"},
+ {"Fixed", "Fija"},
+ {"Insert Point", "Insertar punto"},
+ {"Distance %.2f", "Distancia %.2f"},
+ {"Merge", "Fusionar"},
+ {"New Part", "Nueva pieza"},
+ {"(point %d selected)", "(punto %d seleccionado)"},
+ {"%d points", "%d puntos"},
+ {"Pressure %.2f", "Presión %.2f"},
+ {"Radius %.4g", "Radio %.4g"},
+ {"Draw Tube", "Dibujar Tube"},
+ {"Result", "Resultado"},
+ {"Round", "Redondo"},
+ {"Select a Tube Part to edit its points.", "Selecciona una pieza Tube para editar sus puntos."},
+ {"Smoothing %.2f", "Suavizado %.2f"},
+ {"Snap to surfaces", "Ajustar a superficies"},
+ {"Add a point halfway between the selected point and the next one.",
+ "Añade un punto a medio camino entre el punto seleccionado y el siguiente."},
+ {"Bake re-sweeps the tube in triangles of one size (good for dynamic topology) instead of keeping its quads.",
+ "Bake vuelve a generar el tubo en triángulos de un solo tamaño (bueno para la topología dinámica) en lugar de mantener sus cuadriláteros."},
+ {"Delete the selected point (the one last dragged, in orange). Alt+click a point does the same.",
+ "Borra el punto seleccionado (el último que arrastraste, en naranja). Alt+clic en un punto hace lo mismo."},
+ {"Drag anywhere in the view to draw a clay tube in the air, like a 3D pen: on the model or off it. Pen pressure makes it thinner, Symmetry X draws the mirror copy. Alt+drag still moves the view.",
+ "Arrastra en cualquier lugar de la vista para dibujar un tubo de arcilla en el aire, como un bolígrafo 3D: sobre el modelo o fuera de él. La presión del lápiz lo hace más fino; Simetría X dibuja la copia reflejada. Alt+arrastrar sigue moviendo la vista."},
+ {"Each stroke goes into the active Part, with even edge lengths close to that Part's own, ready for dynamic topology.",
+ "Cada trazo entra en la pieza activa, con aristas uniformes cercanas a las de esa pieza, listo para la topología dinámica."},
+ {"Each stroke makes a Tube Part whose points stay editable until Bake.",
+ "Cada trazo crea una pieza Tube cuyos puntos siguen siendo editables hasta Bake."},
+ {"Flat ends (for new tubes, and the active Tube Part).",
+ "Extremos planos (para los tubos nuevos y la pieza Tube activa)."},
+ {"How much a light touch of the pen thins the tube. 0: the same thickness all along.",
+ "Cuánto adelgaza el tubo un toque ligero del lápiz. 0: el mismo grosor en toda su longitud."},
+ {"How much the stroke's wobble is smoothed out before the tube is made.",
+ "Cuánto se suaviza el temblor del trazo antes de crear el tubo."},
+ {"How thick new tubes are, as a radius on screen at the depth you draw at.",
+ "El grosor de los tubos nuevos, como radio en pantalla a la profundidad en que dibujas."},
+ {"Make the active Tube Part a plain mesh to sculpt. Its points can't be edited after this (undo brings them back).",
+ "Convierte la pieza Tube activa en una malla normal para esculpir. Después ya no se pueden editar sus puntos (deshacer los recupera)."},
+ {"Round ends (for new tubes, and the active Tube Part).",
+ "Extremos redondos (para los tubos nuevos y la pieza Tube activa)."},
+ {"Smoothing", "Suavizado"},
+ {"Strokes are drawn at a fixed distance from the camera (Depth below); orbit to draw at another angle.",
+ "Los trazos se dibujan a una distancia fija de la cámara (Distancia, abajo); orbita para dibujar desde otro ángulo."},
+ {"Strokes are drawn at the depth of the surface under the pen where they start; started off the model, at the depth where the last stroke ended (or the pivot).",
+ "Los trazos se dibujan a la profundidad de la superficie bajo el lápiz donde empiezan; si empiezan fuera del modelo, a la profundidad donde terminó el último trazo (o la del pivote)."},
+ {"Strokes are drawn on the plane through the view's pivot, facing you.",
+ "Los trazos se dibujan en el plano que pasa por el pivote de la vista, de cara a ti."},
+ {"Where the pen is over a surface, the tube lies on it (half sunk in) instead of on the drawing plane.",
+ "Donde el lápiz está sobre una superficie, el tubo se apoya en ella (medio hundido) en lugar de en el plano de dibujo."},
};
} // namespace
diff --git a/src/app/I18nTraditionalChinese.cpp b/src/app/I18nTraditionalChinese.cpp
index 9a588b62..42e38834 100644
--- a/src/app/I18nTraditionalChinese.cpp
+++ b/src/app/I18nTraditionalChinese.cpp
@@ -4374,6 +4374,52 @@ constexpr Entry kTraditionalChinese[] = {
"旋轉模板,以逆時針度數表示;Ctrl+點擊以輸入。"},
{"Centre the Stencil again, upright, 80% of the view's height.",
"將模板重新置中、擺正,高度為視圖的 80%。"},
+ // --- Tube (Tool > Tube, PanelTube.cpp) ---
+ {"Delete Point", "刪除點"},
+ {"Ends", "端部"},
+ {"Even edges", "均勻邊長"},
+ {"Fixed", "固定"},
+ {"Insert Point", "插入點"},
+ {"Distance %.2f", "距離 %.2f"},
+ {"Merge", "合併"},
+ {"New Part", "新部件"},
+ {"(point %d selected)", "(已選取點 %d)"},
+ {"%d points", "%d 個點"},
+ {"Pressure %.2f", "壓力 %.2f"},
+ {"Radius %.4g", "半徑 %.4g"},
+ {"Draw Tube", "繪製 Tube"},
+ {"Result", "結果"},
+ {"Round", "圓形"},
+ {"Select a Tube Part to edit its points.", "選取一個 Tube 部件以編輯它的點。"},
+ {"Smoothing %.2f", "平滑 %.2f"},
+ {"Snap to surfaces", "吸附到表面"},
+ {"Add a point halfway between the selected point and the next one.", "在選取的點和下一個點的正中間新增一個點。"},
+ {"Bake re-sweeps the tube in triangles of one size (good for dynamic topology) instead of keeping its quads.",
+ "Bake 時用大小一致的三角形重新產生管子(適合動態拓樸),而不是保留四邊形。"},
+ {"Delete the selected point (the one last dragged, in orange). Alt+click a point does the same.",
+ "刪除選取的點(最後拖曳的那個,橘色)。Alt+點擊一個點也可以刪除它。"},
+ {"Drag anywhere in the view to draw a clay tube in the air, like a 3D pen: on the model or off it. Pen pressure makes it thinner, Symmetry X draws the mirror copy. Alt+drag still moves the view.",
+ "在視圖中任意位置拖曳,像 3D 筆一樣在空中畫出黏土管子:在模型上或模型外都可以。筆壓越輕管子越細,對稱 X 會畫出鏡像副本。Alt+拖曳仍然移動視圖。"},
+ {"Each stroke goes into the active Part, with even edge lengths close to that Part's own, ready for dynamic topology.",
+ "每一筆都合併進作用中的部件,邊長均勻並接近該部件本身的邊長,適合動態拓樸。"},
+ {"Each stroke makes a Tube Part whose points stay editable until Bake.",
+ "每一筆產生一個 Tube 部件,它的點在 Bake 之前都可以編輯。"},
+ {"Flat ends (for new tubes, and the active Tube Part).", "平面端部(用於新管子和作用中的 Tube 部件)。"},
+ {"How much a light touch of the pen thins the tube. 0: the same thickness all along.",
+ "筆的輕觸讓管子變細的程度。0:整條粗細相同。"},
+ {"How much the stroke's wobble is smoothed out before the tube is made.", "產生管子之前,筆畫的抖動被平滑掉的程度。"},
+ {"How thick new tubes are, as a radius on screen at the depth you draw at.", "新管子的粗細:在你繪製的深度上,螢幕上的半徑。"},
+ {"Make the active Tube Part a plain mesh to sculpt. Its points can't be edited after this (undo brings them back).",
+ "把作用中的 Tube 部件變成一般網格以便雕刻。之後不能再編輯它的點(復原可以找回)。"},
+ {"Round ends (for new tubes, and the active Tube Part).", "圓形端部(用於新管子和作用中的 Tube 部件)。"},
+ {"Smoothing", "平滑"},
+ {"Strokes are drawn at a fixed distance from the camera (Depth below); orbit to draw at another angle.",
+ "筆畫畫在離相機固定距離的位置(見下方的距離);環繞視圖後可以從另一個角度繪製。"},
+ {"Strokes are drawn at the depth of the surface under the pen where they start; started off the model, at the depth where the last stroke ended (or the pivot).",
+ "筆畫畫在起筆處筆下表面的深度;如果在模型外起筆,則畫在上一筆結束處的深度(或樞紐點)。"},
+ {"Strokes are drawn on the plane through the view's pivot, facing you.", "筆畫畫在穿過視圖樞紐點、面向你的平面上。"},
+ {"Where the pen is over a surface, the tube lies on it (half sunk in) instead of on the drawing plane.",
+ "筆在表面上方時,管子貼在表面上(一半陷入),而不是畫在繪製平面上。"},
};
} // namespace
diff --git a/src/app/Palettes.cpp b/src/app/Palettes.cpp
index 86ffbb20..4be079fb 100644
--- a/src/app/Palettes.cpp
+++ b/src/app/Palettes.cpp
@@ -856,6 +856,12 @@ void App::drawPalette_Tool() {
drawForgeSpheresContents(); // PanelForge Spheres.cpp
Demo::popScope();
}
+ if (subpalette("tool.tube", "Tube")) {
+ tray::Section section;
+ Demo::pushScope("Tube");
+ drawTubeContents(); // PanelTube.cpp
+ Demo::popScope();
+ }
if (subpalette("tool.layers", "Layers")) {
tray::Section section;
Demo::pushScope("Layers");
diff --git a/src/app/PanelTube.cpp b/src/app/PanelTube.cpp
new file mode 100644
index 00000000..905ada96
--- /dev/null
+++ b/src/app/PanelTube.cpp
@@ -0,0 +1,392 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Tool > Tube and the Tube tool in the viewport (core/Tube.h): draw clay tubes in the air like a 3D pen.
+// Draw Tube on: a left-drag anywhere (on the model or off it) draws a tube. Its points lie on a plane facing the
+// view: through the surface under the pen where the stroke starts (else the last stroke's end, else the pivot),
+// through the pivot, or at a fixed distance from the camera. Snap to surfaces puts points over a surface onto
+// it. Pen pressure thins the tube; the stroke is smoothed and simplified into the curve's control points.
+// The result is a new Tube Part (undo takes it away again) or, with Merge, part of the active Part.
+// A Tube Part's points show as dots: drag one to move it (in the view plane), Ctrl+drag to make the tube thicker
+// or thinner there, Alt+click to delete it. With Draw Tube on, the dots of every visible Tube Part show and a
+// press on one selects that Part. Bake makes the Part a plain mesh to sculpt.
+// Alt+drag still navigates; every stroke and point drag is one undo step. Symmetry X draws the mirror copy too.
+#include "app/App.h"
+#include "app/Demo.h"
+#include "app/Palettes.h"
+#include "app/Theme.h"
+#include "app/Ui.h"
+
+#include "core/Tube.h"
+
+#include <algorithm>
+#include <cmath>
+
+namespace sf {
+
+namespace {
+
+constexpr const char* kTubePath = "Tool > Tube";
+
+bool ctrlDown(SDL_Keymod mod) { return (mod & (SDL_KMOD_CTRL | SDL_KMOD_GUI)) != 0; } // as App.cpp
+
+glm::vec3 planeHit(const glm::vec3& o, const glm::vec3& d, const glm::vec3& p, const glm::vec3& n) {
+ const float dn = glm::dot(d, n);
+ const float t = std::abs(dn) > 1e-12f ? glm::dot(p - o, n) / dn : 0.0f;
+ return o + d * std::max(t, 0.0f);
+}
+
+} // namespace
+
+void App::registerTubeUiActions() {
+ auto add = [this](const char* id, const char* label, std::function<void()> run, std::function<bool()> enabled,
+ std::function<bool()> checked, const char* description, const char* command = "") {
+ Action a;
+ a.id = id;
+ a.label = label;
+ a.palette = kTubePath;
+ a.run = std::move(run);
+ a.enabled = std::move(enabled);
+ a.checked = std::move(checked);
+ a.description = description;
+ a.command = command;
+ actions_.add(std::move(a));
+ };
+ add("tube.draw", "Draw Tube",
+ [this] {
+ tubeDraw_ = !tubeDraw_;
+ status_ = tubeDraw_ ? "Tube: drag anywhere to draw a tube in the air (Alt+drag moves the view)"
+ : "Tube: Draw Tube off";
+ },
+ nullptr, [this] { return tubeDraw_; },
+ "Drag anywhere in the view to draw a clay tube in the air, like a 3D pen: on the model or off it. Pen "
+ "pressure makes it thinner, Symmetry X draws the mirror copy. Alt+drag still moves the view.");
+ const auto depth = [this](TubeDepth d) {
+ return [this, d] {
+ tubeDepth_ = d;
+ if (d == TubeDepth::Fixed && tubeFixedDepth_ <= 0.0f) tubeFixedDepth_ = glm::distance(camera_.position(), camera_.target);
+ };
+ };
+ add("tube.depth_surface", "Surface", depth(TubeDepth::Surface), nullptr, [this] { return tubeDepth_ == TubeDepth::Surface; },
+ "Strokes are drawn at the depth of the surface under the pen where they start; started off the model, at "
+ "the depth where the last stroke ended (or the pivot).");
+ add("tube.depth_pivot", "Pivot", depth(TubeDepth::Pivot), nullptr, [this] { return tubeDepth_ == TubeDepth::Pivot; },
+ "Strokes are drawn on the plane through the view's pivot, facing you.");
+ add("tube.depth_fixed", "Fixed", depth(TubeDepth::Fixed), nullptr, [this] { return tubeDepth_ == TubeDepth::Fixed; },
+ "Strokes are drawn at a fixed distance from the camera (Depth below); orbit to draw at another angle.");
+ add("tube.snap", "Snap to surfaces", [this] { tubeSnap_ = !tubeSnap_; }, nullptr, [this] { return tubeSnap_; },
+ "Where the pen is over a surface, the tube lies on it (half sunk in) instead of on the drawing plane.");
+ add("tube.caps_round", "Round", [this] { tubeFlatCaps_ = false; if (tubeActive()) runCommand("tube_set", {{"caps", std::string("round")}}); },
+ nullptr, [this] { return tubeActive() ? !doc_.mesh.tube.flatCaps : !tubeFlatCaps_; },
+ "Round ends (for new tubes, and the active Tube Part).", "tube_set");
+ add("tube.caps_flat", "Flat", [this] { tubeFlatCaps_ = true; if (tubeActive()) runCommand("tube_set", {{"caps", std::string("flat")}}); },
+ nullptr, [this] { return tubeActive() ? doc_.mesh.tube.flatCaps : tubeFlatCaps_; },
+ "Flat ends (for new tubes, and the active Tube Part).", "tube_set");
+ add("tube.new_part", "New Part", [this] { tubeMerge_ = false; }, nullptr, [this] { return !tubeMerge_; },
+ "Each stroke makes a Tube Part whose points stay editable until Bake.");
+ add("tube.merge", "Merge", [this] { tubeMerge_ = true; }, nullptr, [this] { return tubeMerge_; },
+ "Each stroke goes into the active Part, with even edge lengths close to that Part's own, ready for dynamic "
+ "topology.");
+ const auto selected = [this] { return tubeSelection() >= 0; };
+ add("tube.delete_point", "Delete Point",
+ [this] { if (const int i = tubeSelection(); i >= 0) runCommand("tube_delete_point", {{"index", double(i)}}); tubeSelected_ = -1; },
+ selected, nullptr, "Delete the selected point (the one last dragged, in orange). Alt+click a point does the same.",
+ "tube_delete_point");
+ add("tube.insert_point", "Insert Point",
+ [this] {
+ const int i = tubeSelection();
+ if (i < 0) return;
+ const int at = size_t(i) + 1 < doc_.mesh.tube.points.size() ? i : i - 1;
+ if (at >= 0) runCommand("tube_insert_point", {{"index", double(at)}});
+ tubeSelected_ = at + 1;
+ },
+ selected, nullptr, "Add a point halfway between the selected point and the next one.", "tube_insert_point");
+ add("tube.bake", "Bake",
+ [this] {
+ runCommand("tube_bake", {{"uniform", tubeBakeUniform_}});
+ tubeSelected_ = -1;
+ },
+ [this] { return tubeActive(); }, nullptr,
+ "Make the active Tube Part a plain mesh to sculpt. Its points can't be edited after this (undo brings them "
+ "back).",
+ "tube_bake");
+}
+
+void App::drawTubeContents() {
+ const ImGuiStyle& style = ImGui::GetStyle();
+ const float full = ImGui::GetContentRegionAvail().x;
+ ui::ActionButton(*this, "tube.draw", ImVec2(full, 0));
+ tray::GroupLabel(*this, "Stroke");
+ ImGui::SetNextItemWidth(full);
+ ui::SliderInside("##tubesize", &tubeSizePx_, 2.0f, 120.0f, tr("Size %.0f"));
+ ui::HelpText("Size", nullptr, "How thick new tubes are, as a radius on screen at the depth you draw at.", kTubePath);
+ ImGui::SetNextItemWidth(full);
+ ui::SliderInside("##tubepressure", &tubePressure_, 0.0f, 1.0f, tr("Pressure %.2f"));
+ ui::HelpText("Pressure", nullptr, "How much a light touch of the pen thins the tube. 0: the same thickness all along.",
+ kTubePath);
+ ImGui::SetNextItemWidth(full);
+ ui::SliderInside("##tubesmooth", &tubeSmoothing_, 0.0f, 1.0f, tr("Smoothing %.2f"));
+ ui::HelpText("Smoothing", nullptr, "How much the stroke's wobble is smoothed out before the tube is made.", kTubePath);
+ ImGui::AlignTextToFramePadding();
+ ImGui::TextDisabled("%s", tr("Depth"));
+ ImGui::SameLine();
+ ui::Segmented(*this, {"tube.depth_surface", "tube.depth_pivot", "tube.depth_fixed"});
+ if (tubeDepth_ == TubeDepth::Fixed) {
+ const float far = std::max(10.0f * glm::distance(camera_.position(), camera_.target), 1.0f);
+ ImGui::SetNextItemWidth(full);
+ ui::SliderInside("##tubedepth", &tubeFixedDepth_, 0.0f, far, tr("Distance %.2f"));
+ }
+ ui::ActionButton(*this, "tube.snap", ImVec2(full, 0));
+ ImGui::AlignTextToFramePadding();
+ ImGui::TextDisabled("%s", tr("Ends"));
+ ImGui::SameLine();
+ ui::Segmented(*this, {"tube.caps_round", "tube.caps_flat"});
+ ImGui::AlignTextToFramePadding();
+ ImGui::TextDisabled("%s", tr("Result"));
+ ImGui::SameLine();
+ ui::Segmented(*this, {"tube.new_part", "tube.merge"});
+ if (!tubeActive()) {
+ ImGui::PushTextWrapPos(0.0f);
+ ImGui::TextDisabled("%s", tr("Select a Tube Part to edit its points."));
+ ImGui::PopTextWrapPos();
+ return;
+ }
+ tray::GroupLabel(*this, "Edit");
+ const TubeShape& t = doc_.mesh.tube;
+ ImGui::TextDisabled(tr("%d points"), int(t.points.size()));
+ if (const int sel = tubeSelection(); sel >= 0) {
+ ImGui::SameLine();
+ ImGui::TextDisabled(tr("(point %d selected)"), sel);
+ // (applied as one undo step when the slider is let go)
+ const float stored = t.points[size_t(sel)].radius;
+ float r = tubeRadiusEdit_ > 0.0f && tubeRadiusEditPoint_ == sel ? tubeRadiusEdit_ : stored;
+ ImGui::SetNextItemWidth(full);
+ if (ui::SliderInside("##tubepointr", &r, 0.0f, 4.0f * stored, tr("Radius %.4g")) && r > 0.0f) {
+ tubeRadiusEdit_ = r;
+ tubeRadiusEditPoint_ = sel;
+ }
+ if (ImGui::IsItemDeactivatedAfterEdit() && tubeRadiusEdit_ > 0.0f) {
+ runCommand("tube_set_point", {{"index", double(sel)}, {"radius", double(tubeRadiusEdit_)}});
+ tubeRadiusEdit_ = -1.0f;
+ }
+ }
+ const float half = (full - style.ItemSpacing.x) * 0.5f;
+ ui::ActionButton(*this, "tube.delete_point", ImVec2(half, 0));
+ ImGui::SameLine();
+ ui::ActionButton(*this, "tube.insert_point", ImVec2(-1, 0));
+ ui::ActionButton(*this, "tube.bake", ImVec2(half, 0));
+ ImGui::SameLine();
+ ui::Checkbox(tr("Even edges##tube_bake_uniform"), &tubeBakeUniform_);
+ ui::HelpText("Even edges", nullptr,
+ "Bake re-sweeps the tube in triangles of one size (good for dynamic topology) instead of keeping its quads.",
+ kTubePath);
+}
+
+glm::vec3 App::tubeViewDir() const { return glm::normalize(camera_.target - camera_.position()); }
+
+int App::tubeSelection() const {
+ return tubeActive() && tubeSelected_ >= 0 && size_t(tubeSelected_) < doc_.mesh.tube.points.size() ? tubeSelected_ : -1;
+}
+
+int App::tubePointAt(float x, float y, int* part) const {
+ const float reach = 9.0f * uiScale_;
+ float best = reach * reach;
+ int found = -1;
+ for (int i = 0; i < doc_.partCount(); ++i) {
+ if (i != doc_.activePart && !tubeDraw_) continue; // other Tube Parts' points show while drawing
+ if (!doc_.parts[size_t(i)].visible) continue;
+ const TubeShape& t = doc_.partMesh(i).tube;
+ for (size_t k = 0; k < t.points.size(); ++k) {
+ ImVec2 s;
+ if (!gizmoProject(t.points[k].position, s)) continue;
+ const float d2 = (s.x - x) * (s.x - x) + (s.y - y) * (s.y - y);
+ if (d2 < best || (d2 == best && i == doc_.activePart)) {
+ best = d2;
+ found = int(k);
+ if (part) *part = i;
+ }
+ }
+ }
+ return found;
+}
+
+bool App::tubeMouseDown(float x, float y, SDL_Keymod mod) {
+ const SDL_Keymod keys = SDL_GetModState(); // the keyboard itself
+ int part = -1;
+ const int point = (tubeActive() || tubeDraw_) ? tubePointAt(x, y, &part) : -1;
+ TubeDrag& d = tubeDrag_;
+ if (point >= 0) {
+ if (part != doc_.activePart) {
+ runCommand("part_select", {{"index", double(part)}});
+ partSelected("tube point");
+ }
+ if (!tubeMatchesMesh(doc_.mesh)) {
+ status_ = "Tube: this Part was moved or changed since it was drawn; Bake keeps it as it is (or undo the change)";
+ return true;
+ }
+ if (keys & SDL_KMOD_ALT) {
+ if (doc_.mesh.tube.points.size() > 1) runCommand("tube_delete_point", {{"index", double(point)}});
+ else status_ = "Tube: the last point stays (delete the Part instead)";
+ tubeSelected_ = -1;
+ return true;
+ }
+ d = {};
+ d.point = point;
+ d.resize = ctrlDown(mod);
+ d.start = doc_.mesh.tube;
+ d.before = doc_.mesh;
+ d.x = x;
+ d.y = y;
+ glm::vec3 o, dir;
+ canvasRay(x, y, o, dir);
+ const glm::vec3 c = d.start.points[size_t(point)].position;
+ d.grab = c - planeHit(o, dir, c, tubeViewDir());
+ tubeSelected_ = point;
+ drag_ = Drag::Tube;
+ return true;
+ }
+ if (tubeDraw_) {
+ if (keys & SDL_KMOD_ALT) return false; // navigates
+ d = {};
+ d.drawing = true;
+ d.planeNormal = tubeViewDir();
+ RayHit hit;
+ const glm::vec3 eye = camera_.position();
+ if (tubeDepth_ == TubeDepth::Fixed) {
+ if (tubeFixedDepth_ <= 0.0f) tubeFixedDepth_ = glm::distance(eye, camera_.target);
+ d.planePoint = eye + d.planeNormal * tubeFixedDepth_;
+ } else if (tubeDepth_ == TubeDepth::Surface && pickPart(x, y, &hit) >= 0) {
+ d.planePoint = hit.position;
+ } else if (tubeDepth_ == TubeDepth::Surface && tubeHaveAnchor_ && glm::dot(tubeAnchor_ - eye, d.planeNormal) > 0.0f) {
+ d.planePoint = tubeAnchor_;
+ } else {
+ d.planePoint = camera_.target;
+ }
+ const float wpp = worldPerPixel(d.planePoint);
+ d.radius = std::max(tubeSizePx_ * (wpp > 0.0f ? wpp : 0.01f), 1e-5f);
+ d.x = x;
+ d.y = y;
+ drag_ = Drag::Tube;
+ tubeDragTo(x, y);
+ return true;
+ }
+ if (tubeActive()) { // a Tube Part isn't sculpted until it is baked
+ RayHit hit;
+ if (!pick(x, y, hit)) return false; // the background navigates
+ status_ = "Tube: drag a point to move it (Ctrl: thickness, Alt+click: delete); Bake to sculpt this Part";
+ return true;
+ }
+ return false;
+}
+
+void App::tubeDragTo(float x, float y) {
+ TubeDrag& d = tubeDrag_;
+ glm::vec3 o, dir;
+ canvasRay(x, y, o, dir);
+ if (d.drawing) {
+ const float pressure = std::clamp(strokePressure(), 0.0f, 1.0f);
+ const float r = d.radius * (1.0f - tubePressure_ + tubePressure_ * std::max(pressure, 0.05f));
+ glm::vec3 p = planeHit(o, dir, d.planePoint, d.planeNormal);
+ RayHit hit;
+ if (tubeSnap_ && pickPart(x, y, &hit) >= 0) p = hit.position + glm::normalize(hit.normal) * (0.5f * r);
+ if (!d.samples.empty() && glm::distance(d.samples.back().position, p) < 0.1f * r) return;
+ d.samples.push_back({p, r});
+ const float wpp = worldPerPixel(p);
+ d.screen.push_back(ImVec4(x, y, wpp > 0.0f ? r / wpp : tubeSizePx_, 0.0f));
+ return;
+ }
+ if (d.point < 0) return;
+ TubeShape s = d.start;
+ TubePoint& p = s.points[size_t(d.point)];
+ if (d.resize) {
+ const float amount = ((x - d.x) - (y - d.y)) / (120.0f * uiScale_);
+ p.radius = std::max(d.start.points[size_t(d.point)].radius * std::exp(amount), 1e-5f);
+ status_ = "Tube: point " + std::to_string(d.point) + " radius " + std::to_string(p.radius).substr(0, 6);
+ } else {
+ p.position = planeHit(o, dir, p.position, tubeViewDir()) + d.grab;
+ }
+ doc_.mesh = tubeMesh(s, kTubePreviewTriangles); // (coarser while dragging a long or thin tube)
+ doc_.mesh.topologyDirty = true;
+ doc_.bvhDirty = true; // (built once when let go)
+ tubeDrag_.preview = s;
+ d.changed = true;
+}
+
+void App::tubeRelease() {
+ TubeDrag& d = tubeDrag_;
+ if (d.drawing) {
+ TubeShape s;
+ s.points = tubeFromStroke(d.samples, tubeSmoothing_);
+ s.flatCaps = tubeFlatCaps_;
+ s.mirrorX = symmetry_.x;
+ if (!s.points.empty()) {
+ int edited = -1;
+ const CommandResult r = tubeAdd(doc_, s, tubeMerge_, "Tube", &edited);
+ status_ = r.message;
+ if (r.ok) {
+ tubeAnchor_ = s.points.back().position;
+ tubeHaveAnchor_ = true;
+ }
+ }
+ } else if (d.changed) {
+ doc_.mesh = std::move(d.before);
+ doc_.replaceMeshUndoable(tubeMesh(d.preview), d.resize ? "Tube point size" : "Tube point"); // (full density)
+ status_ = std::string("Tube: ") + (d.resize ? "point size" : "point moved") + "; " +
+ std::to_string(doc_.mesh.tube.points.size()) + " points";
+ }
+ d = {};
+}
+
+void App::drawTubeOverlay() {
+ const CanvasRect cr = canvasRect();
+ ImDrawList* dl = ImGui::GetBackgroundDrawList();
+ const float s = uiScale_;
+ dl->PushClipRect(ImVec2(cr.x, cr.y), ImVec2(cr.x + cr.w, cr.y + cr.h), true);
+ const TubeDrag& d = tubeDrag_;
+ if (drag_ == Drag::Tube && d.drawing) { // the trail: the tube's silhouette as the pen moves
+ const ImU32 fill = IM_COL32(205, 170, 140, 150), edge = theme::u32(theme::accent);
+ for (const ImVec4& p : d.screen) dl->AddCircleFilled(ImVec2(p.x, p.y), std::max(p.z, 1.0f), fill, 20);
+ for (size_t i = 1; i < d.screen.size(); ++i)
+ dl->AddLine(ImVec2(d.screen[i - 1].x, d.screen[i - 1].y), ImVec2(d.screen[i].x, d.screen[i].y), edge, 1.5f * s);
+ dl->PopClipRect();
+ return;
+ }
+ // The control points of the active Tube Part (and, while drawing tubes, of every visible one).
+ const bool hoverOk = !ImGui::GetIO().WantCaptureMouse && cr.contains(mouseX_, mouseY_) && drag_ == Drag::None;
+ int hoverPart = -1;
+ const int hover = hoverOk ? tubePointAt(mouseX_, mouseY_, &hoverPart) : -1;
+ for (int i = 0; i < doc_.partCount(); ++i) {
+ if ((i != doc_.activePart && !tubeDraw_) || !doc_.parts[size_t(i)].visible) continue;
+ const TubeShape& t = doc_.partMesh(i).tube;
+ const bool active = i == doc_.activePart;
+ ImVec2 prev;
+ bool havePrev = false;
+ for (size_t k = 0; k < t.points.size(); ++k) {
+ ImVec2 p;
+ if (!gizmoProject(t.points[k].position, p)) {
+ havePrev = false;
+ continue;
+ }
+ if (havePrev) dl->AddLine(prev, p, IM_COL32(120, 200, 255, active ? 110 : 60), 1.0f * s);
+ prev = p;
+ havePrev = true;
+ }
+ for (size_t k = 0; k < t.points.size(); ++k) {
+ ImVec2 p;
+ if (!gizmoProject(t.points[k].position, p)) continue;
+ const bool sel = active && int(k) == tubeSelection();
+ const bool hot = int(k) == hover && i == hoverPart;
+ const ImU32 col = hot ? ((inputMods() & SDL_KMOD_ALT) ? IM_COL32(255, 90, 80, 240) : IM_COL32(120, 200, 255, 240))
+ : sel ? IM_COL32(255, 170, 60, 240)
+ : IM_COL32(235, 235, 235, active ? 220 : 120);
+ dl->AddCircleFilled(p, (hot || sel ? 4.5f : 3.5f) * s, col, 12);
+ dl->AddCircle(p, (hot || sel ? 4.5f : 3.5f) * s, IM_COL32(20, 20, 20, 200), 12, 1.0f * s);
+ }
+ }
+ // Draw Tube's cursor: how thick the tube will be.
+ if (tubeDraw_ && hoverOk && hover < 0)
+ dl->AddCircle(ImVec2(mouseX_, mouseY_), tubeSizePx_, theme::u32(theme::accent), 32, 1.5f * s);
+ dl->PopClipRect();
+}
+
+} // namespace sf
diff --git a/src/app/UiTest.cpp b/src/app/UiTest.cpp
index b8b4cea9..6a5eef2c 100644
--- a/src/app/UiTest.cpp
+++ b/src/app/UiTest.cpp
@@ -636,6 +636,14 @@ double Demo::query(const std::string& name, bool& known) const {
if (name == "guides_mode") return app_.guidesMode_ ? 1.0 : 0.0;
if (name == "forgespheres") return double(m.forgespheres.size());
if (name == "forgesphere_preview") return m.forgespherePreview ? 1.0 : 0.0;
+ if (name == "tube_points") return double(m.tube.points.size()); // the active Tube Part's (Tube, PanelTube.cpp)
+ if (name == "tube_draw") return app_.tubeDraw_ ? 1.0 : 0.0;
+ if (name == "tube_selected") return double(app_.tubeSelection());
+ if (name == "tube_parts") {
+ int n = 0;
+ for (int i = 0; i < app_.doc_.partCount(); ++i) n += !app_.doc_.partMesh(i).tube.empty();
+ return double(n);
+ }
if (name == "forgesphere_selected") return double(app_.forgesphereSelection());
if (name == "forgesphere_menu") return app_.zsMenuShown_ ? 1.0 : 0.0;
if (name == "forgesphere_place_child") return app_.forgespherePlaceChild_ ? 1.0 : 0.0;
@@ -1732,6 +1740,37 @@ bool Demo::parseStep(int line, const std::vector<std::string>& w, std::string& e
if (!app_.actions_.find(id)) fail(line, "no action " + id);
else if (got != want) fail(line, id + " has \"" + got + "\", expected \"" + want + "\"");
});
+ } else if (verb == "drag_tube_point") {
+ // drag_tube_point K DX DY [seconds]: press on control point K of the active Tube Part (else the first visible
+ // one; Tube, PanelTube.cpp) and drag it DX, DY pixels; 0 0 is a click.
+ if (!need(3)) return false;
+ const int index = int(num(1, 0));
+ const float dx = num(2, 0), dy = num(3, 0), seconds = num(4, 0.4f);
+ auto start = std::make_shared<ImVec2>();
+ steps_.push_back([this, line, index, dx, dy, seconds, start](float t) {
+ if (t == 0.0f) {
+ const Document& doc = app_.doc_;
+ int part = doc.mesh.tube.empty() ? -1 : doc.activePart;
+ for (int i = 0; part < 0 && i < doc.partCount(); ++i)
+ if (doc.parts[size_t(i)].visible && !doc.partMesh(i).tube.empty()) part = i;
+ const TubeShape* tube = part >= 0 ? &doc.partMesh(part).tube : nullptr;
+ if (!tube || index < 0 || size_t(index) >= tube->points.size() ||
+ !app_.gizmoProject(tube->points[size_t(index)].position, *start)) {
+ fail(line, "tube point " + std::to_string(index) + " is not on screen");
+ return true;
+ }
+ mouseMotion(start->x, start->y);
+ return false;
+ }
+ if (!buttonDown_ && t < seconds) mouseButton(true, SDL_BUTTON_LEFT);
+ const float u = std::min(t / seconds, 1.0f);
+ mouseMotion(start->x + dx * u, start->y + dy * u);
+ if (t >= seconds) {
+ mouseButton(false, SDL_BUTTON_LEFT);
+ return true;
+ }
+ return false;
+ });
} else if (verb == "drag_landmark") {
if (!need(3)) return false;
const int index = int(num(1, 0));
diff --git a/src/core/AgentTools.cpp b/src/core/AgentTools.cpp
index 1c26e710..5bc69050 100644
--- a/src/core/AgentTools.cpp
+++ b/src/core/AgentTools.cpp
@@ -160,6 +160,7 @@ void registerAgentTools(CommandRegistry& reg) {
out += "\n" + std::to_string(i) + ". " + p.name + ": " + std::to_string(m.triangleCount()) + " triangles";
if (subdivLevelCount(m)) out += ", " + subdivLevelText(m);
if (!m.forgespheres.empty()) out += ", Forge Spheres (" + std::to_string(m.forgespheres.size()) + ")";
+ if (!m.tube.empty()) out += ", Tube (" + std::to_string(m.tube.points.size()) + " points, editable until tube_bake)";
if (m.triangleCount()) out += ", " + partLine(doc, i);
if (i == doc.activePart) out += ", active";
if (!p.visible) out += ", hidden";
diff --git a/src/core/CloseHoles.cpp b/src/core/CloseHoles.cpp
index c9cd8822..7a66916d 100644
--- a/src/core/CloseHoles.cpp
+++ b/src/core/CloseHoles.cpp
@@ -487,6 +487,7 @@ void registerCloseHolesCommands(CommandRegistry& registry) {
[](Document& doc, const Args& a) -> CommandResult {
if (doc.mesh.triangleCount() == 0) return {false, "The Part is empty"};
if (!doc.mesh.forgespheres.empty()) return {false, "Close Holes: make Forge Spheres into a mesh first"};
+ if (!doc.mesh.tube.empty()) return {false, "Close Holes: bake the Tube first"};
if (doc.mesh.micro) return {false, "Close Holes: apply or remove the micro level first"};
CloseHolesOptions o;
o.maxEdges = size_t(std::max(0.0, argNumber(a, "max_edges", 0.0)));
diff --git a/src/core/Commands.cpp b/src/core/Commands.cpp
index 8063b7e0..b81ffa97 100644
--- a/src/core/Commands.cpp
+++ b/src/core/Commands.cpp
@@ -36,6 +36,7 @@
#include "core/Project.h"
#include "core/QRemesh.h"
#include "core/ForgeSpheres.h"
+#include "core/Tube.h"
#include "core/Garment.h"
#include "core/Deform.h"
#include "core/Sculptable.h"
@@ -694,6 +695,7 @@ CommandRegistry::CommandRegistry() {
registerRetopoCommands(*this); // qremesh, project_all (RetopoCommands.cpp)
registerQRemeshGuideCommands(*this); // qremesh_guide, ... (QRemeshGuides.cpp)
registerForgeSphereCommands(*this); // Forge Sphere_new, ... (Forge Spheres.cpp)
+ registerTubeCommands(*this); // tube_new, ... (Tube.cpp)
registerAgentTools(*this); // blockout, measure, scene_overview (core/AgentTools.cpp)
registerDeformCommands(*this); // deform_polish, deform_relax, deform_smooth, deform_balloon (Deform.cpp)
diff --git a/src/core/Cut.cpp b/src/core/Cut.cpp
index 56ecbe39..c9395070 100644
--- a/src/core/Cut.cpp
+++ b/src/core/Cut.cpp
@@ -1311,6 +1311,7 @@ void registerCutCommands(CommandRegistry& registry) {
[](Document& doc, const Args& a) -> CommandResult {
if (doc.mesh.triangleCount() == 0) return {false, "The Part is empty"};
if (!doc.mesh.forgespheres.empty()) return {false, "Cut: make Forge Spheres into a mesh first"};
+ if (!doc.mesh.tube.empty()) return {false, "Cut: bake the Tube first"};
if (doc.mesh.micro) return {false, "Cut: apply or remove the micro level first"};
CutShape shape = CutShape::Lasso;
CutMode mode = CutMode::Away;
diff --git a/src/core/Deform.cpp b/src/core/Deform.cpp
index a8f63ee9..6864af7a 100644
--- a/src/core/Deform.cpp
+++ b/src/core/Deform.cpp
@@ -202,6 +202,10 @@ size_t deformActivePart(Document& doc, DeformOp op, const DeformOptions& o, std:
error = name + ": the active Part is a Forge Sphere Part (Make Mesh first)";
return 0;
}
+ if (!mesh.tube.empty()) {
+ error = name + ": the active Part is a Tube Part (Bake it first)";
+ return 0;
+ }
if (mesh.micro) {
error = name + ": the active Part has a micro level (Bake Micro or Delete Micro first)";
return 0;
diff --git a/src/core/Dyntopo.cpp b/src/core/Dyntopo.cpp
index 99738a9b..2a248c7c 100644
--- a/src/core/Dyntopo.cpp
+++ b/src/core/Dyntopo.cpp
@@ -111,6 +111,7 @@ std::string dyntopoBlocker(const Mesh& mesh) {
if (mesh.multires)
return "Dynamic topology needs a mesh without subdivision levels: Freeze Levels keeps the level shown and removes the others";
if (mesh.triangleCount() == 0) return "The mesh has no triangles";
+ if (!mesh.tube.empty()) return "This is a Tube Part: Bake it first (Tool > Tube > Bake)";
return {};
}
diff --git a/src/core/ExtractMirror.cpp b/src/core/ExtractMirror.cpp
index 514975c9..a4aa978e 100644
--- a/src/core/ExtractMirror.cpp
+++ b/src/core/ExtractMirror.cpp
@@ -72,6 +72,10 @@ Mesh extractShell(const Mesh& mesh, const ExtractOptions& o, std::string& error)
error = "Extract works on meshes; make the Forge Spheres a mesh first";
return {};
}
+ if (!mesh.tube.empty()) {
+ error = "Extract works on meshes; bake the Tube first";
+ return {};
+ }
// The patch: the visible triangles whose corners are masked (on average), with their own vertices.
std::vector<uint32_t> remap(nv, kNone), kept, patchOf(mesh.hasQuads() ? nt : 0, kNone);
std::vector<glm::uvec3> tris;
@@ -385,6 +389,7 @@ Mesh mirrorFlip(const Mesh& mesh, int axis, float pivot) {
for (auto& l : out.layers)
for (auto& v : l.delta) v[axis] = -v[axis];
for (auto& z : out.forgespheres) z.center[axis] = 2.0f * pivot - z.center[axis];
+ for (auto& p : out.tube.points) p.position[axis] = 2.0f * pivot - p.position[axis];
for (auto& t : out.triangles) std::swap(t.y, t.z);
for (size_t t = 0; t * 3 + 2 < out.uvs.size(); ++t) std::swap(out.uvs[3 * t + 1], out.uvs[3 * t + 2]);
out.rebuildTopology();
@@ -485,6 +490,7 @@ void registerExtractMirrorCommands(CommandRegistry& reg) {
if (!positive && side != "negative" && side != "-" && side != "neg")
return {false, "Bad side '" + side + "' (positive or negative)"};
if (!doc.mesh.forgespheres.empty()) return {false, "Mirror And Weld works on meshes; make the Forge Spheres a mesh first"};
+ if (!doc.mesh.tube.empty()) return {false, "Mirror And Weld works on meshes; bake the Tube first"};
if (doc.mesh.triangleCount() == 0) return {false, "The Part is empty"};
const size_t before = doc.mesh.triangleCount();
Mesh m = doc.mesh;
diff --git a/src/core/Mesh.h b/src/core/Mesh.h
index acf066e0..09366010 100644
--- a/src/core/Mesh.h
+++ b/src/core/Mesh.h
@@ -88,6 +88,20 @@ struct ForgeSphere {
int parent = -1;
};
+// A Tube's curve (core/Tube.h): control points the tube passes through, each with its own radius. Not empty =
+// a Tube Part, whose triangles are swept along the curve until Bake.
+struct TubePoint {
+ glm::vec3 position{0.0f};
+ float radius = 0.1f;
+};
+struct TubeShape {
+ std::vector<TubePoint> points;
+ bool flatCaps = false; // flat ends instead of round
+ bool mirrorX = false; // a mirror copy across x = 0 (symmetry X)
+ float edge = 0.0f; // target edge length; 0 = from the radius (16 sides around the average)
+ bool empty() const { return points.empty(); }
+};
+
class Mesh {
public:
std::vector<glm::vec3> positions;
@@ -209,6 +223,9 @@ public:
std::vector<ForgeSphere> forgespheres;
bool forgespherePreview = false;
+ // Tube (core/Tube.h): not empty = a Tube Part, whose triangles are swept from this curve; Bake clears it.
+ TubeShape tube;
+
// Selection Sets (core/SelectionSets.h): named snapshots of the mask, face groups, vertex paint, hidden faces, UVs
// and shape, immutable and shared by copies of the mesh (undo steps swap the whole list). They belong to the
// Part, not to one subdivision level: stepping levels keeps them. Null = none.
diff --git a/src/core/Micro.cpp b/src/core/Micro.cpp
index 967b953a..8f417f7c 100644
--- a/src/core/Micro.cpp
+++ b/src/core/Micro.cpp
@@ -348,6 +348,10 @@ bool microDivide(Mesh& m, int level, std::string& error, int outOfCore) {
error = "Forge Sphere Parts can't have a micro level (make an adaptive skin first)";
return false;
}
+ if (!m.tube.empty()) {
+ error = "Tube Parts can't have a micro level (Bake the tube first)";
+ return false;
+ }
if (!m.layers.empty()) {
error = "Sculpt layers can't carry a micro level yet: bake or delete the layers first";
return false;
diff --git a/src/core/Project.cpp b/src/core/Project.cpp
index 8aff1c17..57ac5313 100644
--- a/src/core/Project.cpp
+++ b/src/core/Project.cpp
@@ -13,6 +13,7 @@
#include "core/Texture.h"
#include "core/ThreadPool.h"
#include "core/ForgeSpheres.h"
+#include "core/Tube.h"
#include "io/Zip.h"
#include <algorithm>
@@ -952,6 +953,7 @@ bool saveProject(const std::string& path, const Document& doc, std::string& erro
st.set("forgespheres", forgespheresToJson(m.forgespheres));
if (m.forgespherePreview) st.set("forgesphere_preview", true);
}
+ if (const Mesh& m = doc.partMesh(i); !m.tube.empty()) st.set("tube", tubeToJson(m.tube)); // a Tube Part (core/Tube.h); optional
parts.push(std::move(st));
}
manifest.set("parts", std::move(parts));
@@ -1104,6 +1106,7 @@ bool loadProject(const std::string& path, Document& doc, std::string& error) {
if (!readMesh(r, sj["mesh"], sj["layers"], s.mesh, error, false, false)) return false;
s.mesh.forgespheres = forgespheresFromJson(sj["forgespheres"]);
s.mesh.forgespherePreview = !s.mesh.forgespheres.empty() && sj["forgesphere_preview"].asBool(false);
+ s.mesh.tube = tubeFromJson(sj["tube"]);
readSelectionSets(r, sj["selection_sets"], s.mesh, skippedSets);
// The BVH builds (on the pool) while the levels and topology load (off it), then the normals.
s.startBvh();
diff --git a/src/core/Tube.cpp b/src/core/Tube.cpp
new file mode 100644
index 00000000..97aa3a30
--- /dev/null
+++ b/src/core/Tube.cpp
@@ -0,0 +1,653 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "core/Tube.h"
+
+#include "core/Commands.h"
+#include "core/Parts.h"
+#include "core/PathStroke.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <sstream>
+
+namespace sf {
+
+using glm::vec3;
+
+namespace {
+
+constexpr float kPi = 3.14159265358979f;
+constexpr float kTurnPerRing = 10.0f * kPi / 180.0f; // a new ring at least every 10 degrees of bend
+constexpr size_t kMaxRings = 200000;
+constexpr int kMaxSides = 256;
+constexpr int kMaxCapRings = 64;
+
+bool finite(const vec3& v) { return std::isfinite(v.x) && std::isfinite(v.y) && std::isfinite(v.z); }
+
+// The points without consecutive duplicates (which would give the spline a zero-length span).
+std::vector<TubePoint> distinctPoints(const std::vector<TubePoint>& in) {
+ std::vector<TubePoint> out;
+ float rmax = 0.0f;
+ for (const TubePoint& p : in) rmax = std::max(rmax, p.radius);
+ const float eps = std::max(rmax, 1e-6f) * 1e-4f;
+ for (const TubePoint& p : in)
+ if (out.empty() || glm::distance(out.back().position, p.position) > eps) out.push_back(p);
+ return out;
+}
+
+// Barry-Goldman evaluation of a centripetal Catmull-Rom span (p1 -> p2) at knot t in [t1, t2].
+template <class V> V lerpKnots(const V& a, const V& b, float ta, float tb, float t) {
+ const float d = tb - ta;
+ return d > 0.0f ? a * ((tb - t) / d) + b * ((t - ta) / d) : a;
+}
+template <class V>
+V catmullRom(const V& p0, const V& p1, const V& p2, const V& p3, float t0, float t1, float t2, float t3, float t) {
+ const V a1 = lerpKnots(p0, p1, t0, t1, t), a2 = lerpKnots(p1, p2, t1, t2, t), a3 = lerpKnots(p2, p3, t2, t3, t);
+ const V b1 = lerpKnots(a1, a2, t0, t2, t), b2 = lerpKnots(a2, a3, t1, t3, t);
+ return lerpKnots(b1, b2, t1, t2, t);
+}
+
+// Any unit vector at right angles to `t`.
+vec3 perpendicular(const vec3& t) {
+ const vec3 a = std::abs(t.x) < 0.6f ? vec3(1, 0, 0) : std::abs(t.y) < 0.6f ? vec3(0, 1, 0) : vec3(0, 0, 1);
+ return glm::normalize(a - t * glm::dot(a, t));
+}
+
+struct Ring {
+ vec3 center, n, b;
+ float radius; // 0 = a pole (one vertex)
+ int sides;
+ uint32_t group; // of the band from this ring to the next
+};
+
+// Builds the triangles of one or more tubes into the same arrays.
+struct Builder {
+ Mesh m;
+ std::vector<uint32_t> groups;
+ bool quads = true; // pair matching bands into quads (not for even-edge sweeps: triangles for dynamic topology)
+
+ uint32_t addRing(const Ring& r) {
+ const uint32_t first = uint32_t(m.positions.size());
+ if (r.sides <= 1) {
+ m.positions.push_back(r.center);
+ return first;
+ }
+ for (int j = 0; j < r.sides; ++j) {
+ const float a = 2.0f * kPi * float(j) / float(r.sides);
+ m.positions.push_back(r.center + r.radius * (std::cos(a) * r.n + std::sin(a) * r.b));
+ }
+ return first;
+ }
+ void tri(uint32_t a, uint32_t b, uint32_t c, uint32_t g) {
+ m.triangles.emplace_back(a, b, c);
+ groups.push_back(g);
+ }
+ // Joins ring A (na vertices from a0) to ring B further along the curve: quads when they match, else a strip
+ // walking both rings by angle. Outward winding: (A_j, A_j+1, B_j+1) faces away from the centre line.
+ void stitch(uint32_t a0, int na, uint32_t b0, int nb, uint32_t g) {
+ auto A = [&](int i) { return a0 + uint32_t(na <= 1 ? 0 : i % na); };
+ auto B = [&](int j) { return b0 + uint32_t(nb <= 1 ? 0 : j % nb); };
+ if (na == nb && na > 1) {
+ for (int j = 0; j < na; ++j) {
+ tri(A(j), A(j + 1), B(j + 1), g);
+ tri(A(j), B(j + 1), B(j), g);
+ if (quads) m.pairQuad(uint32_t(m.triangles.size() - 2), uint32_t(m.triangles.size() - 1));
+ }
+ return;
+ }
+ const int ea = na <= 1 ? 0 : na, eb = nb <= 1 ? 0 : nb; // edges along each ring
+ int i = 0, j = 0;
+ while (i < ea || j < eb) {
+ const bool advanceA = j >= eb || (i < ea && float(i + 1) * float(eb) <= float(j + 1) * float(ea));
+ if (advanceA) {
+ tri(A(i), A(i + 1), B(j), g);
+ ++i;
+ } else {
+ tri(A(i), B(j + 1), B(j), g);
+ ++j;
+ }
+ }
+ }
+
+ void sweep(const TubeShape& shape, bool uniform, float edge, uint32_t groupOffset) {
+ const std::vector<TubeSample> line = tubeCenterline(shape, edge);
+ if (line.empty()) return;
+ quads = !uniform;
+ const bool flat = shape.flatCaps && line.size() > 1;
+ float rmax = 0.0f;
+ for (const TubeSample& s : line) rmax = std::max(rmax, s.radius);
+ int fixedSides = std::clamp(int(std::lround(2.0f * kPi * rmax / edge)), 6, kMaxSides);
+ fixedSides += fixedSides & 1;
+ auto sidesFor = [&](float radius, int least) {
+ if (radius <= 0.0f) return 1;
+ return uniform ? std::clamp(int(std::lround(2.0f * kPi * radius / edge)), least, kMaxSides) : fixedSides;
+ };
+
+ const std::vector<vec3> normals = tubeFrames(line);
+
+ std::vector<Ring> rings;
+ auto cap = [&](const TubeSample& s, const vec3& n, bool start) {
+ const vec3 out = start ? -s.tangent : s.tangent;
+ const vec3 b = glm::cross(s.tangent, n);
+ const uint32_t g = groupOffset + (start ? kTubeStartCapGroup : kTubeEndCapGroup);
+ const int k = flat ? std::clamp(int(std::lround(s.radius / edge)), 1, kMaxCapRings)
+ : std::clamp(int(std::lround(0.5f * kPi * s.radius / edge)), 2, kMaxCapRings);
+ std::vector<Ring> part; // from the pole towards the body ring
+ for (int i = 0; i < k; ++i) {
+ Ring r;
+ r.n = n;
+ r.b = b;
+ r.group = g;
+ if (flat) {
+ r.center = s.position;
+ r.radius = s.radius * float(i) / float(k);
+ } else {
+ const float a = 0.5f * kPi * float(i) / float(k); // from the pole
+ r.center = s.position + out * (s.radius * std::cos(a));
+ r.radius = s.radius * std::sin(a);
+ }
+ r.sides = sidesFor(r.radius, 3);
+ part.push_back(r);
+ }
+ if (start) rings.insert(rings.end(), part.begin(), part.end());
+ else rings.insert(rings.end(), part.rbegin(), part.rend());
+ };
+ cap(line.front(), normals.front(), true);
+ for (size_t i = 0; i < line.size(); ++i) {
+ const TubeSample& s = line[i];
+ rings.push_back({s.position, normals[i], glm::cross(s.tangent, normals[i]), s.radius, sidesFor(s.radius, 6),
+ groupOffset + (i + 1 < line.size() ? kTubeBodyGroup : kTubeEndCapGroup)});
+ }
+ cap(line.back(), normals.back(), false);
+
+ uint32_t prev = addRing(rings[0]);
+ for (size_t i = 1; i < rings.size(); ++i) {
+ const uint32_t cur = addRing(rings[i]);
+ stitch(prev, rings[i - 1].sides, cur, rings[i].sides, rings[i - 1].group);
+ prev = cur;
+ }
+ }
+
+ Mesh finish() {
+ m.facegroups = std::move(groups);
+ // pairQuad grows the pairs only up to the last quad; a shorter array would be dropped as stale.
+ if (!m.quadPartners.empty()) m.quadPartners.resize(m.triangles.size(), Mesh::kNoQuad);
+ m.rebuildTopology();
+ m.recomputeAllNormals();
+ return std::move(m);
+ }
+};
+
+// The average edge length of a mesh, from up to ~3000 of its edges.
+float averageEdge(const Mesh& m) {
+ const size_t nt = m.triangleCount();
+ if (nt == 0) return 0.0f;
+ const size_t step = std::max<size_t>(1, nt / 1000);
+ double sum = 0.0;
+ size_t n = 0;
+ for (size_t t = 0; t < nt; t += step)
+ for (int k = 0; k < 3; ++k) {
+ sum += glm::distance(m.positions[m.triangles[t][k]], m.positions[m.triangles[t][(k + 1) % 3]]);
+ ++n;
+ }
+ return float(sum / double(n));
+}
+
+float averageRadius(const TubeShape& s) {
+ double r = 0.0;
+ for (const TubePoint& p : s.points) r += p.radius;
+ return s.points.empty() ? 0.0f : float(r / double(s.points.size()));
+}
+
+std::string num(double v) {
+ char b[32];
+ std::snprintf(b, sizeof b, "%.4g", v);
+ return b;
+}
+
+} // namespace
+
+std::string tubeValidate(const TubeShape& s) {
+ if (s.points.empty()) return "a tube needs at least one point";
+ if (s.points.size() > kTubeMaxPoints) return "at most " + std::to_string(kTubeMaxPoints) + " points";
+ for (const TubePoint& p : s.points) {
+ if (!finite(p.position)) return "point positions must be finite";
+ if (!(p.radius > 0.0f) || !std::isfinite(p.radius)) return "radii must be above 0";
+ }
+ if (!(s.edge >= 0.0f) || !std::isfinite(s.edge)) return "edge length must be 0 (automatic) or more";
+ return {};
+}
+
+float tubeEdgeLength(const TubeShape& s) {
+ if (s.edge > 0.0f) return s.edge;
+ return std::max(2.0f * kPi * averageRadius(s) / 16.0f, 1e-6f);
+}
+
+std::vector<TubePoint> tubeFromStroke(const std::vector<TubePoint>& samples, float smoothing, size_t maxPoints) {
+ std::vector<TubePoint> pts;
+ float rmax = 0.0f; // a dab is a ball as big as the firmest touch, even one dropped as too close below
+ for (const TubePoint& p : samples) {
+ if (!finite(p.position) || !(p.radius > 0.0f) || !std::isfinite(p.radius)) continue;
+ rmax = std::max(rmax, p.radius);
+ if (pts.empty() || glm::distance(pts.back().position, p.position) >= 0.15f * std::min(p.radius, pts.back().radius))
+ pts.push_back(p);
+ }
+ if (pts.size() == 1) pts[0].radius = rmax;
+ if (pts.size() < 2) return pts;
+ if (glm::distance(samples.back().position, pts.back().position) > 0.0f && finite(samples.back().position) &&
+ samples.back().radius > 0.0f)
+ pts.back() = samples.back(); // end where the pen lifted
+ // Relax (Laplacian, the ends fixed).
+ const int passes = int(std::lround(std::clamp(smoothing, 0.0f, 1.0f) * 24.0f));
+ std::vector<TubePoint> tmp = pts;
+ for (int k = 0; k < passes; ++k) {
+ for (size_t i = 1; i + 1 < pts.size(); ++i) {
+ tmp[i].position = 0.5f * pts[i].position + 0.25f * (pts[i - 1].position + pts[i + 1].position);
+ tmp[i].radius = 0.5f * pts[i].radius + 0.25f * (pts[i - 1].radius + pts[i + 1].radius);
+ }
+ std::swap(tmp, pts);
+ }
+ // Resample along the length: about 1.25 radii apart, at most maxPoints.
+ std::vector<float> along(pts.size(), 0.0f);
+ double rsum = 0.0;
+ for (size_t i = 1; i < pts.size(); ++i) along[i] = along[i - 1] + glm::distance(pts[i - 1].position, pts[i].position);
+ for (const TubePoint& p : pts) rsum += p.radius;
+ const float length = along.back(), rmean = float(rsum / double(pts.size()));
+ if (length < rmean) { // a dab: one ball
+ TubePoint p = pts[pts.size() / 2];
+ p.radius = rmax;
+ return {p};
+ }
+ maxPoints = std::max<size_t>(maxPoints, 2);
+ const float spacing = std::max(1.25f * rmean, length / float(maxPoints - 1));
+ const size_t count = std::clamp<size_t>(size_t(std::ceil(length / spacing)) + 1, 2, maxPoints);
+ std::vector<TubePoint> out;
+ out.reserve(count);
+ size_t seg = 0;
+ for (size_t k = 0; k < count; ++k) {
+ const float s = length * float(k) / float(count - 1);
+ while (seg + 2 < pts.size() && along[seg + 1] < s) ++seg;
+ const float d = along[seg + 1] - along[seg];
+ const float f = d > 0.0f ? std::clamp((s - along[seg]) / d, 0.0f, 1.0f) : 0.0f;
+ out.push_back({glm::mix(pts[seg].position, pts[seg + 1].position, f), glm::mix(pts[seg].radius, pts[seg + 1].radius, f)});
+ }
+ return out;
+}
+
+std::vector<TubeSample> tubeCenterline(const TubeShape& shape, float edge) {
+ const std::vector<TubePoint> p = distinctPoints(shape.points);
+ if (p.empty()) return {};
+ if (p.size() == 1) return {{p[0].position, p[0].radius, vec3(0, 0, 1)}};
+ edge = std::max(edge, 1e-6f);
+ double length = 0.0;
+ for (size_t i = 1; i < p.size(); ++i) length += glm::distance(p[i - 1].position, p[i].position);
+ if (length / edge > double(kMaxRings)) edge = float(length / double(kMaxRings));
+
+ // Dense samples along each span (centripetal knots; phantom ends mirror the neighbours).
+ const size_t n = p.size();
+ auto P = [&](long i) -> TubePoint {
+ if (i < 0) return {2.0f * p[0].position - p[1].position, p[0].radius};
+ if (i >= long(n)) return {2.0f * p[n - 1].position - p[n - 2].position, p[n - 1].radius};
+ return p[size_t(i)];
+ };
+ std::vector<vec3> dp;
+ std::vector<float> dr;
+ for (size_t i = 0; i + 1 < n; ++i) {
+ const TubePoint a = P(long(i) - 1), b = P(long(i)), c = P(long(i) + 1), d = P(long(i) + 2);
+ const float t0 = 0.0f;
+ const float t1 = t0 + std::max(std::sqrt(glm::distance(a.position, b.position)), 1e-6f);
+ const float t2 = t1 + std::max(std::sqrt(glm::distance(b.position, c.position)), 1e-6f);
+ const float t3 = t2 + std::max(std::sqrt(glm::distance(c.position, d.position)), 1e-6f);
+ const float chord = glm::distance(b.position, c.position);
+ const int m = std::clamp(int(std::ceil(chord / (0.25f * edge))), 2, 512);
+ const float lo = std::min(b.radius, c.radius), hi = std::max(b.radius, c.radius);
+ for (int k = 0; k < m; ++k) {
+ const float t = t1 + (t2 - t1) * float(k) / float(m);
+ dp.push_back(catmullRom(a.position, b.position, c.position, d.position, t0, t1, t2, t3, t));
+ dr.push_back(std::clamp(catmullRom(a.radius, b.radius, c.radius, d.radius, t0, t1, t2, t3, t), lo, hi));
+ }
+ }
+ dp.push_back(p.back().position);
+ dr.push_back(p.back().radius);
+
+ std::vector<vec3> dt(dp.size());
+ for (size_t i = 0; i < dp.size(); ++i) {
+ const vec3 d = dp[std::min(i + 1, dp.size() - 1)] - dp[i > 0 ? i - 1 : 0];
+ dt[i] = glm::length(d) > 1e-12f ? glm::normalize(d) : (i > 0 ? dt[i - 1] : vec3(0, 0, 1));
+ }
+ // Rings: an edge length apart, closer where the curve turns.
+ std::vector<TubeSample> out{{dp[0], dr[0], dt[0]}};
+ float acc = 0.0f;
+ vec3 last = dt[0];
+ const float cosTurn = std::cos(kTurnPerRing);
+ for (size_t i = 1; i + 1 < dp.size(); ++i) {
+ acc += glm::distance(dp[i - 1], dp[i]);
+ if (acc >= edge || glm::dot(dt[i], last) < cosTurn) {
+ out.push_back({dp[i], dr[i], dt[i]});
+ acc = 0.0f;
+ last = dt[i];
+ }
+ }
+ acc += glm::distance(dp[dp.size() - 2], dp.back());
+ if (out.size() > 1 && acc < 0.3f * edge) out.back() = {dp.back(), dr.back(), dt.back()};
+ else out.push_back({dp.back(), dr.back(), dt.back()});
+ return out;
+}
+
+std::vector<vec3> tubeFrames(const std::vector<TubeSample>& line) {
+ // Rotation-minimizing frames by double reflection (Wang, Juttler, Zheng and Liu 2008).
+ std::vector<vec3> normals(line.size());
+ if (line.empty()) return normals;
+ normals[0] = perpendicular(line[0].tangent);
+ for (size_t i = 0; i + 1 < line.size(); ++i) {
+ const vec3 v1 = line[i + 1].position - line[i].position;
+ const float c1 = glm::dot(v1, v1);
+ vec3 r = normals[i];
+ if (c1 > 1e-20f) {
+ const vec3 rl = r - (2.0f / c1) * glm::dot(v1, r) * v1;
+ const vec3 tl = line[i].tangent - (2.0f / c1) * glm::dot(v1, line[i].tangent) * v1;
+ const vec3 v2 = line[i + 1].tangent - tl;
+ const float c2 = glm::dot(v2, v2);
+ r = c2 > 1e-20f ? rl - (2.0f / c2) * glm::dot(v2, rl) * v2 : rl;
+ }
+ const vec3 t = line[i + 1].tangent;
+ r -= t * glm::dot(r, t);
+ normals[i + 1] = glm::length(r) > 1e-12f ? glm::normalize(r) : perpendicular(t);
+ }
+ return normals;
+}
+
+TubeShape tubeMirrored(const TubeShape& shape) {
+ TubeShape m = shape;
+ for (TubePoint& p : m.points) p.position.x = -p.position.x;
+ return m;
+}
+
+Mesh tubeSweep(const TubeShape& shape, bool uniform, float edge) {
+ if (!tubeValidate(shape).empty()) return {};
+ if (!(edge > 0.0f)) edge = tubeEdgeLength(shape);
+ Builder b;
+ b.sweep(shape, uniform, edge, 0);
+ if (shape.mirrorX) {
+ float xmax = 0.0f, rmax = 0.0f;
+ for (const TubePoint& p : shape.points) {
+ xmax = std::max(xmax, std::abs(p.position.x));
+ rmax = std::max(rmax, p.radius);
+ }
+ if (xmax > 1e-4f * rmax) b.sweep(tubeMirrored(shape), uniform, edge, kTubeEndCapGroup); // not on the plane
+ }
+ return b.finish();
+}
+
+Mesh tubeMesh(const TubeShape& shape, size_t maxTriangles) {
+ float edge = tubeEdgeLength(shape);
+ if (maxTriangles > 0 && !shape.points.empty()) { // estimate: 2 triangles per side per ring
+ float length = 0.0f, rmax = 0.0f;
+ for (size_t i = 0; i < shape.points.size(); ++i) {
+ rmax = std::max(rmax, shape.points[i].radius);
+ if (i) length += glm::distance(shape.points[i - 1].position, shape.points[i].position);
+ }
+ const double sides = std::clamp(2.0 * kPi * rmax / edge, 6.0, double(kMaxSides));
+ const double est = 2.0 * sides * (length / edge + 2.0 * kPi * rmax / edge) * (shape.mirrorX ? 2.0 : 1.0);
+ if (est > double(maxTriangles)) edge *= float(std::sqrt(est / double(maxTriangles)));
+ }
+ Mesh m = tubeSweep(shape, false, edge);
+ if (m.triangleCount() > 0) m.tube = shape;
+ return m;
+}
+
+CommandResult tubeAdd(Document& doc, const TubeShape& shape, bool merge, const std::string& name, int* edited) {
+ if (const std::string err = tubeValidate(shape); !err.empty()) return {false, "Tube: " + err};
+ if (merge && (doc.mesh.multires || doc.mesh.micro))
+ return {false, "Tube: the active Part has subdivision levels or a micro level; draw the tube as a new Part"};
+ if (merge && doc.mesh.triangleCount() > 0) {
+ const float r = averageRadius(shape);
+ const float own = averageEdge(doc.mesh);
+ const float edge = shape.edge > 0.0f ? shape.edge
+ : std::clamp(own > 0.0f ? own : tubeEdgeLength(shape), 2.0f * kPi * r / 48.0f,
+ 2.0f * kPi * r / 8.0f);
+ const Mesh tube = tubeSweep(shape, true, edge);
+ if (tube.triangleCount() == 0) return {false, "Tube: nothing to sweep"};
+ const bool wasTube = !doc.mesh.tube.empty();
+ Mesh merged = mergeMeshes({&doc.mesh, &tube});
+ merged.tube = {};
+ const size_t added = tube.triangleCount();
+ doc.replaceMeshUndoable(std::move(merged), "Tube");
+ if (edited) *edited = doc.activePart;
+ return {true, "Tube merged into \"" + doc.activePartInfo().name + "\": " + std::to_string(added) + " triangles" +
+ (wasTube ? " (that Part's own tube is baked now)" : "")};
+ }
+ Mesh m = tubeMesh(shape);
+ if (m.triangleCount() == 0) return {false, "Tube: nothing to sweep"};
+ const size_t faces = m.triangleCount() - m.quadCount();
+ const std::string partName = doc.uniquePartName(name.empty() ? "Tube" : name);
+ const int at = doc.addPart(std::move(m), partName, false, doc.activePart + 1);
+ UndoRecord r; // undo takes the new Part out again
+ r.label = "Tube";
+ r.part = std::make_shared<PartStep>();
+ r.part->id = doc.parts[size_t(at)].id;
+ r.part->at = at;
+ doc.undo.push(std::move(r));
+ doc.modified = true;
+ if (edited) *edited = at;
+ return {true, "Added Tube Part \"" + partName + "\": " + std::to_string(shape.points.size()) + " points, " +
+ std::to_string(faces) + " faces"};
+}
+
+bool tubeMatchesMesh(const Mesh& mesh) {
+ if (mesh.tube.empty()) return false;
+ const Mesh s = tubeSweep(mesh.tube);
+ const size_t n = s.vertexCount();
+ if (n != mesh.vertexCount() || s.triangleCount() != mesh.triangleCount() || n == 0) return false;
+ float scale = 0.0f;
+ for (const TubePoint& p : mesh.tube.points) scale = std::max(scale, p.radius);
+ const float eps = 1e-4f * scale;
+ const size_t step = std::max<size_t>(1, n / 64);
+ for (size_t v = 0; v < n; v += step)
+ if (glm::distance(s.positions[v], mesh.positions[v]) > eps) return false;
+ return glm::distance(s.positions[n - 1], mesh.positions[n - 1]) <= eps;
+}
+
+CommandResult tubeEdit(Document& doc, TubeShape shape, const std::string& label) {
+ if (doc.mesh.tube.empty()) return {false, "The active Part is not a Tube Part (tube_new makes one)"};
+ if (!tubeMatchesMesh(doc.mesh))
+ return {false, "Tube: this Part was moved or changed since the tube was drawn, so its points no longer fit; "
+ "Bake keeps it as it is (or undo the change to edit the points)"};
+ if (const std::string err = tubeValidate(shape); !err.empty()) return {false, "Tube: " + err};
+ doc.replaceMeshUndoable(tubeMesh(shape), label);
+ return {true, label + "; " + std::to_string(shape.points.size()) + " points"};
+}
+
+Json tubeToJson(const TubeShape& s) {
+ Json pts = Json::array();
+ for (const TubePoint& p : s.points) {
+ for (int k = 0; k < 3; ++k) pts.push(double(p.position[k]));
+ pts.push(double(p.radius));
+ }
+ Json out = Json::object();
+ out.set("points", std::move(pts));
+ if (s.flatCaps) out.set("flat_caps", true);
+ if (s.mirrorX) out.set("mirror_x", true);
+ if (s.edge > 0.0f) out.set("edge", double(s.edge));
+ return out;
+}
+
+TubeShape tubeFromJson(const Json& json) {
+ TubeShape s;
+ const Json& pts = json["points"];
+ if (!pts.isArray() || pts.size() % 4 != 0) return {};
+ for (size_t i = 0; i < pts.size(); i += 4)
+ s.points.push_back({vec3(float(pts[i].asNumber(NAN)), float(pts[i + 1].asNumber(NAN)), float(pts[i + 2].asNumber(NAN))),
+ float(pts[i + 3].asNumber(NAN))});
+ s.flatCaps = json["flat_caps"].asBool(false);
+ s.mirrorX = json["mirror_x"].asBool(false);
+ s.edge = float(json["edge"].asNumber(0.0));
+ if (!tubeValidate(s).empty()) return {};
+ return s;
+}
+
+bool parseTubePoints(const std::string& text, float radius, std::vector<TubePoint>& out, std::string& error) {
+ out.clear();
+ std::string t = text;
+ for (char& c : t)
+ if (c == ';' || c == '|') c = ' ';
+ std::istringstream in(t);
+ std::string tok;
+ while (in >> tok) {
+ std::vector<float> v;
+ size_t start = 0;
+ while (true) {
+ const size_t end = tok.find(',', start);
+ const std::string part = tok.substr(start, end == std::string::npos ? std::string::npos : end - start);
+ char* stop = nullptr;
+ const float x = std::strtof(part.c_str(), &stop);
+ if (part.empty() || stop != part.c_str() + part.size()) v.clear(), v.resize(9);
+ else v.push_back(x);
+ if (end == std::string::npos || v.size() > 4) break;
+ start = end + 1;
+ }
+ if (v.size() < 3 || v.size() > 4) {
+ error = "bad point \"" + tok + "\": use x,y,z or x,y,z,radius";
+ return false;
+ }
+ out.push_back({vec3(v[0], v[1], v[2]), v.size() == 4 ? v[3] : radius});
+ }
+ if (out.empty()) {
+ error = "no points";
+ return false;
+ }
+ return true;
+}
+
+namespace {
+
+constexpr const char* kNotTube = "The active Part is not a Tube Part (tube_new makes one; a baked tube is a plain mesh)";
+
+bool validPoint(const TubeShape& s, int i) { return i >= 0 && size_t(i) < s.points.size(); }
+
+void applyOptions(TubeShape& s, const Args& a) {
+ if (a.contains("caps")) s.flatCaps = argString(a, "caps") == "flat";
+ if (a.contains("symmetry")) {
+ const std::string sym = argString(a, "symmetry");
+ s.mirrorX = sym.find('x') != std::string::npos || sym.find('X') != std::string::npos;
+ }
+ if (a.contains("edge")) s.edge = float(argNumber(a, "edge", 0.0));
+}
+
+} // namespace
+
+void registerTubeCommands(CommandRegistry& reg) {
+ using T = ParamSpec::Type;
+ const ParamSpec capsParam{"caps", T::String, "Ends: \"round\" (default) or \"flat\".", false};
+ const ParamSpec symParam{"symmetry", T::String, "\"x\" adds a mirror copy across x = 0; \"none\" removes it.", false};
+ const ParamSpec edgeParam{"edge", T::Number, "Target edge length (0 = automatic, from the radius).", false};
+ reg.add({"tube_new",
+ "Tube: sweep a clay tube along a smooth curve through 3D points (like drawing with a 3D pen). By default "
+ "a new Tube Part whose points stay editable (tube_set_point, tube_insert_point, tube_delete_point) "
+ "until tube_bake; with merge=true it goes into the active Part with even edge lengths (good for dynamic "
+ "topology). One undo step either way.",
+ {{"points", T::String, "Points \"x,y,z[,radius] x,y,z[,radius] ...\" (spaces, ';' or '|' between them).", true},
+ {"radius", T::Number, "Radius for points given without one (default 0.05).", false},
+ {"smooth", T::Number,
+ "0 (default): the points are the curve's control points. Above 0 (to 1): they are raw stroke samples, "
+ "smoothed by this much and simplified to at most 500 control points.",
+ false},
+ capsParam, symParam, edgeParam,
+ {"merge", T::Bool, "Merge into the active Part instead of adding a Tube Part (default false).", false},
+ {"name", T::String, "Part name (default \"Tube\").", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ const float radius = float(argNumber(a, "radius", 0.05));
+ TubeShape s;
+ std::string err;
+ if (!parseTubePoints(argString(a, "points"), radius, s.points, err)) return {false, "Tube: " + err};
+ if (const float sm = float(argNumber(a, "smooth", 0.0)); sm > 0.0f) {
+ if (const std::string e = tubeValidate(s); !e.empty()) return {false, "Tube: " + e};
+ s.points = tubeFromStroke(s.points, sm);
+ }
+ applyOptions(s, a);
+ return tubeAdd(doc, s, argBool(a, "merge", false), argString(a, "name", "Tube"));
+ }});
+ reg.add({"tube_list", "List the active Tube Part's control points (index, position, radius) and options.", {},
+ [](Document& doc, const Args&) -> CommandResult {
+ const TubeShape& s = doc.mesh.tube;
+ if (s.empty()) return {false, kNotTube};
+ std::string out = std::to_string(s.points.size()) + " points, " + (s.flatCaps ? "flat" : "round") +
+ " caps" + (s.mirrorX ? ", mirrored in X" : "") +
+ (s.edge > 0.0f ? ", edge " + num(s.edge) : ", edge automatic");
+ for (size_t i = 0; i < s.points.size(); ++i) {
+ const TubePoint& p = s.points[i];
+ out += "\n" + std::to_string(i) + ": (" + num(p.position.x) + ", " + num(p.position.y) + ", " +
+ num(p.position.z) + ") radius " + num(p.radius);
+ }
+ return {true, out};
+ }});
+ reg.add({"tube_set_point", "Move and/or resize a control point of the active Tube Part.",
+ {{"index", T::Number, "Point index (0 = the start).", true},
+ {"position", T::String, "New position \"x,y,z\" (default: unchanged).", false},
+ {"radius", T::Number, "New radius (default: unchanged).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ TubeShape s = doc.mesh.tube;
+ if (s.empty()) return {false, kNotTube};
+ const int i = int(argNumber(a, "index", -1));
+ if (!validPoint(s, i)) return {false, "index must be from 0 to " + std::to_string(s.points.size() - 1)};
+ TubePoint& p = s.points[size_t(i)];
+ if (a.contains("position") && !parseVec3(argString(a, "position"), p.position))
+ return {false, "position must be \"x,y,z\""};
+ p.radius = float(argNumber(a, "radius", p.radius));
+ return tubeEdit(doc, std::move(s), "Tube point");
+ }});
+ reg.add({"tube_insert_point",
+ "Insert a control point on the active Tube Part halfway between point `index` and the next one.",
+ {{"index", T::Number, "The point before the new one.", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ TubeShape s = doc.mesh.tube;
+ if (s.empty()) return {false, kNotTube};
+ const int i = int(argNumber(a, "index", -1));
+ if (i < 0 || size_t(i) + 1 >= s.points.size())
+ return {false, s.points.size() < 2 ? "Tube: a one-point tube has no span to insert into"
+ : "index must be from 0 to " + std::to_string(s.points.size() - 2)};
+ const TubePoint& p = s.points[size_t(i)];
+ const TubePoint& q = s.points[size_t(i) + 1];
+ s.points.insert(s.points.begin() + i + 1, TubePoint{0.5f * (p.position + q.position), 0.5f * (p.radius + q.radius)});
+ return tubeEdit(doc, std::move(s), "Tube insert point");
+ }});
+ reg.add({"tube_delete_point", "Delete a control point of the active Tube Part (one point always stays).",
+ {{"index", T::Number, "Point index.", true}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ TubeShape s = doc.mesh.tube;
+ if (s.empty()) return {false, kNotTube};
+ const int i = int(argNumber(a, "index", -1));
+ if (!validPoint(s, i)) return {false, "index must be from 0 to " + std::to_string(s.points.size() - 1)};
+ if (s.points.size() == 1) return {false, "Tube: the last point stays (delete the Part instead)"};
+ s.points.erase(s.points.begin() + i);
+ return tubeEdit(doc, std::move(s), "Tube delete point");
+ }});
+ reg.add({"tube_set", "Change the active Tube Part's ends, mirror copy, density or thickness.",
+ {capsParam, symParam, edgeParam,
+ {"radius_scale", T::Number, "Multiply every point's radius by this (default 1).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ TubeShape s = doc.mesh.tube;
+ if (s.empty()) return {false, kNotTube};
+ applyOptions(s, a);
+ const float k = float(argNumber(a, "radius_scale", 1.0));
+ if (!(k > 0.0f) || !std::isfinite(k)) return {false, "radius_scale must be above 0"};
+ for (TubePoint& p : s.points) p.radius *= k;
+ return tubeEdit(doc, std::move(s), "Tube settings");
+ }});
+ reg.add({"tube_bake",
+ "Bake the active Tube Part into a plain, sculptable mesh (its points are no longer editable). "
+ "uniform=true re-sweeps it with even edge lengths (triangles) for dynamic topology; else it keeps its quads.",
+ {{"uniform", T::Bool, "Even edge lengths (default false).", false}},
+ [](Document& doc, const Args& a) -> CommandResult {
+ if (doc.mesh.tube.empty()) return {false, kNotTube};
+ Mesh m = argBool(a, "uniform", false) ? tubeSweep(doc.mesh.tube, true) : doc.mesh;
+ m.tube = {};
+ const size_t tris = m.triangleCount();
+ doc.replaceMeshUndoable(std::move(m), "Tube bake");
+ return {true, "Baked the tube: " + std::to_string(tris) + " triangles, ready to sculpt"};
+ }});
+}
+
+} // namespace sf
diff --git a/src/core/Tube.h b/src/core/Tube.h
new file mode 100644
index 00000000..7d238b8e
--- /dev/null
+++ b/src/core/Tube.h
@@ -0,0 +1,89 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Tube: draw clay tubes freely in 3D space, like a 3D pen. A stroke becomes a smooth curve (centripetal
+// Catmull-Rom through control points, each with its own radius) and a tube is swept along it: rings placed
+// adaptively (closer where the curve bends), oriented by rotation-minimizing frames (double reflection), so the
+// tube never twists. The ends are round or flat. A Tube Part keeps its curve in Mesh::tube and its triangles are
+// made from it, so the points can be moved and resized until Bake makes it a plain, sculptable mesh. Merged into
+// the active Part instead, the tube is swept with even edge lengths (rings with as many sides as their size
+// needs), which suits dynamic topology. Every change is one undo step.
+#pragma once
+
+#include "core/Json.h"
+#include "core/Mesh.h"
+
+#include <string>
+#include <vector>
+
+namespace sf {
+
+class CommandRegistry;
+struct Document;
+struct CommandResult;
+
+constexpr size_t kTubeMaxPoints = 2000; // control points per tube
+constexpr size_t kTubeStrokePoints = 500; // a drawn stroke is simplified to at most this many
+constexpr uint32_t kTubeBodyGroup = 1; // face groups: the body, the start cap, the end cap
+constexpr uint32_t kTubeStartCapGroup = 2; // (the mirror copy adds 3)
+constexpr uint32_t kTubeEndCapGroup = 3;
+
+// Empty when `shape` can be swept: 1 to kTubeMaxPoints points, finite, radii above 0, edge >= 0.
+std::string tubeValidate(const TubeShape& shape);
+
+// The edge length a tube is swept with: shape.edge, or 2*pi times the average radius over 16.
+float tubeEdgeLength(const TubeShape& shape);
+
+// A drawn stroke (dense pen samples with pressure-scaled radii) as control points: samples closer than a fraction
+// of their radius are dropped, `smoothing` (0..1) relaxes positions and radii (the ends stay), and the result is
+// resampled along its length to at most `maxPoints`. A stroke shorter than its radius becomes one point (a ball).
+std::vector<TubePoint> tubeFromStroke(const std::vector<TubePoint>& samples, float smoothing,
+ size_t maxPoints = kTubeStrokePoints);
+
+// A point of the swept centre line: position, radius and unit tangent.
+struct TubeSample {
+ glm::vec3 position{0.0f};
+ float radius = 0.0f;
+ glm::vec3 tangent{0.0f, 0.0f, 1.0f};
+};
+// The centre line rings are placed on: at most `edge` apart along it and closer where it turns (about 10 degrees
+// between rings), from the first point to the last.
+std::vector<TubeSample> tubeCenterline(const TubeShape& shape, float edge);
+
+// The ring orientation along `line`: a unit normal per sample, at right angles to its tangent, carried along without
+// twisting (rotation-minimizing frames).
+std::vector<glm::vec3> tubeFrames(const std::vector<TubeSample>& line);
+
+// The tube as a plain mesh (no Mesh::tube): watertight, face groups as above. `uniform`: every edge near the edge
+// length (triangles; rings get as many sides as their radius needs) for dynamic topology; else rings with the
+// same number of sides, in quads. `edge` <= 0: tubeEdgeLength(shape). Empty when the shape is invalid.
+Mesh tubeSweep(const TubeShape& shape, bool uniform = false, float edge = 0.0f);
+// The mesh a Tube Part shows: tubeSweep in quads, carrying `shape` in Mesh::tube. `maxTriangles` > 0: a coarser
+// sweep when the full one would have more (the live preview while a point is dragged: 60 fps on the floor tier).
+Mesh tubeMesh(const TubeShape& shape, size_t maxTriangles = 0);
+constexpr size_t kTubePreviewTriangles = 60000;
+// The shape mirrored across x = 0 (the mirror copy symmetry X sweeps).
+TubeShape tubeMirrored(const TubeShape& shape);
+
+// Adds a tube to the scene as one undo step: a new Tube Part (not made active; undo removes it), or with `merge`
+// swept with even edges (near the active Part's own edge length) into the active Part. `edited` is the Part that
+// holds it now.
+CommandResult tubeAdd(Document& doc, const TubeShape& shape, bool merge, const std::string& name = "Tube",
+ int* edited = nullptr);
+// True when `mesh` is still the tube its Mesh::tube sweeps (not moved, sculpted or otherwise changed since): a
+// tube is only re-swept from its points then, so nothing done to it afterwards is lost silently.
+bool tubeMatchesMesh(const Mesh& mesh);
+// Replaces the active Tube Part's curve (one undo step labelled `label`).
+CommandResult tubeEdit(Document& doc, TubeShape shape, const std::string& label);
+
+// "x,y,z,radius" per point, a flat array, plus the options; FromJson gives an empty shape for a bad one.
+Json tubeToJson(const TubeShape& shape);
+TubeShape tubeFromJson(const Json& json);
+// Parses "x,y,z[,radius] x,y,z[,radius] ..." (points separated by spaces, ';' or '|'); points without a radius get
+// `radius`.
+bool parseTubePoints(const std::string& text, float radius, std::vector<TubePoint>& out, std::string& error);
+
+// tube_new, tube_list, tube_set_point, tube_insert_point, tube_delete_point, tube_set, tube_bake.
+void registerTubeCommands(CommandRegistry& registry);
+
+} // namespace sf
diff --git a/tests/test_tube.cpp b/tests/test_tube.cpp
new file mode 100644
index 00000000..39e11852
--- /dev/null
+++ b/tests/test_tube.cpp
@@ -0,0 +1,326 @@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+//
+// Tube (src/core/Tube.cpp): the curve, the sweep (watertight, no twist, adaptive rings, caps, even edges), strokes
+// into control points, the tube_* commands with undo, merging, and projects.
+#include "TestHarness.h"
+
+#include "core/Commands.h"
+#include "core/MeshTransform.h"
+#include "core/Primitives.h"
+#include "core/Project.h"
+#include "core/Tube.h"
+
+#include <chrono>
+#include <cmath>
+#include <cstdio>
+#include <map>
+
+using namespace sf;
+using glm::vec3;
+
+namespace {
+
+bool watertight(const Mesh& m) {
+ std::map<std::pair<uint32_t, uint32_t>, int> edges;
+ for (const glm::uvec3& t : m.triangles) {
+ if (t.x == t.y || t.y == t.z || t.x == t.z) return false;
+ for (int k = 0; k < 3; ++k) ++edges[{std::min(t[k], t[(k + 1) % 3]), std::max(t[k], t[(k + 1) % 3])}];
+ }
+ for (const auto& [e, n] : edges)
+ if (n != 2) return false;
+ return !edges.empty();
+}
+
+// Every edge used once in each direction: the triangles agree on which side is out.
+bool oriented(const Mesh& m) {
+ std::map<std::pair<uint32_t, uint32_t>, int> half;
+ for (const glm::uvec3& t : m.triangles)
+ for (int k = 0; k < 3; ++k)
+ if (++half[{t[k], t[(k + 1) % 3]}] > 1) return false;
+ return true;
+}
+
+double signedVolume(const Mesh& m) {
+ double v = 0.0;
+ for (const glm::uvec3& t : m.triangles)
+ v += glm::dot(m.positions[t.x], glm::cross(m.positions[t.y], m.positions[t.z])) / 6.0;
+ return v;
+}
+
+// Swept fine (48 sides) so the volume checks measure the shape, not the polygon's few percent.
+TubeShape line(float length, float radius) {
+ TubeShape s;
+ s.points = {{vec3(0, 0, 0), radius}, {vec3(length * 0.5f, 0, 0), radius}, {vec3(length, 0, 0), radius}};
+ s.edge = 2.0f * 3.14159265f * radius / 48.0f;
+ return s;
+}
+
+// An S in the XY plane, then up out of it.
+TubeShape curvy() {
+ TubeShape s;
+ for (int i = 0; i <= 24; ++i) {
+ const float a = float(i) / 24.0f * 6.0f;
+ s.points.push_back({vec3(a, std::sin(a) * 1.5f, i > 18 ? float(i - 18) * 0.4f : 0.0f), 0.2f + 0.01f * float(i)});
+ }
+ return s;
+}
+
+} // namespace
+
+TEST(tube_sweep_closed_and_outward) {
+ const float pi = 3.14159265f;
+ // A straight tube with round ends is a capsule: volume pi r^2 L + 4/3 pi r^3, facing out.
+ const Mesh m = tubeSweep(line(2.0f, 0.25f));
+ CHECK(watertight(m) && oriented(m));
+ CHECK(m.hasQuads() && m.facegroups.size() == m.triangleCount());
+ const double want = pi * 0.0625 * 2.0 + 4.0 / 3.0 * pi * 0.015625;
+ CHECK(signedVolume(m) > 0.0 && std::abs(signedVolume(m) / want - 1.0) < 0.03);
+ // Flat ends: a cylinder, a little less.
+ TubeShape flat = line(2.0f, 0.25f);
+ flat.flatCaps = true;
+ const Mesh f = tubeSweep(flat);
+ CHECK(watertight(f) && oriented(f));
+ CHECK(std::abs(signedVolume(f) / (pi * 0.0625 * 2.0) - 1.0) < 0.03);
+ // A curvy tube with varying radius, both ways; a single point is a ball.
+ for (bool uniform : {false, true}) {
+ const Mesh c = tubeSweep(curvy(), uniform);
+ CHECK(watertight(c) && oriented(c) && signedVolume(c) > 0.0);
+ }
+ TubeShape ball;
+ ball.points = {{vec3(1, 2, 3), 0.5f}};
+ ball.edge = 2.0f * 3.14159265f * 0.5f / 48.0f;
+ const Mesh b = tubeSweep(ball);
+ CHECK(watertight(b) && oriented(b));
+ CHECK(std::abs(signedVolume(b) / (4.0 / 3.0 * pi * 0.125) - 1.0) < 0.05);
+ // Invalid shapes sweep to nothing.
+ TubeShape bad = line(1.0f, 0.1f);
+ bad.points[1].radius = 0.0f;
+ CHECK(!tubeValidate(bad).empty() && tubeSweep(bad).triangleCount() == 0);
+ CHECK(!tubeValidate(TubeShape{}).empty());
+}
+
+TEST(tube_frames_do_not_twist) {
+ // A planar curve: the carried normal keeps the same angle to the plane all along (no twist).
+ TubeShape s = curvy();
+ s.points.resize(19); // (the planar part)
+ const auto c = tubeCenterline(s, tubeEdgeLength(s));
+ const auto n = tubeFrames(c);
+ CHECK(c.size() > 20 && n.size() == c.size());
+ for (size_t i = 0; i < c.size(); ++i) {
+ CHECK(std::abs(glm::dot(n[i], c[i].tangent)) < 1e-4f);
+ CHECK(std::abs(std::abs(n[i].z) - std::abs(n[0].z)) < 1e-3f);
+ }
+ // A helix: neighbouring frames turn only as much as the tangent does.
+ TubeShape h;
+ for (int i = 0; i <= 80; ++i) {
+ const float a = float(i) * 0.25f;
+ h.points.push_back({vec3(std::cos(a), std::sin(a), a * 0.2f), 0.1f});
+ }
+ const auto hc = tubeCenterline(h, tubeEdgeLength(h));
+ const auto hn = tubeFrames(hc);
+ for (size_t i = 1; i < hc.size(); ++i) {
+ const float turnT = std::acos(std::clamp(glm::dot(hc[i].tangent, hc[i - 1].tangent), -1.0f, 1.0f));
+ const float turnN = std::acos(std::clamp(glm::dot(hn[i], hn[i - 1]), -1.0f, 1.0f));
+ CHECK(turnN <= turnT + 1e-3f);
+ }
+}
+
+TEST(tube_rings_adapt_to_bends) {
+ // Straight, then a tight hairpin: the hairpin gets rings closer together than the edge length.
+ TubeShape s;
+ s.points = {{vec3(-4, 0, 0), 0.1f}, {vec3(0, 0, 0), 0.1f}, {vec3(0.3f, 0.3f, 0), 0.1f}, {vec3(0, 0.6f, 0), 0.1f},
+ {vec3(-4, 0.6f, 0), 0.1f}};
+ s.edge = 0.2f; // 10 degrees of the hairpin is well under an edge
+ const float edge = tubeEdgeLength(s);
+ const auto c = tubeCenterline(s, edge);
+ float straightGap = 0.0f, bendGap = 1e9f;
+ for (size_t i = 1; i < c.size(); ++i) {
+ const float gap = glm::distance(c[i].position, c[i - 1].position);
+ CHECK(gap <= edge * 1.31f);
+ if (c[i].position.x < -2.0f && c[i - 1].position.x < -2.0f && c[i].position.y < 0.1f) straightGap = std::max(straightGap, gap);
+ if (c[i].position.x > 0.15f) bendGap = std::min(bendGap, gap);
+ }
+ CHECK(straightGap > 0.9f * edge && bendGap < 0.7f * edge);
+ CHECK(glm::distance(c.front().position, s.points.front().position) < 1e-5f);
+ CHECK(glm::distance(c.back().position, s.points.back().position) < 1e-5f);
+}
+
+TEST(tube_uniform_edges) {
+ // Even edges whatever the radius: a thick end and a thin end get as many sides as they need.
+ TubeShape s;
+ s.points = {{vec3(0, 0, 0), 0.5f}, {vec3(1.5f, 0.3f, 0), 0.25f}, {vec3(3, 0, 0), 0.08f}};
+ const float edge = 0.06f;
+ const Mesh m = tubeSweep(s, true, edge);
+ CHECK(watertight(m) && oriented(m) && !m.hasQuads());
+ size_t n = 0, good = 0;
+ for (const glm::uvec3& t : m.triangles)
+ for (int k = 0; k < 3; ++k) {
+ const float l = glm::distance(m.positions[t[k]], m.positions[t[(k + 1) % 3]]);
+ ++n;
+ good += l > 0.4f * edge && l < 1.9f * edge;
+ }
+ CHECK(double(good) / double(n) > 0.95);
+}
+
+TEST(tube_mirror_copy) {
+ TubeShape s = line(1.0f, 0.1f);
+ for (TubePoint& p : s.points) p.position.x += 0.5f;
+ s.mirrorX = true;
+ const Mesh m = tubeSweep(s);
+ CHECK(watertight(m) && m.triangleCount() == 2 * tubeSweep(line(1.0f, 0.1f)).triangleCount());
+ float xmin = 1e9f;
+ for (const vec3& p : m.positions) xmin = std::min(xmin, p.x);
+ CHECK(xmin < -1.5f);
+ CHECK(signedVolume(m) > 0.0); // the copy faces out too
+ // On the plane itself there is nothing to mirror.
+ TubeShape onPlane;
+ onPlane.points = {{vec3(0, 0, 0), 0.1f}, {vec3(0, 1, 0), 0.1f}};
+ onPlane.mirrorX = true;
+ onPlane.edge = 0.05f;
+ TubeShape plain = onPlane;
+ plain.mirrorX = false;
+ CHECK(tubeSweep(onPlane).triangleCount() == tubeSweep(plain).triangleCount());
+}
+
+TEST(tube_from_stroke) {
+ // 3000 jittery pen samples along a line with pressure from light to firm.
+ std::vector<TubePoint> raw;
+ for (int i = 0; i < 3000; ++i) {
+ const float u = float(i) / 2999.0f;
+ const float jitter = 0.01f * std::sin(float(i) * 1.7f);
+ raw.push_back({vec3(u * 10.0f, jitter, 0.0f), 0.05f + 0.1f * u});
+ }
+ const auto pts = tubeFromStroke(raw, 0.5f);
+ CHECK(pts.size() >= 2 && pts.size() <= kTubeStrokePoints);
+ CHECK(glm::distance(pts.front().position, raw.front().position) < 1e-4f);
+ CHECK(glm::distance(pts.back().position, raw.back().position) < 1e-4f);
+ CHECK(pts.front().radius < pts.back().radius);
+ float worst = 0.0f;
+ for (const TubePoint& p : pts) worst = std::max(worst, std::abs(p.position.y));
+ CHECK(worst < 0.01f); // smoothed
+ // At most maxPoints, even for a very long stroke.
+ CHECK(tubeFromStroke(raw, 0.0f, 40).size() == 40);
+ // A dab is a ball.
+ const auto dab = tubeFromStroke({{vec3(0.0f), 0.2f}, {vec3(0.01f, 0, 0), 0.25f}, {vec3(0.02f, 0, 0), 0.2f}}, 0.5f);
+ CHECK(dab.size() == 1 && std::abs(dab[0].radius - 0.25f) < 1e-6f);
+ CHECK(tubeFromStroke({}, 0.5f).empty());
+}
+
+TEST(tube_parse_points) {
+ std::vector<TubePoint> p;
+ std::string err;
+ CHECK(parseTubePoints("0,0,0 1,2,3,0.5;4,5,6|7,8,9,0.25", 0.1f, p, err) && p.size() == 4);
+ CHECK(p[0].radius == 0.1f && p[1].radius == 0.5f && p[1].position == vec3(1, 2, 3) && p[3].radius == 0.25f);
+ CHECK(!parseTubePoints("1,2", 0.1f, p, err));
+ CHECK(!parseTubePoints("1,2,3,4,5", 0.1f, p, err));
+ CHECK(!parseTubePoints("1,x,3", 0.1f, p, err));
+ CHECK(!parseTubePoints(" ", 0.1f, p, err));
+}
+
+TEST(tube_commands_and_undo) {
+ Document doc;
+ CommandRegistry reg;
+ CHECK(!reg.execute(doc, "tube_set_point", {{"index", 0.0}, {"radius", 0.2}}).ok); // not a Tube Part
+ const int parts = doc.partCount();
+ CHECK(reg.execute(doc, "tube_new", {{"points", std::string("0,0,0 1,0,0 1,1,0")}, {"radius", 0.1}}).ok);
+ // A new Part below the active one, which stays active; undo takes it out, redo puts it back.
+ CHECK(doc.partCount() == parts + 1 && doc.activePart == 0 && doc.parts[1].name == "Tube");
+ CHECK(doc.partMesh(1).tube.points.size() == 3 && watertight(doc.partMesh(1)));
+ CHECK(reg.execute(doc, "undo").ok && doc.partCount() == parts);
+ CHECK(reg.execute(doc, "redo").ok && doc.partCount() == parts + 1 && doc.partMesh(1).tube.points.size() == 3);
+
+ doc.selectPart(1);
+ CHECK(reg.execute(doc, "tube_list").message.find("3 points, round caps") == 0);
+ CHECK(reg.execute(doc, "tube_set_point", {{"index", 2.0}, {"position", std::string("2,1,0")}, {"radius", 0.3}}).ok);
+ CHECK(doc.mesh.tube.points[2].position == vec3(2, 1, 0) && doc.mesh.tube.points[2].radius == 0.3f);
+ CHECK(reg.execute(doc, "tube_insert_point", {{"index", 0.0}}).ok && doc.mesh.tube.points.size() == 4);
+ CHECK(doc.mesh.tube.points[1].position == vec3(0.5f, 0, 0));
+ CHECK(reg.execute(doc, "tube_delete_point", {{"index", 3.0}}).ok && doc.mesh.tube.points.size() == 3);
+ CHECK(!reg.execute(doc, "tube_insert_point", {{"index", 2.0}}).ok);
+ CHECK(reg.execute(doc, "tube_set", {{"caps", std::string("flat")}, {"symmetry", std::string("x")}}).ok);
+ CHECK(doc.mesh.tube.flatCaps && doc.mesh.tube.mirrorX && watertight(doc.mesh));
+ // Each edit one undo step, the curve coming back with the mesh.
+ CHECK(doc.undo.undo(doc.mesh, doc.bvh) && !doc.mesh.tube.flatCaps);
+ CHECK(doc.undo.undo(doc.mesh, doc.bvh) && doc.mesh.tube.points.size() == 4);
+ CHECK(doc.undo.redo(doc.mesh, doc.bvh) && doc.undo.redo(doc.mesh, doc.bvh) && doc.mesh.tube.flatCaps);
+
+ // Moved with the gizmo: the points no longer fit, so editing them says so instead of undoing the move.
+ MeshTransform t;
+ t.translate = vec3(0.5f, 0, 0);
+ CHECK(transformPart(doc, doc.activePart, t, false, 0.0f, {false, false, false}, "Transform") > 0);
+ CHECK(!tubeMatchesMesh(doc.mesh));
+ CHECK(!reg.execute(doc, "tube_set_point", {{"index", 0.0}, {"radius", 0.2}}).ok);
+ CHECK(doc.undo.undo(doc.mesh, doc.bvh) && tubeMatchesMesh(doc.mesh));
+
+ // Bake: a plain mesh, same triangles; uniform re-sweeps in even triangles.
+ const size_t tris = doc.mesh.triangleCount();
+ CHECK(reg.execute(doc, "tube_bake").ok && doc.mesh.tube.empty() && doc.mesh.triangleCount() == tris);
+ CHECK(!reg.execute(doc, "tube_bake").ok);
+ CHECK(doc.undo.undo(doc.mesh, doc.bvh) && !doc.mesh.tube.empty());
+ CHECK(reg.execute(doc, "tube_bake", {{"uniform", true}}).ok && doc.mesh.tube.empty() && !doc.mesh.hasQuads());
+}
+
+TEST(tube_merge_into_active) {
+ Document doc;
+ CommandRegistry reg;
+ doc.mesh = makeQuadSphere(8);
+ const size_t before = doc.mesh.triangleCount();
+ const int parts = doc.partCount();
+ CHECK(before > 0);
+ CHECK(reg.execute(doc, "tube_new", {{"points", std::string("0.5,0,0 1.5,0.5,0 2,1.5,0.5")}, {"radius", 0.1},
+ {"merge", true}}).ok);
+ CHECK(doc.partCount() == parts && doc.mesh.triangleCount() > before && doc.mesh.tube.empty());
+ CHECK(doc.undo.undo(doc.mesh, doc.bvh) && doc.mesh.triangleCount() == before); // one step
+ // Raw samples with smoothing go through the stroke simplifier.
+ CHECK(reg.execute(doc, "tube_new", {{"points", std::string("0,0,0 0.01,0.02,0 0.02,0.01,0 0.5,0.02,0 1,0,0")},
+ {"radius", 0.05}, {"smooth", 0.5}, {"name", std::string("Vine")}}).ok);
+ CHECK(doc.parts[size_t(doc.activePart + 1)].name == "Vine");
+}
+
+TEST(tube_project_roundtrip) {
+ Document doc;
+ CommandRegistry reg;
+ CHECK(reg.execute(doc, "tube_new", {{"points", std::string("0,0,0,0.1 1,0,0,0.2 1,1,0,0.05")}, {"caps", std::string("flat")},
+ {"symmetry", std::string("x")}, {"edge", 0.04}}).ok);
+ const std::string path = tempPath("sf_tube.sfproj");
+ std::string err;
+ CHECK(saveProject(path, doc, err));
+ Document back;
+ CHECK(loadProject(path, back, err));
+ CHECK(back.partCount() == doc.partCount());
+ const Mesh& m = back.partMesh(1);
+ CHECK(m.tube.points.size() == 3 && m.tube.flatCaps && m.tube.mirrorX && std::abs(m.tube.edge - 0.04f) < 1e-6f);
+ CHECK(m.tube.points[1].radius == 0.2f && m.triangleCount() == doc.partMesh(1).triangleCount());
+ back.selectPart(1);
+ CHECK(tubeMatchesMesh(back.mesh));
+ CHECK(reg.execute(back, "tube_set_point", {{"index", 0.0}, {"radius", 0.15}}).ok);
+ std::filesystem::remove(path);
+ CHECK(tubeFromJson(Json::object()).empty());
+}
+
+TEST(tube_sweep_speed_500_points) {
+ // Floor tier: dragging a point of a 500-point curve re-sweeps it every frame (60 fps = 16.7 ms).
+ TubeShape s;
+ for (int i = 0; i < 500; ++i) {
+ const float a = float(i) * 0.05f;
+ s.points.push_back({vec3(std::cos(a) * (1.0f + 0.1f * a), std::sin(a) * (1.0f + 0.1f * a), a * 0.1f), 0.04f});
+ }
+ double best = 1e9;
+ size_t tris = 0;
+ for (int k = 0; k < 5; ++k) {
+ const auto t0 = std::chrono::steady_clock::now();
+ const Mesh m = tubeMesh(s);
+ best = std::min(best, std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count());
+ tris = m.triangleCount();
+ }
+ std::printf("tube_sweep_speed_500_points: %zu triangles in %.2f ms (best of 5)\n", tris, best);
+ CHECK(tris > 10000);
+ CHECK(best < 50.0); // (debug and sanitizer builds are slower; bench numbers in REPORT.md)
+ // The live preview stays near its triangle budget however thin the tube, and carries the curve.
+ for (TubePoint& p : s.points) p.radius = 0.01f;
+ const Mesh full = tubeMesh(s), preview = tubeMesh(s, kTubePreviewTriangles);
+ CHECK(full.triangleCount() > 2 * kTubePreviewTriangles);
+ CHECK(preview.triangleCount() < kTubePreviewTriangles * 5 / 4 && preview.triangleCount() > kTubePreviewTriangles / 3);
+ CHECK(preview.tube.points.size() == 500 && watertight(preview));
+}
diff --git a/tests/ui/tube.sfui b/tests/ui/tube.sfui
new file mode 100644
index 00000000..5982cac6
--- /dev/null
+++ b/tests/ui/tube.sfui
@@ -0,0 +1,131 @@
+# Tube (Tool > Tube, PanelTube.cpp; requested by GABO on Discord): Draw Tube draws a clay tube in the air from a drag
+# that starts on the model and leaves it, as a new Tube Part (undo takes it away); its points are dragged to move
+# them, Ctrl+dragged to resize, Alt+clicked to delete; Insert / Delete Point, flat ends and Bake; Merge puts a
+# stroke into the active Part as one undo step. The shots feed the guide's Tube chapter.
+run ui_look look=classic layout=classic # written for the Classic look and the classic palette bar and shelves
+wait 0.3
+click "Tube##tool.tube"
+expect "Tube/Draw Tube"
+hold ctrl
+hover "Tube/Draw Tube"
+expect_help "3D pen"
+hold none
+shot panel
+click "Tube/Draw Tube"
+expect_value tube_draw == 1
+expect_status "drag anywhere"
+
+# An S from the model out into the air: the trail shows while drawing, then a Tube Part; the sculpt stays active.
+drag_path 0.3 0.4 0.55 0.2 0.8 0.45 1.05 0.25 1.3 0.5 keep S=1.2
+shot drawing
+release
+wait 0.2
+expect_value tube_parts == 1
+expect_value parts == 2
+expect_value active_part == 0
+expect_status "Added Tube Part"
+shot drawn
+ui_scale 200 # 200%: the dots and the panel stay crisp and in proportion
+wait 0.3
+shot drawn-200
+ui_scale 100
+wait 0.3
+key ctrl+z
+expect_value tube_parts == 0
+run redo
+expect_value tube_parts == 1
+
+# A point's dot: dragging it selects the Tube Part and moves the point (one undo step).
+drag_tube_point 2 0 -60
+expect_value active_part == 1
+expect_value tube_selected == 2
+expect_status "point moved"
+shot edit
+ui_scale auto # the Edit group as a 2560x1600 laptop at 200% shows it (#105)
+logical_width 1280
+wait_idle 30
+shot panel-200
+logical_width 1600
+ui_scale 100
+wait 0.3
+key ctrl+z
+expect_status "Undo"
+
+# Ctrl+drag: thicker there.
+hold ctrl
+drag_tube_point 2 80 0
+hold none
+expect_status "point size"
+
+# Insert after the selected point, delete it again; Alt+click deletes a point too.
+run tube_list
+expect_value tube_selected == 2
+click "Tube/Insert Point"
+expect_value tube_selected == 3
+click "Tube/Delete Point"
+expect_value tube_selected == -1
+hold alt
+drag_tube_point 0 0 0
+hold none
+expect_status "Tube delete point"
+
+# Flat ends on the active tube, then Bake: a plain mesh to sculpt.
+click "Tube/Flat"
+expect_status "Tube settings"
+shot flat
+click "Tube/Bake"
+expect_value tube_points == 0
+expect_value tube_parts == 0
+expect_status "Baked the tube"
+key ctrl+z
+expect_value tube_parts == 1
+
+# Merge with Snap to surfaces: a strap along the sculpt goes into it, one undo step, no new Part.
+run part_select index=0
+click "Tube/Merge"
+click "Tube/Snap to surfaces"
+wait_value triangles > 0
+drag_path 0.22 0.55 0.35 0.72 0.5 0.78 0.65 0.72 0.78 0.55 S=0.8
+wait 0.2
+expect_value parts == 2
+expect_status "merged into"
+shot merged
+key ctrl+z
+expect_status "Undo"
+click "Tube/Snap to surfaces"
+click "Tube/Draw Tube"
+expect_value tube_draw == 0
+
+# Review shots at 1440 and 1024 logical px wide (display scale, as on a laptop) (the 200% ones are above): drawing, then the result with its Tube Part
+# selected (the panel's Edit group). The old tube goes first so the new one stands alone.
+run part_delete index=1
+expect_value tube_parts == 0
+click "Tube/New Part"
+click "Tube/Draw Tube"
+ui_scale auto
+logical_width 1440
+wait_idle 30
+drag_path 0.3 0.4 0.55 0.2 0.8 0.45 1.05 0.25 1.3 0.5 keep S=1.2
+shot drawing-1440
+release
+wait 0.2
+run part_select index=1
+expect_value tube_parts == 1
+shot result-1440
+run part_delete index=1
+run part_select index=0
+expect_value tube_parts == 0
+logical_width 1024
+wait_idle 30
+drag_path 0.3 0.4 0.55 0.2 0.8 0.45 1.05 0.25 1.3 0.5 keep S=1.2
+shot drawing-1024
+release
+wait 0.2
+run part_select index=1
+expect_value tube_parts == 1
+shot result-1024
+logical_width 1600
+ui_scale 100
+wait 0.3
+click "Tube/Draw Tube"
+expect_value tube_draw == 0
diff --git a/tools/i18n/keep_english.txt b/tools/i18n/keep_english.txt
index 42cdedda..8d81b3ad 100644
--- a/tools/i18n/keep_english.txt
+++ b/tools/i18n/keep_english.txt
@@ -41,3 +41,4 @@ http://%s
Gen-2.5 Low
Gen-2.5 Medium
Gen-2.5 High
+Tube
diff --git a/tools/marks_media_cache.json b/tools/marks_media_cache.json
index a292ac6d..86fd532d 100644
--- a/tools/marks_media_cache.json
+++ b/tools/marks_media_cache.json
@@ -85,6 +85,7 @@
"4bde61522bf27f55e387a0aa6c1925af05e06582184a30ace5cde82fb53a6dac": [],
"4f9321a7e87722aad3cb9703ef2bafea27c10bacaf6315c0670a229b0146e1ff": [],
"51313f9f90c32f96e254eb807442ef05ea0abbd0eaedff8e4df630d169ad57f1": [],
+"513ad55daca7516ab9f1fc210599cdf1169aa546b47f80cfaa1992aa8d57bc7f": [],
"51dacad0a25a5eb928fbb1debfa46cda06da4543871d254a706b4a67f3b0ced5": [],
"52f6361d0616feac8f940fb4fb91000b2bd559d3ae110fb6303a655cac3ae0c4": [],
"537afc75c0ab7ba9a183fee60331fa05b54055f582c7a4a487c52794c0aa8252": [],
@@ -228,6 +229,7 @@
"c14167f8b87f5beb2224bdc41fc44e66ca867d68549d82186545365c1f96ef28": [],
"c2822980664e43ab9e0444ecd4b11bfd4876e25afed8c9165606ec3eb8f68f35": [],
"c55da3155e8fb24d550449dcf69ba03dad7e6ed85e3fbff177a1eeca95cfb76a": [],
+"c7fdea880a8fb7e01963105ae5347eea10fcbcfdd72666712ce2616b906bb5db": [],
"c80e952f5c5931f9bada69cc73a37641cafb4315373620374cf05213972271ed": [],
"ca0ff93102fbcf0832a596809b07388b3a8f07ca4e15e8c12abd97f9436ed9f4": [],
"cfaaad5aaf5c67626f9eec0821b1e6691dfd03f1991d82ddd234348425fc130f": [],