M3: real 3D translate gizmo — the "полноценный 3D-пайплайн" it was chosen for

TranslateGizmo draws three axis handles at the selected GameObject's
world position by projecting real 3D points through the real camera's
View/Projection (GizmoMath.WorldToScreen) onto ImGui's foreground draw
list. Nothing OpenGL-side draws lines yet, so this isn't 3D geometry
in the GL sense — but it IS driven by the actual camera matrices, which
is what the earlier scoped-2D-vs-full-3D-pipeline choice was actually
about: a handle dragged in screen space has to map onto a real 3D axis,
and that only means something once there's a real camera to project
through. The screenshot below shows exactly that — the axes aren't
screen-perpendicular, because the camera at (0,3,6) looking at the
origin means they shouldn't be.

Dragging a handle re-projects the mouse delta onto the axis's own
screen-space direction (GizmoMath.ProjectDragOntoAxis) and writes the
result back through GizmoMath.WorldToLocalPosition, which inverts the
parent's WorldMatrix rather than writing LocalPosition directly — a
parent with non-identity scale or rotation means "move 1 world unit"
and "add 1 to LocalPosition" are different amounts, and
samples/WindowDemo's ChildQuad (parented under a (2,2,1)-scaled Quad)
is exactly that case.

Split the actual math into GizmoMath (Engine.Editor.Contracts, no GL/
ImGui/mouse dependency) so it's unit-testable without a window or a real
mouse — neither exists in a headless test run, and dragging is exactly
the kind of interaction that's easy to get subtly wrong (screen-space
ratio direction, perspective sign, parent-scale correctness) without
something to check it against beyond eyeballing a screenshot. New
Engine.Editor.Tests project, 8 tests: screen-center projection, a
behind-camera point returning null, drag-ratio math on both an
axis-aligned and a diagonal screen direction, and the parent-scale/
parent-translation inverse-transform cases. All 8 passed on the first
run — including the non-uniform-scale case, the one most likely to be
subtly wrong.

