3D view: pan the camera with Alt+drag or middle-drag

The 3D view could only orbit around the mesh center and zoom, so there was
no way to look at an off-center part of a mesh up close.

- View3d gains `target`, the orbit point's offset from the mesh center in
  mesh radii (world axes, so orbiting after a pan turns around the new
  point). `view.3d {target: [x, y, z]}` sets it, validated before anything
  changes and clamped to 5 radii; view.3d.reset clears it.
- The renderer orbits around the offset target, and `pan` turns a drag
  (in view heights) into a new target so the mesh follows the pointer.
- Alt+drag or middle-drag pans in the 3D view, like the graph. Double-click
  and the Camera presets recenter. The headless render honours the target.
This commit is contained in:
ljkx committed 2026-11-02 20:30:01 +01:00
1 parent cedabf0203
commit f786a2d4c3
9 files changed
+96 -9

No files matched your search

+1
View File
@@ -236,6 +236,7 @@ impl Headless {
yaw: o.yaw.unwrap_or(v.yaw),
pitch: o.pitch.unwrap_or(v.pitch),
distance: v.distance,
target: v.target,
tiling,
exposure: v.exposure,
env_rotation: v.env_rotation,
+3
View File
@@ -26,6 +26,8 @@ pub struct View3d {
pub yaw: f32,
pub pitch: f32,
pub distance: f32,
/// Where the camera orbits: offset from the mesh center (mesh radii, world axes).
pub target: [f32; 3],
/// Environment: `studio`, `sunset`, `overcast`, `night`.
pub environment: String,
pub env_rotation: f32,
@@ -44,6 +46,7 @@ impl Default for View3d {
yaw: 35.0,
pitch: 25.0,
distance: 3.2,
target: [0.0; 3],
environment: "studio".into(),
env_rotation: 0.0,
exposure: 0.0,
+19 -1
View File
@@ -18,6 +18,9 @@ pub const SCENES: &[(&str, &str)] = &[
("torus", "Torus"),
];
/// How far the 3D view's orbit target may move from the mesh center, in mesh radii.
pub const MAX_TARGET: f32 = 5.0;
/// Environments: (id, label).
pub const ENVIRONMENTS: &[(&str, &str)] = &[("studio", "Studio"), ("sunset", "Sunset"), ("overcast", "Overcast"), ("night", "Night")];
@@ -29,7 +32,7 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
"3D view settings",
[],
None,
"{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale?, axis?, grid?}",
"{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point, mesh radii from its center), environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale?, axis?, grid?}",
always,
view3d
),
@@ -85,6 +88,18 @@ fn view2d(s: &mut Session, p: &J) -> Result<J> {
}
fn view3d(s: &mut Session, p: &J) -> Result<J> {
// Validated up front so a bad target changes nothing.
let target = match p.get("target") {
None => None,
Some(t) => {
let xyz: Option<Vec<f32>> =
t.as_array().filter(|a| a.len() == 3).map(|a| a.iter().filter_map(J::as_f64).map(|f| f as f32).filter(|f| f.is_finite()).collect());
match xyz.as_deref() {
Some(&[x, y, z]) => Some([x, y, z].map(|v| v.clamp(-MAX_TARGET, MAX_TARGET))),
_ => return Err(bad("view.3d", "`target` is [x, y, z]")),
}
}
};
if let Some(sc) = strp(p, "scene") {
if sc == "custom" && s.custom_mesh.is_none() {
return Err(bad("view.3d", "no mesh is loaded: use view.3d.loadMesh"));
@@ -114,6 +129,9 @@ fn view3d(s: &mut Session, p: &J) -> Result<J> {
if let Some(t) = f32p(p, "distance") {
v.distance = t.clamp(1.2, 20.0);
}
if let Some(t) = target {
v.target = t;
}
if let Some(t) = f32p(p, "envRotation") {
v.env_rotation = t.rem_euclid(360.0);
}
+15
View File
@@ -151,3 +151,18 @@ fn presets_store_and_restore_inputs() {
run(&mut s, "graph.preset.delete", json!({"name": "Low"}));
assert!(s.graph().unwrap().presets.is_empty());
}
#[test]
fn view3d_target_is_validated_clamped_and_reset() {
let mut s = sample_session();
run(&mut s, "view.3d", json!({"target": [0.5, -0.25, 99.0]}));
assert_eq!(s.view3d.target, [0.5, -0.25, 5.0]);
// A malformed target is refused and changes nothing, not even the other fields.
for bad in [json!([1.0, 2.0]), json!("up"), json!([0.0, "x", 0.0]), json!([0.0, 1e300, 0.0])] {
assert!(execute(&mut s, "view.3d", &json!({"target": bad, "yaw": 90.0})).is_err());
assert_eq!(s.view3d.target, [0.5, -0.25, 5.0]);
assert_eq!(s.view3d.yaw, 35.0);
}
run(&mut s, "view.3d.reset", json!({}));
assert_eq!(s.view3d.target, [0.0; 3]);
}
+1 -1
View File
@@ -9,4 +9,4 @@
pub mod ibl;
pub mod preview;
pub use preview::{Lighting, Maps, Scene, Settings, builtin_mesh, render};
pub use preview::{Lighting, Maps, Scene, Settings, builtin_mesh, pan, render};
+42 -1
View File
@@ -163,6 +163,8 @@ pub struct Settings {
pub pitch: f32,
/// In scene radii.
pub distance: f32,
/// Orbit target offset from the scene center, in scene radii.
pub target: [f32; 3],
pub tiling: f32,
/// Stops.
pub exposure: f32,
@@ -187,6 +189,7 @@ impl Default for Settings {
yaw: 35.0,
pitch: 25.0,
distance: 3.2,
target: [0.0; 3],
tiling: 1.0,
exposure: 0.0,
env_rotation: 0.0,
@@ -199,10 +202,14 @@ impl Default for Settings {
}
}
/// How far the orbit target may wander from the scene center, in scene radii.
pub const MAX_TARGET: f32 = 5.0;
/// The orbit camera for `s` around `scene`.
pub fn camera(scene: &Scene, s: &Settings) -> OrbitCamera {
let t = Vec3::from(s.target.map(|v| if v.is_finite() { v.clamp(-MAX_TARGET, MAX_TARGET) } else { 0.0 }));
OrbitCamera {
target: scene.center,
target: scene.center + t * scene.radius,
yaw: s.yaw.to_radians(),
pitch: s.pitch.clamp(-89.0, 89.0).to_radians(),
distance: s.distance.clamp(1.05, 50.0) * scene.radius,
@@ -212,6 +219,14 @@ pub fn camera(scene: &Scene, s: &Settings) -> OrbitCamera {
}
}
/// `s.target` after panning the view by (dx, dy) viewport heights: the scene follows the pointer.
pub fn pan(scene: &Scene, s: &Settings, dx: f32, dy: f32) -> [f32; 3] {
let mut cam = camera(scene, s);
cam.pan(dx, dy);
let t = (cam.target - scene.center) / scene.radius.max(1e-6);
t.to_array().map(|v| if v.is_finite() { v.clamp(-MAX_TARGET, MAX_TARGET) } else { 0.0 })
}
#[inline]
fn tex(img: &Option<Image>, uv: Vec2) -> Option<[f32; 4]> {
img.as_ref().map(|i| i.sample(uv.x, uv.y, true))
@@ -458,4 +473,30 @@ mod tests {
assert!(px[c] > px[c + 1], "{id}: center is not red ({:?})", &px[c..c + 3]);
}
}
#[test]
fn panning_moves_the_scene_with_the_pointer() {
let scene = Scene::builtin("sphere");
let s = Settings::default();
let at = |s: &Settings| camera(&scene, s).project(scene.center, 1.0).unwrap();
// Dragging right and down by a tenth of the view moves the center right and down by
// the same fraction (NDC spans two view heights, y up).
let right = Settings { target: pan(&scene, &s, 0.1, 0.0), ..s };
let p = at(&right);
assert!((p.x - 0.2).abs() < 1e-3 && p.y.abs() < 1e-3, "{p:?}");
let down = Settings { target: pan(&scene, &s, 0.0, 0.1), ..s };
let p = at(&down);
assert!(p.x.abs() < 1e-3 && (p.y + 0.2).abs() < 1e-3, "{p:?}");
// Orbiting turns around the panned target, not the scene center.
let turned = Settings { yaw: s.yaw + 90.0, ..right };
let cam = camera(&scene, &turned);
assert!((cam.target - camera(&scene, &right).target).length() < 1e-5);
// Panning back returns home; hostile inputs stay finite and bounded.
let back = pan(&scene, &right, -0.1, 0.0);
assert!(back.iter().all(|v| v.abs() < 1e-4), "{back:?}");
let far = pan(&scene, &s, 1e9, f32::NAN);
assert!(far.iter().all(|v| v.is_finite() && v.abs() <= MAX_TARGET), "{far:?}");
let wild = Settings { target: [f32::NAN, f32::INFINITY, -1e9], ..s };
assert!(camera(&scene, &wild).eye().is_finite());
}
}
+13 -5
View File
@@ -1,6 +1,7 @@
//! The 3D view: the open graph's material on a built-in scene, rendered by
//! `materialcraft-render` (one ray per pixel at half resolution while the camera moves, 2×2
//! supersampled when it rests). Left-drag orbits, the wheel zooms, Shift+drag turns the light.
//! supersampled when it rests). Left-drag orbits, Alt+drag or middle-drag pans, the wheel zooms,
//! Shift+drag turns the light and a double-click resets the camera.
use egui::{Color32, ColorImage, Rect, Sense, TextureHandle, TextureOptions, Ui, pos2, vec2};
use egui_phosphor::regular as icon;
@@ -64,7 +65,7 @@ fn menus(app: &mut MaterialCraftApp, ui: &mut Ui) {
ui.menu_button(tr("Camera"), |ui| {
for (label, yaw, pitch) in [("Default", 35.0, 25.0), ("Front", 0.0, 0.0), ("Top", 0.0, 89.0), ("Side", 90.0, 0.0)] {
if ui.button(tr(label)).clicked() {
app.run("view.3d", json!({"yaw": yaw, "pitch": pitch, "distance": 3.2}));
app.run("view.3d", json!({"yaw": yaw, "pitch": pitch, "distance": 3.2, "target": [0.0, 0.0, 0.0]}));
ui.close();
}
}
@@ -114,7 +115,13 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
if resp.dragged() {
let d = resp.drag_delta();
let v = &app.session.view3d;
if ui.input(|i| i.modifiers.shift) {
if ui.input(|i| i.modifiers.alt) || resp.dragged_by(egui::PointerButton::Middle) {
if let Some((_, scene)) = &app.view3d.scene {
let s = Settings { yaw: v.yaw, pitch: v.pitch, distance: v.distance, target: v.target, ..Settings::default() };
let h = rect.height().max(1.0);
app.session.view3d.target = materialcraft_render::pan(scene, &s, d.x / h, d.y / h);
}
} else if ui.input(|i| i.modifiers.shift) {
let rot = (v.env_rotation + d.x * 0.5).rem_euclid(360.0);
app.session.view3d.env_rotation = rot;
} else {
@@ -132,7 +139,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
}
}
if resp.double_clicked() {
app.run("view.3d", json!({"yaw": 35.0, "pitch": 25.0, "distance": 3.2}));
app.run("view.3d", json!({"yaw": 35.0, "pitch": 25.0, "distance": 3.2, "target": [0.0, 0.0, 0.0]}));
}
render(app, ui.ctx(), rect, moving || resp.is_pointer_button_down_on());
let p = ui.painter_at(rect);
@@ -185,7 +192,7 @@ fn content_key(app: &MaterialCraftApp, w: u32, h: u32, show_env: bool) -> u64 {
let mut hs = DefaultHasher::new();
let v = &app.session.view3d;
(w, h, show_env, &v.scene, &v.environment, app.session.custom_mesh.as_ref().map(|(n, _)| n)).hash(&mut hs);
for f in [v.yaw, v.pitch, v.distance, v.tiling, v.exposure, v.env_rotation, v.height_scale] {
for f in [v.yaw, v.pitch, v.distance, v.target[0], v.target[1], v.target[2], v.tiling, v.exposure, v.env_rotation, v.height_scale] {
f.to_bits().hash(&mut hs);
}
if let Ok(g) = app.session.graph() {
@@ -224,6 +231,7 @@ fn render(app: &mut MaterialCraftApp, ctx: &egui::Context, rect: Rect, moving: b
yaw: v.yaw,
pitch: v.pitch,
distance: v.distance,
target: v.target,
tiling: v.tiling,
exposure: v.exposure,
env_rotation: v.env_rotation,
+1
View File
@@ -345,6 +345,7 @@ fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) {
("Middle drag / Alt+drag", "Pan the graph"),
("Double-click node", "Show in the 2D view"),
("Shift+D", "Disable selection"),
("Middle drag / Alt+drag (3D view)", "Pan the camera"),
("Shift+drag (3D view)", "Turn the environment"),
] {
ui.label(tr(what));
+1 -1
View File
@@ -14,7 +14,7 @@ automation + tests), weighted by how much of the day each area carries. **Remain
| Function graphs | 10 | 70% | A compiled, 4-wide evaluator with ~55 ops (constants, $pos/$size, exposed variables, samplers, vectors, swizzles, math, logic, comparison, noise, random, if/else); pixel and value processors; a visual function editor; dynamic parameters (a function on any numeric, color, bool or enum parameter, evaluated from the graph's inputs) | Loops, function graphs as reusable package items |
| Graph parameters and instances | 8 | 70% | Exposed inputs (float, int, bool, enum, color) bound to parameters of any compatible type, shown in groups, edited with one shared editor on the graph and on its instances; presets (save, apply, delete); sub-graph instances with their own inputs and outputs; graph attributes; `--set` on the CLI | Visibility conditions, per-instance output sizes, embedded vs. linked packages |
| 2D view | 5 | 80% | Pan/zoom, fit and 1:1, RGBA/R/G/B/A isolation, 3×3 tiling check, histogram, pixel readout, size/format line, save image | Color picker to parameters, UV overlay |
| 3D view | 10 | 55% | Rounded cube, cube, sphere, cylinder, plane, torus and material ball; OBJ, glTF and GLB meshes; base color, normal, roughness, metallic, height (parallax occlusion), AO, emissive and opacity; 4 procedural environments with rotation and exposure; orbit/zoom; tiling; supersampling at rest | GPU renderer with tessellation, lights, material/shader switching, path-traced renderer |
| 3D view | 10 | 55% | Rounded cube, cube, sphere, cylinder, plane, torus and material ball; OBJ, glTF and GLB meshes; base color, normal, roughness, metallic, height (parallax occlusion), AO, emissive and opacity; 4 procedural environments with rotation and exposure; orbit/pan/zoom; tiling; supersampling at rest | GPU renderer with tessellation, lights, material/shader switching, path-traced renderer |
| Files | 8 | 70% | `.mcraft` packages with embedded bitmaps; `.mcmat` portable materials (cooked maps, exposed inputs, presets, input nodes, the source package) that TextureCraft paints with and re-cooks through the CLI at its own resolution, values and mesh maps; preview images for input nodes; export of every output (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR; 8/16/32 bits; name pattern; sRGB vs. linear by usage); bitmap import (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR); mesh import (OBJ, glTF, GLB); open, save, import and export in the browser; atomic writes; autosave; recent files | An MCP tool for portable materials, package dependencies, SVG and font files as resources |
| UI and UX | 8 | 70% | Dockable/floatable panels (explorer, library, graph, 3D, 2D, properties, console, history), menus, main toolbar, graph toolbar with atomic quick-insert, library with live previews, properties with curve/gradient/color editors, New graph dialog with rendered templates, export dialog, preferences (brightness, accent, scale, preview size, autosave), shortcuts list, home screen at startup (samples and recent files), visual function editor, presets bar, accessible names on every widget, status bar | Translations, keymap editor, minimap, multi-graph tabs |
| Platforms | 4 | 50% | Windows, macOS, Linux, FreeBSD and web builds compile; browser file I/O; packaging scripts and release workflows | First release run |