diff --git a/LinguaEngine.sln b/LinguaEngine.sln index 10f9391..e8479fe 100644 --- a/LinguaEngine.sln +++ b/LinguaEngine.sln @@ -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 diff --git a/plugins/engine.editor/Engine.Editor.Contracts/GizmoMath.cs b/plugins/engine.editor/Engine.Editor.Contracts/GizmoMath.cs new file mode 100644 index 0000000..b467d91 --- /dev/null +++ b/plugins/engine.editor/Engine.Editor.Contracts/GizmoMath.cs @@ -0,0 +1,87 @@ +using System.Numerics; + +namespace Engine.Editor.Contracts; + +/// +/// 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. +/// +public static class GizmoMath +{ + /// + /// Projects a world-space point through view*projection to a + /// screen-space pixel coordinate. Null when the point is behind the + /// camera (w <= 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. + /// + 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); + } + + /// + /// 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. + /// + 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; + } + + /// + /// 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. + /// + 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); + } +} diff --git a/plugins/engine.editor/Engine.Editor/EditorPlugin.cs b/plugins/engine.editor/Engine.Editor/EditorPlugin.cs index ea0fddf..3f8ba2f 100644 --- a/plugins/engine.editor/Engine.Editor/EditorPlugin.cs +++ b/plugins/engine.editor/Engine.Editor/EditorPlugin.cs @@ -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(); var input = ctx.Services.Require(); _time = ctx.Time; + _window = window; + _camera = ctx.Services.Require(); 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(); } diff --git a/plugins/engine.editor/Engine.Editor/TranslateGizmo.cs b/plugins/engine.editor/Engine.Editor/TranslateGizmo.cs new file mode 100644 index 0000000..72cdd04 --- /dev/null +++ b/plugins/engine.editor/Engine.Editor/TranslateGizmo.cs @@ -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; + +/// +/// 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. +/// +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 + }; +} diff --git a/tests/Engine.Editor.Tests/Engine.Editor.Tests.csproj b/tests/Engine.Editor.Tests/Engine.Editor.Tests.csproj new file mode 100644 index 0000000..d2d62e9 --- /dev/null +++ b/tests/Engine.Editor.Tests/Engine.Editor.Tests.csproj @@ -0,0 +1,22 @@ + + + + false + + + + + + + + + + + + + + + + + + diff --git a/tests/Engine.Editor.Tests/GizmoMathTests.cs b/tests/Engine.Editor.Tests/GizmoMathTests.cs new file mode 100644 index 0000000..7dfefe9 --- /dev/null +++ b/tests/Engine.Editor.Tests/GizmoMathTests.cs @@ -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); + } +}