Full suite: 73 tests, all green (65 previous + 8 new).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01N1qPfzq8TDCUMFMV3UwV5N
This commit is contained in:
Emil
2026-09-02 16:30:54 +03:00
co-authored by Claude Sonnet 5
parent d7fcc20f5e
commit e0e6c1d503
6 changed files with 339 additions and 0 deletions
+15
View File
@@ -55,6 +55,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Engine.Editor.Contracts", "
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Engine.Editor", "plugins\engine.editor\Engine.Editor\Engine.Editor.csproj", "{B60A3933-923C-4339-98D1-E4C87A76E80B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Engine.Editor.Tests", "tests\Engine.Editor.Tests\Engine.Editor.Tests.csproj", "{7F1CF468-6717-4152-BA95-2DA1E011B6CB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -269,6 +271,18 @@ Global
{B60A3933-923C-4339-98D1-E4C87A76E80B}.Release|x64.Build.0 = Release|Any CPU
{B60A3933-923C-4339-98D1-E4C87A76E80B}.Release|x86.ActiveCfg = Release|Any CPU
{B60A3933-923C-4339-98D1-E4C87A76E80B}.Release|x86.Build.0 = Release|Any CPU
{7F1CF468-6717-4152-BA95-2DA1E011B6CB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7F1CF468-6717-4152-BA95-2DA1E011B6CB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7F1CF468-6717-4152-BA95-2DA1E011B6CB}.Debug|x64.ActiveCfg = Debug|Any CPU
{7F1CF468-6717-4152-BA95-2DA1E011B6CB}.Debug|x64.Build.0 = Debug|Any CPU
{7F1CF468-6717-4152-BA95-2DA1E011B6CB}.Debug|x86.ActiveCfg = Debug|Any CPU
{7F1CF468-6717-4152-BA95-2DA1E011B6CB}.Debug|x86.Build.0 = Debug|Any CPU
{7F1CF468-6717-4152-BA95-2DA1E011B6CB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7F1CF468-6717-4152-BA95-2DA1E011B6CB}.Release|Any CPU.Build.0 = Release|Any CPU
{7F1CF468-6717-4152-BA95-2DA1E011B6CB}.Release|x64.ActiveCfg = Release|Any CPU
{7F1CF468-6717-4152-BA95-2DA1E011B6CB}.Release|x64.Build.0 = Release|Any CPU
{7F1CF468-6717-4152-BA95-2DA1E011B6CB}.Release|x86.ActiveCfg = Release|Any CPU
{7F1CF468-6717-4152-BA95-2DA1E011B6CB}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -297,5 +311,6 @@ Global
{8067C66D-9D49-192B-E4C1-1C024401ACE3} = {07D57EEB-2F50-60C4-C011-FE4FA775C9A8}
{6A2943F1-1984-470D-BD74-C6E16BB77241} = {8067C66D-9D49-192B-E4C1-1C024401ACE3}
{B60A3933-923C-4339-98D1-E4C87A76E80B} = {8067C66D-9D49-192B-E4C1-1C024401ACE3}
{7F1CF468-6717-4152-BA95-2DA1E011B6CB} = {0AB3BF05-4346-4AA6-1389-037BE0695223}
EndGlobalSection
EndGlobal
@@ -0,0 +1,87 @@
using System.Numerics;
namespace Engine.Editor.Contracts;
/// <summary>
/// The pure math behind a screen-space-drag-to-3D-axis gizmo, split out
/// from TranslateGizmo (Engine.Editor, which owns the ImGui drawing and
/// live mouse/GameObject state) specifically so it's unit-testable without
/// a GL context, a real window, or a mouse — none of which a headless test
/// run has. See TranslateGizmo's own doc comment for how these three
/// functions compose into an actual drag.
/// </summary>
public static class GizmoMath
{
/// <summary>
/// Projects a world-space point through view*projection to a
/// screen-space pixel coordinate. Null when the point is behind the
/// camera (w &lt;= 0) — there's no sane screen position for it, and
/// drawing one anyway (naive perspective division) would fling it to
/// whatever's on the opposite side of the screen instead of just not
/// being there.
/// </summary>
public static Vector2? WorldToScreen(Vector3 worldPos, Matrix4x4 viewProjection, Vector2 screenSize)
{
var clip = Vector4.Transform(new Vector4(worldPos, 1f), viewProjection);
if (clip.W <= 0f)
return null;
var ndcX = clip.X / clip.W;
var ndcY = clip.Y / clip.W;
// NDC's Y axis points up; screen-space pixel Y points down.
return new Vector2(
(ndcX * 0.5f + 0.5f) * screenSize.X,
(1f - (ndcY * 0.5f + 0.5f)) * screenSize.Y);
}
/// <summary>
/// How far along a world-space axis the current drag corresponds to,
/// in world units. Works entirely in screen space: how far the mouse
/// moved along the axis's own on-screen direction (not just its raw XY
/// delta — an axis pointing diagonally on screen needs the component
/// of the mouse movement that's actually along it), scaled by how many
/// world units one screen pixel represented for this axis at drag
/// start (screenLen pixels spanned axisWorldLength world units).
///
/// This is a projection-ratio approximation, not true ray/nearest-point
/// axis math — ratio holds exactly only at the handle's own depth, and
/// drifts slightly as the object moves toward or away from the camera
/// mid-drag under perspective projection. Good enough for a first
/// working gizmo; a real nearest-point-on-ray solve is more machinery
/// than a single translate handle has earned yet.
/// </summary>
public static float ProjectDragOntoAxis(
Vector2 origin2D, Vector2 tip2D, Vector2 dragStartMouse, Vector2 currentMouse, float axisWorldLength)
{
var screenDir = tip2D - origin2D;
var screenLen = screenDir.Length();
if (screenLen < 0.0001f)
return 0f;
var normalizedDir = screenDir / screenLen;
var mouseDelta = currentMouse - dragStartMouse;
var pixelsAlongAxis = Vector2.Dot(mouseDelta, normalizedDir);
return pixelsAlongAxis / screenLen * axisWorldLength;
}
/// <summary>
/// Converts a desired new world-space position into the local position
/// GameObject.Transform.LocalPosition needs to produce it — the inverse
/// of GameObject.WorldMatrix's own composition. Null parentWorldMatrix
/// (no parent) means local and world are the same space. Matters
/// specifically because a parent's non-identity scale or rotation means
/// "move 1 world unit along X" and "add 1 to LocalPosition.X" are not
/// the same thing — see samples/WindowDemo's ChildQuad, parented under
/// a GameObject with a non-uniform (2,2,1) scale, which is exactly the
/// case this needs to get right.
/// </summary>
public static Vector3 WorldToLocalPosition(Vector3 worldPos, Matrix4x4? parentWorldMatrix)
{
if (parentWorldMatrix is null)
return worldPos;
Matrix4x4.Invert(parentWorldMatrix.Value, out var inverse);
return Vector3.Transform(worldPos, inverse);
}
}
@@ -4,6 +4,7 @@ using Engine.Kernel.Diagnostics;
using Engine.Kernel.Plugins;
using Engine.Kernel.Scheduling;
using Engine.Kernel.World;
using Engine.Render.Contracts;
using Engine.Windowing.Contracts;
using ImGuiNET;
using Silk.NET.OpenGL;
@@ -29,16 +30,21 @@ namespace Engine.Editor;
public sealed class EditorPlugin : IPlugin
{
private readonly EditorState _state = new();
private readonly TranslateGizmo _gizmo = new();
private GL? _gl;
private ImGuiController? _controller;
private ITime? _time;
private PlayModeController? _playMode;
private IEngineWindow? _window;
private ICameraService? _camera;
public void Configure(IPluginContext ctx)
{
var window = ctx.Services.Require<IEngineWindow>();
var input = ctx.Services.Require<IEngineInput>();
_time = ctx.Time;
_window = window;
_camera = ctx.Services.Require<ICameraService>();
window.Native.GLContext!.MakeCurrent();
_gl = window.Native.CreateOpenGL();
@@ -61,6 +67,8 @@ public sealed class EditorPlugin : IPlugin
_gl = null;
_time = null;
_playMode = null;
_window = null;
_camera = null;
}
private void DrawUi(IWorld world)
@@ -101,6 +109,7 @@ public sealed class EditorPlugin : IPlugin
HierarchyPanel.Draw(world, _state);
InspectorPanel.Draw(_state);
_gizmo.Draw(_state, _camera!, _window!);
_controller.Render();
}
@@ -0,0 +1,100 @@
using System.Numerics;
using Engine.Editor.Contracts;
using Engine.Kernel.World;
using Engine.Render.Contracts;
using Engine.Windowing.Contracts;
using ImGuiNET;
namespace Engine.Editor;
/// <summary>
/// M3's actual gizmo, per the "полноценный 3D-пайплайн" choice over a
/// scoped 2D one: three axis handles at the selected GameObject's world
/// position, drawn by projecting real 3D points through the real camera's
/// View/Projection (GizmoMath.WorldToScreen) onto ImGui's foreground draw
/// list — not OpenGL geometry, since nothing in engine.render draws lines
/// yet and ImGui's own 2D draw list, fed real 3D-projected coordinates, is
/// already exactly "a handle dragged in screen space mapped onto a real 3D
/// axis." Dragging reads GizmoMath.ProjectDragOntoAxis and writes back
/// through GizmoMath.WorldToLocalPosition — both pure and unit-tested in
/// Engine.Editor.Tests, since neither needs a GL context or a real mouse to
/// verify, only this glue does.
/// </summary>
internal sealed class TranslateGizmo
{
private const float AxisLength = 1.5f;
private const float HandleRadius = 6f;
private static readonly Vector3[] AxisDirections = [Vector3.UnitX, Vector3.UnitY, Vector3.UnitZ];
private int _dragAxis = -1;
private Vector2 _dragStartMouse;
private Vector3 _dragStartWorldPosition;
public void Draw(EditorState state, ICameraService camera, IEngineWindow window)
{
var go = state.Selected;
if (go is null)
return;
var screenSize = new Vector2(window.Native.FramebufferSize.X, window.Native.FramebufferSize.Y);
if (screenSize.X <= 0 || screenSize.Y <= 0)
return;
var viewProjection = camera.View * camera.Projection;
var worldPos = go.WorldMatrix.Translation;
var origin2D = GizmoMath.WorldToScreen(worldPos, viewProjection, screenSize);
if (origin2D is null)
return;
var mouse = ImGui.GetIO().MousePos;
var mouseFree = !ImGui.GetIO().WantCaptureMouse;
var drawList = ImGui.GetForegroundDrawList();
for (var axis = 0; axis < 3; axis++)
{
var tipWorld = worldPos + AxisDirections[axis] * AxisLength;
var tip2D = GizmoMath.WorldToScreen(tipWorld, viewProjection, screenSize);
if (tip2D is null)
continue;
var color = AxisColor(axis);
drawList.AddLine(origin2D.Value, tip2D.Value, color, 3f);
drawList.AddCircleFilled(tip2D.Value, HandleRadius, color);
var hovering = Vector2.Distance(mouse, tip2D.Value) <= HandleRadius + 2f;
if (_dragAxis == -1 && hovering && mouseFree && ImGui.IsMouseClicked(ImGuiMouseButton.Left))
{
_dragAxis = axis;
_dragStartMouse = mouse;
_dragStartWorldPosition = worldPos;
}
if (_dragAxis != axis)
continue;
if (!ImGui.IsMouseDown(ImGuiMouseButton.Left))
{
_dragAxis = -1;
continue;
}
var delta = GizmoMath.ProjectDragOntoAxis(origin2D.Value, tip2D.Value, _dragStartMouse, mouse, AxisLength);
var newWorldPos = _dragStartWorldPosition + AxisDirections[axis] * delta;
var parentMatrix = go.Parent?.WorldMatrix;
var t = go.Transform;
t.LocalPosition = GizmoMath.WorldToLocalPosition(newWorldPos, parentMatrix);
go.Transform = t;
}
}
private static uint AxisColor(int axis) => axis switch
{
0 => ImGui.ColorConvertFloat4ToU32(new Vector4(1f, 0.25f, 0.25f, 1f)), // X: red
1 => ImGui.ColorConvertFloat4ToU32(new Vector4(0.3f, 1f, 0.3f, 1f)), // Y: green
_ => ImGui.ColorConvertFloat4ToU32(new Vector4(0.35f, 0.55f, 1f, 1f)), // Z: blue
};
}
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\plugins\engine.editor\Engine.Editor.Contracts\Engine.Editor.Contracts.csproj" />
</ItemGroup>
</Project>
+106
View File
@@ -0,0 +1,106 @@
using System.Numerics;
using Engine.Editor.Contracts;
namespace Engine.Editor.Tests;
public class GizmoMathTests
{
[Fact]
public void WorldToScreen_OriginProjectsToScreenCenter_ForSymmetricCamera()
{
var view = Matrix4x4.CreateLookAt(new Vector3(0, 0, 5), Vector3.Zero, Vector3.UnitY);
var projection = Matrix4x4.CreatePerspectiveFieldOfView(MathF.PI / 4f, 1f, 0.1f, 100f);
var screenSize = new Vector2(800, 800);
var screen = GizmoMath.WorldToScreen(Vector3.Zero, view * projection, screenSize);
Assert.NotNull(screen);
Assert.Equal(400f, screen!.Value.X, precision: 3);
Assert.Equal(400f, screen.Value.Y, precision: 3);
}
[Fact]
public void WorldToScreen_PointBehindCamera_ReturnsNull()
{
var view = Matrix4x4.CreateLookAt(new Vector3(0, 0, 5), Vector3.Zero, Vector3.UnitY);
var projection = Matrix4x4.CreatePerspectiveFieldOfView(MathF.PI / 4f, 1f, 0.1f, 100f);
// Camera sits at z=5 looking toward z=0; a point at z=10 is on the
// far side of the camera from where it's looking, not just far away.
var screen = GizmoMath.WorldToScreen(new Vector3(0, 0, 10), view * projection, new Vector2(800, 800));
Assert.Null(screen);
}
[Fact]
public void ProjectDragOntoAxis_AlongScreenAxis_ScalesLinearly()
{
var origin = new Vector2(100, 100);
var tip = new Vector2(200, 100); // 100px maps to 2 world units
var start = new Vector2(100, 100);
var current = new Vector2(150, 100); // half the drag
var result = GizmoMath.ProjectDragOntoAxis(origin, tip, start, current, axisWorldLength: 2f);
Assert.Equal(1f, result, precision: 4);
}
[Fact]
public void ProjectDragOntoAxis_DiagonalAxis_ProjectsOnlyTheAlignedComponent()
{
var origin = new Vector2(0, 0);
var tip = new Vector2(100, 100); // 45-degree axis, length ~141.42
var start = Vector2.Zero;
// Move straight along X only — half of it is "along" the diagonal axis.
var current = new Vector2(100, 0);
var result = GizmoMath.ProjectDragOntoAxis(origin, tip, start, current, axisWorldLength: 2f);
Assert.Equal(1f, result, precision: 3);
}
[Fact]
public void ProjectDragOntoAxis_ZeroLengthAxis_ReturnsZero()
{
var result = GizmoMath.ProjectDragOntoAxis(
new Vector2(50, 50), new Vector2(50, 50), Vector2.Zero, new Vector2(999, 999), axisWorldLength: 2f);
Assert.Equal(0f, result);
}
[Fact]
public void WorldToLocalPosition_NoParent_ReturnsWorldPositionUnchanged()
{
var worldPos = new Vector3(3, 4, 5);
var local = GizmoMath.WorldToLocalPosition(worldPos, parentWorldMatrix: null);
Assert.Equal(worldPos, local);
}
[Fact]
public void WorldToLocalPosition_ParentWithNonUniformScale_AccountsForScale()
{
// Exactly samples/WindowDemo's ChildQuad case: a parent scaled
// (2,2,1) — moving 2 world units along X must become 1 local unit,
// not 2, or the object would drift as it's dragged.
var parentMatrix = Matrix4x4.CreateScale(2, 2, 1);
var worldPos = new Vector3(2, 0, 0);
var local = GizmoMath.WorldToLocalPosition(worldPos, parentMatrix);
Assert.Equal(new Vector3(1, 0, 0), local);
}
[Fact]
public void WorldToLocalPosition_ParentWithTranslation_SubtractsParentOffset()
{
var parentMatrix = Matrix4x4.CreateTranslation(5, 0, 0);
var worldPos = new Vector3(7, 0, 0);
var local = GizmoMath.WorldToLocalPosition(worldPos, parentMatrix);
Assert.Equal(new Vector3(2, 0, 0), local);
}
}