diff --git a/Components/Components/Containers/ChiselModelComponent.cs b/Components/Components/Containers/ChiselModelComponent.cs index 7d983d29..8ed1f722 100644 --- a/Components/Components/Containers/ChiselModelComponent.cs +++ b/Components/Components/Containers/ChiselModelComponent.cs @@ -247,7 +247,19 @@ public sealed class ChiselModelComponent : ChiselNodeComponent public ChiselGeneratedRenderSettings RenderSettings { get { return renderSettings; } } - public ChiselGeneratedColliderSettings ColliderSettings { get { return colliderSettings; } } + public ChiselGeneratedColliderSettings ColliderSettings { get { return colliderSettings; } } + + /// + /// The operation of a brush drawn out of one of the model's surfaces when none is chosen: pulled out of the surface + /// (a positive height) it adds, pushed into it it cuts. With the subtractive workflow the model's brushes are the + /// empty space, so there it is the other way round. + /// + public CSGOperationType OperationOutOfSurface(float height) + { + var pushedIn = height < 0; + var subtractiveWorkflow = renderSettings != null && renderSettings.subtractiveWorkflow; + return pushedIn != subtractiveWorkflow ? CSGOperationType.Subtractive : CSGOperationType.Additive; + } public override CSGTreeNode TopTreeNode { get { return Node; } protected set { Node = (CSGTree)value; } } public override bool IsContainer { get { return IsActive; } } public bool IsInitialized { get; private set; } = false; diff --git a/Components/Components/Decals/ChiselDecalComponent.cs b/Components/Components/Decals/ChiselDecalComponent.cs index 6f2e0695..808dc5e5 100644 --- a/Components/Components/Decals/ChiselDecalComponent.cs +++ b/Components/Components/Decals/ChiselDecalComponent.cs @@ -173,12 +173,14 @@ public ChiselExtrudedShapeComponent ExtrudeIntoBrush(float height) } /// How far a brush made reaches out of its surface (into it below zero), - /// adding or cutting to match + /// adding or cutting to match () public static void SetExtrusionHeight(ChiselExtrudedShapeComponent extruded, float height) { if (extruded == null) return; - extruded.Operation = height > 0 ? CSGOperationType.Additive : CSGOperationType.Subtractive; + var model = extruded.GetComponentInParent(); + extruded.Operation = model ? model.OperationOutOfSurface(height) : + height > 0 ? CSGOperationType.Additive : CSGOperationType.Subtractive; extruded.definition.path.segments[1].position = ChiselPathPoint.DefaultDirection * height; extruded.OnValidate(); // as the placement tools do while dragging, so it is built again diff --git a/Components/Components/Decals/ChiselSurfaceShapes.cs b/Components/Components/Decals/ChiselSurfaceShapes.cs index 95bc9dbd..978ea585 100644 --- a/Components/Components/Decals/ChiselSurfaceShapes.cs +++ b/Components/Components/Decals/ChiselSurfaceShapes.cs @@ -148,9 +148,9 @@ public static bool NearestOnOutline(IReadOnlyList outline, Vector3 poin } /// - /// A polygon decal as its surface has it now: its frame laid on the surface's plane (world space, Z into the surface), - /// and its corners in that frame's XY, the anchored ones where their edges are now. False when it has no surface - /// to be on: then it is where its transform and outline put it. + /// A polygon decal as its surface has it now: its frame laid on the surface's plane (world space, Z into the surface + /// from the side the decal is on), and its corners in that frame's XY, the anchored ones where their edges are now. + /// False when it has no surface to be on: then it is where its transform and outline put it. /// public static bool Resolve(ChiselDecalComponent decal, out Matrix4x4 frame, List corners) { @@ -165,9 +165,10 @@ public static bool Resolve(ChiselDecalComponent decal, out Matrix4x4 frame, List !SurfaceOutline(targets[0].brush, targets[0].surfaceIndex, outline, out var plane)) return false; - // the decal's frame turned onto the surface's plane, and moved onto it + // the decal's frame turned onto the surface's plane, and moved onto it. It stays on the side it was drawn on: a + // surface drawn turned round (a room's wall) is seen, and drawn on, from behind its brush's plane var transform = decal.transform; - var forward = -plane.normal; + var forward = Vector3.Dot(transform.forward, plane.normal) > 0 ? plane.normal : -plane.normal; var turn = Quaternion.FromToRotation(transform.forward, forward); var rotation = turn * transform.rotation; var position = plane.ClosestPointOnPlane(transform.position); diff --git a/Components/Query/ChiselHotspotRepeats.cs b/Components/Query/ChiselHotspotRepeats.cs index d54aba35..db7ea2ec 100644 --- a/Components/Query/ChiselHotspotRepeats.cs +++ b/Components/Query/ChiselHotspotRepeats.cs @@ -1,4 +1,5 @@ using Chisel.Core; +using Unity.Entities; using Unity.Mathematics; namespace Chisel.Components @@ -6,10 +7,10 @@ namespace Chisel.Components // A hotspot surface's repeats as its last build laid them public static class ChiselHotspotRepeats { - // The section input a surface was last built with; false when it has none - public static bool TryGetSectionInput(SurfaceReference surface, out HotspotSectionInput input) + // What the last build of the surface's brush drew; false when it drew nothing yet or the surface isn't in it + internal static bool TryGetBuilt(SurfaceReference surface, out BlobAssetReference buffer) { - input = default; + buffer = default; if (surface == null || !surface.node || !surface.brush.Valid) return false; var model = surface.node.hierarchyItem.Model; @@ -21,12 +22,18 @@ public static bool TryGetSectionInput(SurfaceReference surface, out HotspotSecti var data = lookups[model.Node]; data.lastJobHandle.Complete(); if (!data.brushRenderBufferLookup.IsCreated || - !data.brushRenderBufferLookup.TryGetValue(CompactHierarchyManager.GetCompactNodeID(surface.brush), out var buffer) || !buffer.IsCreated) + !data.brushRenderBufferLookup.TryGetValue(CompactHierarchyManager.GetCompactNodeID(surface.brush), out buffer) || !buffer.IsCreated) return false; - ref var surfaces = ref buffer.Value.surfaces; - if (surface.surfaceIndex < 0 || surface.surfaceIndex >= surfaces.Length) + return surface.surfaceIndex >= 0 && surface.surfaceIndex < buffer.Value.surfaces.Length; + } + + // The section input a surface was last built with; false when it has none + public static bool TryGetSectionInput(SurfaceReference surface, out HotspotSectionInput input) + { + input = default; + if (!TryGetBuilt(surface, out var buffer)) return false; - input = surfaces[surface.surfaceIndex].sectionInput; + input = buffer.Value.surfaces[surface.surfaceIndex].sectionInput; return input.count > 0; } diff --git a/Components/Query/ChiselTextureLock.cs b/Components/Query/ChiselTextureLock.cs index 8baec988..d0cd7c9f 100644 --- a/Components/Query/ChiselTextureLock.cs +++ b/Components/Query/ChiselTextureLock.cs @@ -32,10 +32,31 @@ public static SurfaceDetails Toggled(SurfaceReference surface, SurfaceDetails de var to = toWorld ? worldToPlane : objectToPlane; details.UV0 = (UVMatrix)math.mul((float4x4)details.UV0, math.mul(from, math.inverse(to))); - details.hotspot = ToggledHotspot(surface, details.hotspot, toWorld, treePlane.xyz, math.normalizesafe(plane.xyz), nodeToTree, treeToNode); + // a hotspot tile is laid out as seen from the side the surface is drawn on + var localNormal = math.normalizesafe(plane.xyz); + var turned = IsDrawnTurned(surface, treePlane.xyz); + details.hotspot = ToggledHotspot(surface, details.hotspot, toWorld, turned ? -treePlane.xyz : treePlane.xyz, localNormal, + turned ? -localNormal : localNormal, nodeToTree, treeToNode); return Flip(details, toWorld); } + // Whether the surface was last drawn turned round, seen from behind its brush's plane (treeNormal): every vertex + // of it facing the other way, as GenerateSurfaceTrianglesJob decides it + static bool IsDrawnTurned(SurfaceReference surface, float3 treeNormal) + { + if (!ChiselHotspotRepeats.TryGetBuilt(surface, out var buffer)) + return false; + ref var vertices = ref buffer.Value.surfaces[surface.surfaceIndex].renderVertices; + if (vertices.Length == 0) + return false; + for (int v = 0; v < vertices.Length; v++) + { + if (math.dot(vertices[v].normal, treeNormal) >= 0) + return false; + } + return true; + } + static SurfaceDetails Flip(SurfaceDetails details, bool toWorld) { if (toWorld) details.detailFlags |= SurfaceDetailFlags.TextureIsInWorldSpace; @@ -46,8 +67,9 @@ static SurfaceDetails Flip(SurfaceDetails details, bool toWorld) // A hotspot surface's settings in the other space: the turn between the object's frame and the world's, its // density in the brush's own units or the tree's, and its repeats' offset from the inset corner or the frame's // origin (from its last build) + // (normal: the drawn side's, in the tree; localNormal: the brush's plane's; ownNormal: that facing the drawn side) static HotspotSurface ToggledHotspot(SurfaceReference surface, HotspotSurface hotspot, bool toWorld, float3 normal, float3 localNormal, - float4x4 nodeToTree, float4x4 treeToNode) + float3 ownNormal, float4x4 nodeToTree, float4x4 treeToNode) { HotspotMatcher.Frame(normal, localNormal, nodeToTree, 0, false, out _, out var objectUp); HotspotMatcher.Frame(normal, 0, false, out var worldRight, out var worldUp); @@ -56,7 +78,7 @@ static HotspotSurface ToggledHotspot(SurfaceReference surface, HotspotSurface ho var rotation = hotspot.rotation + (toWorld ? delta : -delta); rotation -= 360 * math.floor(rotation / 360); // the brush's own units along the frame as locked (its rotation there) - var units = HotspotMatcher.OwnUnits(normal, localNormal, treeToNode, toWorld ? hotspot.rotation : rotation, hotspot.mirror); + var units = HotspotMatcher.OwnUnits(normal, ownNormal, treeToNode, toWorld ? hotspot.rotation : rotation, hotspot.mirror); hotspot.rotation = rotation; var density = hotspot.Density * (toWorld ? units : 1 / units); hotspot.density = density == 1 ? 0 : density; diff --git a/Components/Tests/ChiselHotspotMappingTests.cs b/Components/Tests/ChiselHotspotMappingTests.cs index 0105de81..14f3a548 100644 --- a/Components/Tests/ChiselHotspotMappingTests.cs +++ b/Components/Tests/ChiselHotspotMappingTests.cs @@ -510,6 +510,32 @@ public void TogglingTheLock_ChangesNothingOnScreen() AssertSameLook(plainBefore, plainModel, plainFront, "plain, to the world"); } + // A room's wall, seen from inside, looks the same after its lock is toggled too + [Test] + public void TogglingTheLockOfARoomsWall_ChangesNothingOnScreen([Values] bool subtractiveWorkflow) + { + BorderOnB1(32); + var model = Model(); + if (subtractiveWorkflow) + { + model.renderSettings.subtractiveWorkflow = true; + model.SyncModelSettingsStore(); + } else + Box(model, new float3(-8, -6, -4), new float3(10, 8, 4)); + var room = Box(model, new float3(-2, 0, -0.125f), new float3(6, 2, 0.125f), d => { d.hotspot.rotation = 90; return d; }); + if (!subtractiveWorkflow) + room.Operation = CSGOperationType.Subtractive; + Place(room, new Vector3(0.3f, 0.2f, 0), Quaternion.Euler(0, 0, 20), new Vector3(0.75f, 0.75f, 0.75f)); + // the wall the box's front is, seen from inside + var inside = math.normalize((float3)(room.transform.localRotation * Vector3.forward)); + var before = Drawn(model, inside); + ToggleLock(room); + Assert.That(ChiselTextureLock.IsInWorldSpace(room.SurfaceDefinition.surfaces[0].surfaceDetails), Is.True); + AssertSameLook(before, model, inside, "to the world"); + ToggleLock(room); + AssertSameLook(before, model, inside, "back to the object"); + } + // Every uv drawn at a position on a face with this normal static List UVsAt(ChiselModelComponent model, float3 position, float3 normal) { @@ -1464,6 +1490,30 @@ public void AMirroredWall_TakesItsTileMirrored() AreEqual(new float2(1.0f, 1.0f), UVAt(model, new float3(-2, 2, -0.125f), kFront), "top left"); } + // The back wall of a room, seen from inside, takes its tile as a wall of a solid does from outside: not mirrored. + // The room is carved out of a solid by a subtractive brush, or is a brush of a model with the subtractive workflow + [Test] + public void ARoomsWall_TakesItsTileUnmirrored([Values] bool subtractiveWorkflow) + { + var model = Model(); + if (subtractiveWorkflow) + { + model.renderSettings.subtractiveWorkflow = true; + model.SyncModelSettingsStore(); + Box(model, new float3(-2, 0, -1.875f), new float3(2, 2, 0.125f)); + } else + { + Box(model, new float3(-3, -1, -3), new float3(3, 3, 1)); + var room = Box(model, new float3(-2, 0, -1.875f), new float3(2, 2, 0.125f)); + room.Operation = CSGOperationType.Subtractive; + Update(); + } + // B1 as on the 4 x 2 wall seen from the front (AWall4x2_TakesThe2To1Tile_UpStaysUp) + AreEqual(new float2(0.5f, 0.75f), UVAt(model, new float3(-2, 0, 0.125f), kFront), "bottom left"); + AreEqual(new float2(1.0f, 0.75f), UVAt(model, new float3(2, 0, 0.125f), kFront), "bottom right"); + AreEqual(new float2(0.5f, 1.0f), UVAt(model, new float3(-2, 2, 0.125f), kFront), "top left"); + } + [Test] public void ADenserWall_HasANarrowerBorder() { diff --git a/Components/Tests/ChiselSubtractiveWorkflowTests.cs b/Components/Tests/ChiselSubtractiveWorkflowTests.cs new file mode 100644 index 00000000..04a6c843 --- /dev/null +++ b/Components/Tests/ChiselSubtractiveWorkflowTests.cs @@ -0,0 +1,1254 @@ +using System; +using System.Collections.Generic; +using Chisel.Core; +using NUnit.Framework; +using Unity.Mathematics; +using UnityEngine; + +namespace Chisel.Components.Tests +{ + // A model with the subtractive workflow draws what it would draw without it, seen from the other side: its + // brushes are the empty space, rooms carved out of solid, seen from inside + [TestFixture] +#if UNITY_6000_7_OR_NEWER + [Unity.Scripting.LifecycleManagement.NoAutoStaticsCleanup] // only a fixed table of generators +#endif + public class ChiselSubtractiveWorkflowTests + { + readonly List roots = new(); + readonly List assets = new(); + + [SetUp] + public void SetUp() + { + if (UnityEngine.Object.FindObjectsByType(FindObjectsInactive.Include).Length > 0) + Assert.Ignore("A Chisel model is loaded; run these in a scene without one"); + } + + [TearDown] + public void TearDown() + { + foreach (var root in roots) + { + if (root) + UnityEngine.Object.DestroyImmediate(root); + } + roots.Clear(); + Update(); + foreach (var asset in assets) + { + if (asset) + UnityEngine.Object.DestroyImmediate(asset); + } + assets.Clear(); + if (paintProfile != null) + { + ChiselPaintProfiles.Unregister(paintProfile); + paintProfile = null; + } + if (UnityEditor.AssetDatabase.IsValidFolder(kAssetFolder)) + UnityEditor.AssetDatabase.DeleteAsset(kAssetFolder); + } + + const string kAssetFolder = "Assets/ChiselSubtractiveWorkflowTests"; + ChiselPaintProfile paintProfile; + + static void Update() + { + for (int i = 0; i < 3; i++) + { + ChiselNodeHierarchyManager.Update(); + ChiselModelManager.Instance.UpdateModels(); + } + } + + static readonly Type[] kGenerators = + { + typeof(ChiselBoxComponent), typeof(ChiselBrushComponent), typeof(ChiselCapsuleComponent), typeof(ChiselCylinderComponent), + typeof(ChiselExtrudedShapeComponent), typeof(ChiselHemisphereComponent), typeof(ChiselLinearStairsComponent), + typeof(ChiselPathedStairsComponent), typeof(ChiselRevolvedShapeComponent), typeof(ChiselSphereComponent), + typeof(ChiselSpiralStairsComponent), typeof(ChiselStadiumComponent), typeof(ChiselTorusComponent) + }; + + ChiselModelComponent Model() + { + var root = new GameObject("subtractive workflow test"); + roots.Add(root); + return root.AddComponent(); + } + + static ChiselGeneratorComponent Add(ChiselModelComponent model, Type type) + { + var go = new GameObject(type.Name); + go.transform.SetParent(model.transform, false); + var generator = (ChiselGeneratorComponent)go.AddComponent(type); + Update(); + return generator; + } + + static ChiselBoxComponent Box(ChiselModelComponent model, float3 min, float3 max, CSGOperationType operation = CSGOperationType.Additive) + { + var box = (ChiselBoxComponent)Add(model, typeof(ChiselBoxComponent)); + if (math.any(min > box.Max)) { box.Max = max; box.Min = min; } + else { box.Min = min; box.Max = max; } + box.Operation = operation; + Update(); + return box; + } + + static void SetSubtractiveWorkflow(ChiselModelComponent model, bool on) + { + model.renderSettings.subtractiveWorkflow = on; + model.SyncModelSettingsStore(); + Update(); + } + + struct Corner + { + public Vector3Int key; + public float3 position, normal; + public float2 uv; + public float4 tangent; + public float4 color; + } + + struct Triangle + { + public Corner a, b, c; + public float3 WindingNormal => math.cross(b.position - a.position, c.position - a.position); + } + + static Vector3Int KeyOf(float3 p) => new(Mathf.RoundToInt(p.x * 10000), Mathf.RoundToInt(p.y * 10000), Mathf.RoundToInt(p.z * 10000)); + + static bool Less(Vector3Int l, Vector3Int r) => l.x != r.x ? l.x < r.x : l.y != r.y ? l.y < r.y : l.z < r.z; + + // The triangle's corners turned round so the smallest is first, keeping their order: the same for the same + // triangle wound the same way, another for it wound the other way + static (Vector3Int, Vector3Int, Vector3Int) WoundKey(Vector3Int a, Vector3Int b, Vector3Int c) + { + if (Less(b, a) && !Less(c, b)) return (b, c, a); + if (Less(c, a) && Less(c, b)) return (c, a, b); + return (a, b, c); + } + + // Every triangle the model draws, in the model's space; with a material, only those drawn with it (decal) or not + static List Drawn(ChiselModelComponent model, Material material = null, bool decal = true) + { + var triangles = new List(); + foreach (var renderable in model.generated.renderables) + { + if (renderable == null || renderable.sharedMesh == null) + continue; + if (material && (renderable.query & SurfaceDestinationFlags.Renderable) == 0) + continue; + var mesh = renderable.sharedMesh; + var positions = mesh.vertices; + var normals = mesh.normals; + var uvs = mesh.uv; + var tangents = mesh.tangents; + var colors = mesh.colors; + Corner CornerOf(int i) => new() + { + key = KeyOf(positions[i]), + position = positions[i], + normal = i < normals.Length ? (float3)normals[i] : float3.zero, + uv = i < uvs.Length ? (float2)uvs[i] : float2.zero, + tangent = i < tangents.Length ? (float4)tangents[i] : float4.zero, + color = i < colors.Length ? (float4)(Vector4)colors[i] : new float4(1) + }; + for (int sub = 0; sub < mesh.subMeshCount; sub++) + { + if (material) + { + var drawnWith = renderable.renderMaterials != null && sub < renderable.renderMaterials.Length && + renderable.renderMaterials[sub] == material; + if (drawnWith != decal) + continue; + } + var indices = mesh.GetTriangles(sub); + for (int t = 0; t + 2 < indices.Length; t += 3) + triangles.Add(new Triangle { a = CornerOf(indices[t]), b = CornerOf(indices[t + 1]), c = CornerOf(indices[t + 2]) }); + } + } + return triangles; + } + + static Dictionary<(Vector3Int, Vector3Int, Vector3Int), List> ByWinding(List triangles, bool reversed) + { + var lookup = new Dictionary<(Vector3Int, Vector3Int, Vector3Int), List>(); + foreach (var triangle in triangles) + { + var key = reversed ? WoundKey(triangle.a.key, triangle.c.key, triangle.b.key) + : WoundKey(triangle.a.key, triangle.b.key, triangle.c.key); + if (!lookup.TryGetValue(key, out var list)) + lookup[key] = list = new List(); + list.Add(triangle); + } + return lookup; + } + + static Corner CornerAt(Triangle triangle, Vector3Int key) + { + if (triangle.a.key == key) return triangle.a; + if (triangle.b.key == key) return triangle.b; + return triangle.c; + } + + // Each drawn triangle the other's turned round: wound the other way, its normals the other way + static void AssertTurnedRound(List without, List with, string what) + { + Assert.That(without.Count, Is.GreaterThan(0), $"{what}: nothing drawn"); + Assert.That(with.Count, Is.EqualTo(without.Count), $"{what}: as many triangles"); + var reversed = ByWinding(without, reversed: true); + foreach (var triangle in with) + { + var key = WoundKey(triangle.a.key, triangle.b.key, triangle.c.key); + Assert.That(reversed.TryGetValue(key, out var matches) && matches.Count > 0, Is.True, + $"{what}: triangle {(Vector3)triangle.a.position} {(Vector3)triangle.b.position} {(Vector3)triangle.c.position} isn't one drawn without the setting, wound the other way"); + var match = matches[matches.Count - 1]; + matches.RemoveAt(matches.Count - 1); + foreach (var corner in new[] { triangle.a, triangle.b, triangle.c }) + { + var other = CornerAt(match, corner.key); + Assert.That(math.distance(corner.normal, -other.normal), Is.LessThan(1e-3f), + $"{what}: the normal at {(Vector3)corner.position} is {(Vector3)corner.normal}, not {(Vector3)(-other.normal)}"); + } + } + } + + // How a triangle's texture lies on it, seen from the side it is drawn on: 1 when its u runs to the right of its v, + // -1 when mirrored, 0 when its uvs don't span it + // The directions u and v grow fastest along a triangle; false when it has no area + static bool UVGradients(Triangle triangle, out float3 gradientU, out float3 gradientV) + { + var n = triangle.WindingNormal; + var e1 = triangle.b.position - triangle.a.position; + var e2 = triangle.c.position - triangle.a.position; + var nn = math.lengthsq(n); + gradientU = gradientV = float3.zero; + if (!(nn > 1e-12f)) + return false; + float3 Gradient(float f0, float f1, float f2) => ((f1 - f0) * math.cross(e2, n) + (f2 - f0) * math.cross(n, e1)) / nn; + gradientU = Gradient(triangle.a.uv.x, triangle.b.uv.x, triangle.c.uv.x); + gradientV = Gradient(triangle.a.uv.y, triangle.b.uv.y, triangle.c.uv.y); + return true; + } + + static int TextureHandedness(Triangle triangle) + { + if (!UVGradients(triangle, out var gradientU, out var gradientV)) + return 0; + var n = triangle.WindingNormal; + var nn = math.lengthsq(n); + var turn = math.dot(math.cross(gradientU, gradientV), n); + if (math.abs(turn) < 1e-6f * math.length(gradientU) * math.length(gradientV) * math.sqrt(nn)) + return 0; + return turn > 0 ? 1 : -1; + } + + [TestCaseSource(nameof(kGenerators))] + public void EveryGenerator_IsDrawnTurnedRound(Type type) + { + var model = Model(); + Add(model, type); + var without = Drawn(model); + SetSubtractiveWorkflow(model, true); + AssertTurnedRound(without, Drawn(model), type.Name); + } + + // A texture reads the same way from inside a room as it does from outside a solid: not mirrored + [TestCaseSource(nameof(kGenerators))] + public void EveryGenerator_TextureIsNotMirroredFromInside(Type type) + { + var model = Model(); + Add(model, type); + var without = Drawn(model); + SetSubtractiveWorkflow(model, true); + var mirrored = MirroredAgainst(Drawn(model), without, out var compared); + Assert.That(compared, Is.GreaterThan(0), $"{type.Name}: no textured triangles compared"); + Assert.That(mirrored, Is.Zero, $"{type.Name}: {mirrored} of {compared} triangles have their texture mirrored from inside"); + } + + // Without the setting, the walls of a room a subtractive brush carves out of a solid are that brush's faces seen + // from inside, as a room's are with it: their texture reads as the brush's faces do from outside + [Test] + public void ARoomCarvedOutOfASolid_TextureIsNotMirrored() + { + var outside = Model(); + Box(outside, new float3(1, 1, 1), new float3(3, 2, 3)); + + var carved = Model(); + Box(carved, new float3(0, 0, 0), new float3(4, 3, 4)); + Box(carved, new float3(1, 1, 1), new float3(3, 2, 3), CSGOperationType.Subtractive); + var mirrored = MirroredAgainst(Drawn(carved), Drawn(outside), out var compared); + Assert.That(compared, Is.EqualTo(12), "the room's six walls, two triangles each"); + Assert.That(mirrored, Is.Zero, $"{mirrored} of {compared} triangles of the room have their texture mirrored"); + } + + static void SetUV0(ChiselBoxComponent box, UVMatrix uv0) + { + foreach (var surface in box.SurfaceDefinition.surfaces) + surface.surfaceDetails.UV0 = uv0; + box.OnValidate(); + Update(); + } + + // How many triangles of one model read their texture the other way round than the same face of another + static int MirroredAgainst(List triangles, List reference, out int compared) + { + var lookup = ByWinding(reference, reversed: true); + var mirrored = 0; + compared = 0; + foreach (var triangle in triangles) + { + var key = WoundKey(triangle.a.key, triangle.b.key, triangle.c.key); + if (!lookup.TryGetValue(key, out var matches) || matches.Count == 0) + continue; + var a = TextureHandedness(matches[0]); + var b = TextureHandedness(triangle); + if (a == 0 || b == 0) + continue; + compared++; + if (a != b) + mirrored++; + } + return mirrored; + } + + // A texture mirrored on purpose, by the surface's uv matrix, is mirrored on the walls of a room too: they read as + // the brush's faces with the same mapping do from outside + [Test] + public void ARoomCarvedOutOfASolid_MirroredOnPurpose_IsMirrored([Values] bool subtractiveWorkflow) + { + var mirror = new UVMatrix(new float4(-1, 0, 0, 0.25f), new float4(0, 1, 0, 0)); + var outside = Model(); + SetUV0(Box(outside, new float3(1, 1, 1), new float3(3, 2, 3)), mirror); + + var carved = Model(); + if (subtractiveWorkflow) + { + SetSubtractiveWorkflow(carved, true); + SetUV0(Box(carved, new float3(1, 1, 1), new float3(3, 2, 3)), mirror); + } else + { + Box(carved, new float3(0, 0, 0), new float3(4, 3, 4)); + SetUV0(Box(carved, new float3(1, 1, 1), new float3(3, 2, 3), CSGOperationType.Subtractive), mirror); + } + var mirrored = MirroredAgainst(Drawn(carved), Drawn(outside), out var compared); + Assert.That(compared, Is.EqualTo(12), "the room's six walls, two triangles each"); + Assert.That(mirrored, Is.Zero, $"{mirrored} of {compared} triangles of the room don't read as the mirrored box does from outside"); + } + + // A face's tangent runs the way its u does and its bitangent the way its v does, so normal maps light it the + // right way: on the walls of a room as on the outside of a solid + [Test] + public void ARoom_TangentsFollowItsTexture([Values] bool subtractiveWorkflow) + { + var model = Model(); + if (subtractiveWorkflow) + { + SetSubtractiveWorkflow(model, true); + Box(model, new float3(1, 1, 1), new float3(3, 2, 3)); + } else + { + Box(model, new float3(0, 0, 0), new float3(4, 3, 4)); + Box(model, new float3(1, 1, 1), new float3(3, 2, 3), CSGOperationType.Subtractive); + } + var checkedCorners = 0; + foreach (var triangle in Drawn(model)) + { + var middle = (triangle.a.position + triangle.b.position + triangle.c.position) / 3; + if (math.any(middle < 1 - 1e-3f) || math.any(middle > new float3(3, 2, 3) + 1e-3f)) + continue; // the outside of the solid + Assert.That(UVGradients(triangle, out var gradientU, out var gradientV), Is.True); + foreach (var corner in new[] { triangle.a, triangle.b, triangle.c }) + { + var tangent = corner.tangent.xyz; + var bitangent = math.cross(corner.normal, tangent) * corner.tangent.w; + Assert.That(math.dot(tangent, gradientU), Is.GreaterThan(0), $"the tangent at {(Vector3)corner.position} of the wall at {(Vector3)middle} runs against u"); + Assert.That(math.dot(bitangent, gradientV), Is.GreaterThan(0), $"the bitangent at {(Vector3)corner.position} of the wall at {(Vector3)middle} runs against v"); + checkedCorners++; + } + } + Assert.That(checkedCorners, Is.EqualTo(36), "the room's twelve triangles"); + } + + public enum Floor { OfASolid, OfACarvedRoom, OfASubtractiveWorkflowRoom } + + // A floor at y = 0 from (0, 0) to (4, 4), facing up: the top of a solid, or the floor of a room 3 high + ChiselModelComponent FloorModel(Floor floor) + { + var model = Model(); + switch (floor) + { + case Floor.OfASolid: + Box(model, new float3(0, -1, 0), new float3(4, 0, 4)); + break; + case Floor.OfACarvedRoom: + Box(model, new float3(-1, -1, -1), new float3(5, 4, 5)); + Box(model, new float3(0, 0, 0), new float3(4, 3, 4), CSGOperationType.Subtractive); + break; + case Floor.OfASubtractiveWorkflowRoom: + SetSubtractiveWorkflow(model, true); + Box(model, new float3(0, 0, 0), new float3(4, 3, 4)); + break; + } + return model; + } + + // A 1 x 1 opaque decal above the floor's middle, looking down; an omni-directional one reaches half a metre + Material Decal(ChiselModelComponent model, ChiselDecalProjection projection) + { + var material = new Material(Shader.Find("Standard")) { name = "decal" }; + assets.Add(material); + var go = new GameObject("decal"); + go.transform.SetParent(model.transform, false); + go.transform.localPosition = new Vector3(2, 0.2f, 2); + go.transform.localRotation = Quaternion.LookRotation(Vector3.down, Vector3.forward); + var decal = go.AddComponent(); + decal.Material = material; + decal.Transparent = false; + var settings = decal.Settings; + settings.projection = projection; + decal.Settings = settings; + decal.Size = new Vector3(1, 1, 1); + Update(); + return material; + } + + static double AreaFacingUp(List triangles) + { + double area = 0; + foreach (var triangle in triangles) + { + var normal = triangle.WindingNormal; + if (math.normalizesafe(normal).y > 0.99f) + area += math.length(normal) * 0.5; + } + return area; + } + + // How the decal's image lies on the floor: the same handedness on every triangle of it, 0 when they differ + static int DecalHandedness(List triangles) + { + var handedness = 0; + foreach (var triangle in triangles) + { + var h = TextureHandedness(triangle); + if (h == 0) + continue; + if (handedness == 0) + handedness = h; + else if (h != handedness) + return 0; + } + return handedness; + } + + // A decal on the floor of a room, seen from inside, is its whole image, and reads as on the top of a solid + [Test] + public void ADecalOnARoomsFloor_IsItsWholeImage_NotMirrored([Values(ChiselDecalProjection.Orthographic, ChiselDecalProjection.Omni)] ChiselDecalProjection projection, + [Values(Floor.OfACarvedRoom, Floor.OfASubtractiveWorkflowRoom)] Floor floor) + { + var solid = FloorModel(Floor.OfASolid); + var onSolid = Drawn(solid, Decal(solid, projection)); + var expected = DecalHandedness(onSolid); + Assume.That(AreaFacingUp(onSolid), Is.EqualTo(1).Within(1e-3), "on the solid"); + Assume.That(expected, Is.Not.Zero, "on the solid"); + + var room = FloorModel(floor); + var inRoom = Drawn(room, Decal(room, projection)); + Assert.That(AreaFacingUp(inRoom), Is.EqualTo(1).Within(1e-3), "the whole image on the floor"); + Assert.That(DecalHandedness(inRoom), Is.EqualTo(expected), "read as on the solid (0: some of it mirrored)"); + } + + // An omni-directional decal lies with its image's right along the floor's texture, as the floor is seen + [Test] + public void AnOmniDecalOnAFloor_RunsAlongItsTexture([Values] Floor floor) + { + var model = FloorModel(floor); + var material = Decal(model, ChiselDecalProjection.Omni); + var decalU = float3.zero; + foreach (var triangle in Drawn(model, material)) + { + if (UVGradients(triangle, out var gradientU, out _)) + decalU += math.normalizesafe(gradientU); + } + var floorU = float3.zero; + foreach (var triangle in Drawn(model, material, decal: false)) + { + if (math.normalizesafe(triangle.WindingNormal).y > 0.99f && math.abs(triangle.a.position.y) < 1e-4f && + UVGradients(triangle, out var gradientU, out _)) + floorU += math.normalizesafe(gradientU); + } + Assert.That(math.lengthsq(decalU), Is.GreaterThan(0), "the decal is drawn"); + Assert.That(math.lengthsq(floorU), Is.GreaterThan(0), "the floor is drawn"); + Assert.That(math.dot(math.normalize(decalU), math.normalize(floorU)), Is.GreaterThan(0.999f), + $"the decal's right {(Vector3)math.normalize(decalU)} isn't the floor texture's {(Vector3)math.normalize(floorU)}"); + } + + static readonly string[] kRooms = + { + "a box", "a cylinder", "a sphere", "linear stairs", "a cylinder smoothed by the model's angle", + "a double sided box", "a box with a texture twice as wide as high", "a box with a painted floor", "a box with a displaced floor", + "a box with a hotspot material", "a box with a trim along the floor's edge" + }; + + // The surface of a box whose plane faces this way + static int SurfaceFacing(ChiselGeneratorComponent box, float3 normal) + { + Update(); + var brush = (CSGTreeBrush)box.TopTreeNode; + ref var mesh = ref BrushMeshManager.GetBrushMeshBlob(brush.BrushMesh).Value; + for (int s = 0; s < mesh.polygons.Length; s++) + { + if (math.dot(math.normalize(mesh.localPlanes[s].xyz), normal) > 0.999f) + return mesh.polygons[s].descriptionIndex; + } + Assert.Fail($"the box has no surface facing {normal}"); + return -1; + } + + Material AssetMaterial(string name) + { + if (!UnityEditor.AssetDatabase.IsValidFolder(kAssetFolder)) + UnityEditor.AssetDatabase.CreateFolder("Assets", kAssetFolder.Substring("Assets/".Length)); + var material = new Material(ChiselProjectSettings.DefaultWallMaterial); + UnityEditor.AssetDatabase.CreateAsset(material, UnityEditor.AssetDatabase.GenerateUniqueAssetPath($"{kAssetFolder}/{name}.mat")); + return material; + } + + static HotspotTile Tile(int id, int x, int y, int w, int h) => + new() { id = id, name = $"T{id}", points = new[] { new Vector2Int(x, y), new Vector2Int(x + w, y), new Vector2Int(x + w, y + h), new Vector2Int(x, y + h) } }; + + // The surface of a box whose plane faces down: a room's floor + static int FloorOf(ChiselGeneratorComponent box) + { + Update(); + var brush = (CSGTreeBrush)box.TopTreeNode; + ref var mesh = ref BrushMeshManager.GetBrushMeshBlob(brush.BrushMesh).Value; + for (int s = 0; s < mesh.polygons.Length; s++) + { + if (math.normalize(mesh.localPlanes[s].xyz).y < -0.999f) + return mesh.polygons[s].descriptionIndex; + } + Assert.Fail("the box has no floor"); + return -1; + } + + void SetMaterial(ChiselGeneratorComponent generator, Material material) + { + foreach (var surface in generator.SurfaceDefinition.surfaces) + surface.SetMaterial(material); + } + + // The same room built either way: a brush of a model with the subtractive workflow, or a subtractive brush in a solid + ChiselModelComponent RoomModel(string room, bool subtractiveWorkflow) + { + var model = Model(); + if (subtractiveWorkflow) + SetSubtractiveWorkflow(model, true); + else + Box(model, new float3(-6), new float3(6)); + var type = room switch + { + "a cylinder" or "a cylinder smoothed by the model's angle" => typeof(ChiselCylinderComponent), + "a sphere" => typeof(ChiselSphereComponent), + "linear stairs" => typeof(ChiselLinearStairsComponent), + _ => typeof(ChiselBoxComponent) + }; + var generator = Add(model, type); + generator.Operation = subtractiveWorkflow ? CSGOperationType.Additive : CSGOperationType.Subtractive; + if (generator is ChiselBoxComponent box) + { + box.Min = new float3(-1, 0, -1); + box.Max = new float3(1, 2, 1); + } + switch (room) + { + case "a cylinder smoothed by the model's angle": + ((ChiselCylinderComponent)generator).SmoothingGroup = 0; + model.renderSettings.normalSmoothing = true; + model.renderSettings.normalSmoothingAngle = 45; + model.SyncModelSettingsStore(); + break; + case "a double sided box": + { + var material = AssetMaterial("double sided"); + material.AddMetadataOfType().outputFlags = SurfaceOutputFlags.DoubleSided; + SetMaterial(generator, material); + break; + } + case "a box with a hotspot material": + { + var layout = ScriptableObject.CreateInstance(); + assets.Add(layout); + layout.size = new Vector2Int(1024, 1024); + layout.pixelsPerUnit = 256; + layout.tiles = new List { Tile(1, 0, 0, 512, 512), Tile(2, 512, 0, 512, 256), Tile(3, 0, 512, 1024, 512) }; + var material = AssetMaterial("hotspot"); + material.AddMetadataOfType().hotspotLayout = layout; + SetMaterial(generator, material); + break; + } + case "a box with a trim along the floor's edge": + { + var material = new Material(Shader.Find("Standard")) { name = "trim" }; + assets.Add(material); + generator.OnValidate(); + var go = new GameObject("Trim"); + go.transform.SetParent(model.transform, false); + var trim = go.AddComponent(); + trim.Material = material; + trim.Shape = ChiselDecalShape.Trim; + trim.Size = new Vector3(1, 0.5f, 1); + trim.Transparent = false; + trim.SetTargets(new[] + { + new ChiselDecalSurfaceTarget { brush = generator, surfaceIndex = SurfaceFacing(generator, new float3(0, -1, 0)) }, + new ChiselDecalSurfaceTarget { brush = generator, surfaceIndex = SurfaceFacing(generator, new float3(-1, 0, 0)) } + }); + break; + } + case "a box with a texture twice as wide as high": + { + var texture = new Texture2D(256, 128); + assets.Add(texture); + var material = new Material(ChiselProjectSettings.DefaultWallMaterial) { mainTexture = texture }; + assets.Add(material); + ChiselTextureScale.Refresh(null); + SetMaterial(generator, material); + break; + } + case "a box with a painted floor": + { + var material = new Material(Shader.Find("Universal Render Pipeline/Lit")) { name = "paint" }; + assets.Add(material); + if (paintProfile == null) + { + paintProfile = new ChiselPaintProfile { shader = material.shader }; + paintProfile.modes.Add(ChiselPaintMode.Color("Color")); + ChiselPaintProfiles.Register(paintProfile); + } + SetMaterial(generator, material); + generator.OnValidate(); + var paint = ChiselSurfacePaint.Create(FloorOf(generator), ChiselPaintAttribute.Color, ChiselPaintComponents.XYZW, Vector4.one, + new Vector3(-1, 0, -1), Vector3.right, Vector3.forward, new Vector2Int(3, 3)); + paint[0, 0] = new Vector4(1, 0, 0, 1); + paint[2, 0] = new Vector4(0, 1, 0, 1); + paint[1, 2] = new Vector4(0, 0, 1, 1); + ((ChiselBoxComponent)generator).SetSurfacePaint(paint); + break; + } + case "a box with a displaced floor": + { + // a bump in its middle + var grid = ChiselSurfacePaint.Create(FloorOf(generator), ChiselPaintAttribute.Color, ChiselPaintComponents.X, Vector4.zero, + new Vector3(-1, 0, -1), Vector3.right, Vector3.forward, new Vector2Int(3, 3)); + grid[1, 1] = new Vector4(0.3f, 0, 0, 0); + ((ChiselBoxComponent)generator).SetSurfaceDisplacement(grid); + break; + } + } + generator.OnValidate(); + Update(); + return model; + } + + // Inside, a room is drawn the same either way: the same triangles, wound the same way, with the same normals, + // uvs, tangents and colors. Only the solid's outside is drawn besides, carved out of it + [TestCaseSource(nameof(kRooms))] + public void ARoom_IsDrawnAsTheSameRoomCarvedOutOfASolid(string room) + { + var carved = Drawn(RoomModel(room, subtractiveWorkflow: false)); + var inside = Drawn(RoomModel(room, subtractiveWorkflow: true)); + Assert.That(inside.Count, Is.GreaterThan(0), "the room is drawn"); + Assert.That(carved.Count - inside.Count, Is.EqualTo(12), "the carved room has the solid's six outside faces besides"); + // what is compared is there + if (room == "a box with a painted floor") + Assert.That(inside.Exists(t => math.any(t.a.color != new float4(1)) || math.any(t.b.color != new float4(1)) || math.any(t.c.color != new float4(1))), + Is.True, "the floor is painted"); + if (room == "a double sided box") + Assert.That(inside.Count, Is.GreaterThanOrEqualTo(24), "the walls are drawn from behind too"); + if (room == "a box with a hotspot material") + Assert.That(inside.TrueForAll(t => math.all(t.a.uv >= -1e-4f & t.a.uv <= 1 + 1e-4f)), Is.True, "the walls are mapped by the layout's tiles"); + if (room == "a box with a trim along the floor's edge") + Assert.That(inside.Count, Is.GreaterThan(12), "the trim is drawn"); + if (room == "a box with a displaced floor") + Assert.That(inside.Exists(t => math.abs(t.a.position.y) > 0.1f && math.abs(t.a.position.y) < 0.5f), Is.True, "the floor has its bump"); + var lookup = ByWinding(carved, reversed: false); + foreach (var triangle in inside) + { + var key = WoundKey(triangle.a.key, triangle.b.key, triangle.c.key); + Assert.That(lookup.TryGetValue(key, out var matches) && matches.Count > 0, Is.True, + $"{room}: the triangle {(Vector3)triangle.a.position} {(Vector3)triangle.b.position} {(Vector3)triangle.c.position} isn't drawn in the carved room"); + var match = matches[matches.Count - 1]; + matches.RemoveAt(matches.Count - 1); + foreach (var corner in new[] { triangle.a, triangle.b, triangle.c }) + { + var other = CornerAt(match, corner.key); + var at = (Vector3)corner.position; + Assert.That(math.distance(corner.normal, other.normal), Is.LessThan(1e-3f), $"{room}: the normal at {at}: {(Vector3)corner.normal}, carved {(Vector3)other.normal}"); + Assert.That(math.distance(corner.uv, other.uv), Is.LessThan(1e-3f), $"{room}: the uv at {at}: {(Vector2)corner.uv}, carved {(Vector2)other.uv}"); + Assert.That(math.distance(corner.tangent, other.tangent), Is.LessThan(1e-3f), $"{room}: the tangent at {at}: {(Vector4)corner.tangent}, carved {(Vector4)other.tangent}"); + Assert.That(math.distance(corner.color, other.color), Is.LessThan(1e-3f), $"{room}: the color at {at}: {(Vector4)corner.color}, carved {(Vector4)other.color}"); + } + } + } + + // The area of the triangles facing up at height y + static double AreaFacingUpAt(List triangles, float y) + { + double area = 0; + foreach (var triangle in triangles) + { + var normal = triangle.WindingNormal; + if (math.normalizesafe(normal).y > 0.99f && math.abs(triangle.a.position.y - y) < 1e-3f) + area += math.length(normal) * 0.5; + } + return area; + } + + // A shape drawn on a room's floor, made into a brush: pulled out of the floor it is a pillar, pushed into it a pit, + // in the subtractive workflow as in a room carved out of a solid + [Test] + public void AShapeOnARoomsFloor_ExtrudedIntoABrush_IsAPillarOrAPit([Values(0.5f, -0.25f)] float height, + [Values(Floor.OfACarvedRoom, Floor.OfASubtractiveWorkflowRoom)] Floor floor) + { + var model = FloorModel(floor); + var boxes = model.GetComponentsInChildren(); + var room = boxes[boxes.Length - 1]; + var material = new Material(ChiselProjectSettings.DefaultWallMaterial); + assets.Add(material); + var square = new[] { new Vector3(1.5f, 0, 1.5f), new Vector3(2.5f, 0, 1.5f), new Vector3(2.5f, 0, 2.5f), new Vector3(1.5f, 0, 2.5f) }; + var decal = ChiselDecalComponent.CreateOnSurface(room, FloorOf(room), material, Vector3.up, square); + Assert.That(decal, Is.Not.Null); + var extruded = decal.ExtrudeIntoBrush(height); + Assert.That(extruded, Is.Not.Null); + UnityEngine.Object.DestroyImmediate(decal.gameObject); + Update(); + + var drawn = Drawn(model); + Assert.That(AreaFacingUpAt(drawn, height), Is.EqualTo(1).Within(1e-4), height > 0 ? "the pillar's top" : "the pit's floor"); + Assert.That(AreaFacingUpAt(drawn, 0), Is.EqualTo(16 - 1).Within(1e-4), "the floor round it"); + } + + // A ray from inside a room finds its floor: the room's brush, with the plane facing back up into the room. From below + // the floor, its back faces left out, it finds nothing of it. Inside one of the floor's triangles, or on the edge + // between two of them (its diagonal) + [Test] + public void ARoomsFloor_IsFoundFromInside_NotFromBehind([Values] Floor floor, [Values] bool onTheDiagonal) + { + var model = FloorModel(floor); + var boxes = model.GetComponentsInChildren(); + var room = boxes[boxes.Length - 1]; + + var at = onTheDiagonal ? new Vector3(2, 0, 2) : new Vector3(1.3f, 0, 2.6f); + var found = new List(); + Assert.That(ChiselSceneQuery.FindFirstWorldIntersection(found, at + Vector3.up, at + Vector3.down * 0.5f, ignoreBackfaced: true), Is.True, + "the floor is found from inside"); + var nearest = found[0]; + foreach (var intersection in found) + { + if (intersection.brushIntersection.surfaceIntersection.distance < nearest.brushIntersection.surfaceIntersection.distance) + nearest = intersection; + } + Assert.That(nearest.treeNode, Is.EqualTo(room), "the room's brush"); + Assert.That(nearest.worldPlaneIntersection.y, Is.EqualTo(0).Within(1e-4f), "on the floor"); + Assert.That(nearest.worldPlane.normal.y, Is.EqualTo(1).Within(1e-4f), "facing up into the room"); + + found.Clear(); + ChiselSceneQuery.FindFirstWorldIntersection(found, at + Vector3.down * 0.5f, at + Vector3.up, ignoreBackfaced: true); + Assert.That(found.Exists(intersection => intersection.treeNode == room), Is.False, "the floor isn't found from behind"); + } + + // The floor's corners, each with the uv it is drawn with + static List<(float3 position, float2 uv)> FloorUVs(ChiselModelComponent model) + { + var found = new List<(float3, float2)>(); + foreach (var triangle in Drawn(model)) + { + if (math.normalizesafe(triangle.WindingNormal).y < 0.99f || math.abs(triangle.a.position.y) > 1e-4f) + continue; + foreach (var corner in new[] { triangle.a, triangle.b, triangle.c }) + found.Add((corner.position, corner.uv)); + } + return found; + } + + // The uv the floor is drawn with at a point on it, from a triangle of it: the mapping is the same all over it + static float2 FloorUVAt(List floor, float3 point) + { + var triangle = floor[0]; + Assert.That(UVGradients(triangle, out var gradientU, out var gradientV), Is.True); + var offset = point - triangle.a.position; + return triangle.a.uv + new float2(math.dot(gradientU, offset), math.dot(gradientV, offset)); + } + + // The texture moved or turned by the uv tools on a room's floor moves as it is seen, as on the top of a solid: what is + // drawn at a point afterwards is what was drawn where the move takes it + [Test] + public void ATextureMovedOnAFloor_MovesAsItIsSeen([Values] Floor floor, [Values] bool turned) + { + var model = FloorModel(floor); + var boxes = model.GetComponentsInChildren(); + var box = boxes[boxes.Length - 1]; + var before = Drawn(model).FindAll(t => math.normalizesafe(t.WindingNormal).y > 0.99f && math.abs(t.a.position.y) < 1e-4f); + Assert.That(before, Is.Not.Empty, "the floor is drawn"); + + var brush = (CSGTreeBrush)box.TopTreeNode; + ref var mesh = ref BrushMeshManager.GetBrushMeshBlob(brush.BrushMesh).Value; + var surfaceIndex = -1; + for (int s = 0; s < mesh.localPlanes.Length && surfaceIndex < 0; s++) + { + if (math.abs(math.normalize(mesh.localPlanes[s].xyz).y) > 0.999f && math.abs(mesh.localPlanes[s].w) < 1e-4f) + surfaceIndex = s; + } + Assert.That(surfaceIndex, Is.GreaterThanOrEqualTo(0), "the box has a surface on the floor"); + var surface = new SurfaceReference(box, mesh.polygons[surfaceIndex].descriptionIndex, brush, surfaceIndex); + var move = turned ? Matrix4x4.Translate(new Vector3(2, 0, 2)) * Matrix4x4.Rotate(Quaternion.Euler(0, 30, 0)) * Matrix4x4.Translate(new Vector3(-2, 0, -2)) + : Matrix4x4.Translate(new Vector3(0.3f, 0, 0.7f)); + surface.WorldSpaceTransformUV(move, surface.UV0); + box.OnValidate(); + Update(); + + var after = FloorUVs(model); + Assert.That(after, Is.Not.Empty); + foreach (var (position, uv) in after) + { + var expected = FloorUVAt(before, (float3)move.MultiplyPoint3x4(position)); + Assert.That(math.distance(uv, expected), Is.LessThan(1e-3f), $"at {(Vector3)position}: {(Vector2)uv}, what was drawn where the move takes it {(Vector2)expected}"); + } + } + + static readonly Vector3 kRoomMiddle = new(2, 1.5f, 2); + static readonly Vector3[] kDirections = { Vector3.left, Vector3.right, Vector3.down, Vector3.up, Vector3.back, Vector3.forward }; + + // From the middle of a room, every way: its wall is hit where it is, its normal facing back into the room + [Test] + public void ARoomsWalls_AreHitFromInside([Values(Floor.OfACarvedRoom, Floor.OfASubtractiveWorkflowRoom)] Floor floor) + { + FloorModel(floor); + Physics.SyncTransforms(); + foreach (var direction in kDirections) + { + Assert.That(Physics.Raycast(kRoomMiddle, direction, out var hit, 10), Is.True, $"nothing hit going {direction}"); + var expected = Vector3.Dot(direction, Vector3.one) > 0 ? Vector3.Dot(new Vector3(4, 3, 4), direction) : 0; + Assert.That(Vector3.Dot(hit.point, direction), Is.EqualTo(expected).Within(1e-3f), $"the wall {direction} is hit at {hit.point}"); + Assert.That(Vector3.Dot(hit.normal, -direction), Is.GreaterThan(0.999f), $"the wall {direction} faces {hit.normal}"); + } + } + + // Something moving inside a room stops at its walls and floor + [Test] + public void ACharacterInARoom_StopsAtItsWalls([Values(Floor.OfACarvedRoom, Floor.OfASubtractiveWorkflowRoom)] Floor floor) + { + var model = FloorModel(floor); + var go = new GameObject("character"); + roots.Add(go); + go.transform.position = kRoomMiddle; + var character = go.AddComponent(); + character.radius = 0.25f; + character.height = 1; + Physics.SyncTransforms(); + // it keeps its skin width away from what it touches + var skin = character.skinWidth; + character.Move(new Vector3(0, -5, 0)); + Assert.That(go.transform.position.y, Is.EqualTo(0.5f + skin).Within(0.02f), "stands on the floor"); + character.Move(new Vector3(10, 0, 0)); + Assert.That(go.transform.position.x, Is.EqualTo(4 - 0.25f - skin).Within(0.02f), "stops at the wall"); + character.Move(new Vector3(0, 0, -10)); + Assert.That(go.transform.position.z, Is.EqualTo(0.25f + skin).Within(0.02f), "stops at the other wall"); + } + + // How bright what the camera sees is, on average (0 to 1) + static float Brightness(Camera camera) + { + const int kSize = 32; + var target = RenderTexture.GetTemporary(kSize, kSize, 24); + var image = new Texture2D(kSize, kSize, TextureFormat.RGBA32, false); + var active = RenderTexture.active; + try + { + camera.targetTexture = target; + camera.Render(); + RenderTexture.active = target; + image.ReadPixels(new Rect(0, 0, kSize, kSize), 0, 0); + image.Apply(); + var sum = 0f; + foreach (var color in image.GetPixels()) + sum += color.grayscale; + return sum / (kSize * kSize); + } + finally + { + RenderTexture.active = active; + camera.targetTexture = null; + RenderTexture.ReleaseTemporary(target); + UnityEngine.Object.DestroyImmediate(image); + } + } + + // How much brighter a room's wall, floor or ceiling looks, from its middle looking that way, with a lamp in the + // middle of the room + float LitByALamp(Vector3 looking) => LitByALamp(kRoomMiddle, kRoomMiddle, looking, LightShadows.None); + + float LitByALamp(Vector3 lampAt, Vector3 cameraAt, Vector3 looking, LightShadows shadows) + { + var lampObject = new GameObject("lamp"); + roots.Add(lampObject); + lampObject.transform.position = lampAt; + var lamp = lampObject.AddComponent(); + lamp.type = LightType.Point; + lamp.range = 8; + lamp.intensity = 3; + lamp.shadows = shadows; + + var camera = Looking(roots, cameraAt, looking); + return InTheDark(() => + { + var lit = Brightness(camera); + lamp.enabled = false; + var unlit = Brightness(camera); + return lit - unlit; + }); + } + + // Only the lights of the scene: none from the sky or reflections + static T InTheDark(Func lit) + { + var ambientMode = RenderSettings.ambientMode; + var ambientLight = RenderSettings.ambientLight; + var skybox = RenderSettings.skybox; + var reflectionIntensity = RenderSettings.reflectionIntensity; + try + { + RenderSettings.ambientMode = UnityEngine.Rendering.AmbientMode.Flat; + RenderSettings.ambientLight = Color.black; + RenderSettings.skybox = null; + RenderSettings.reflectionIntensity = 0; + Physics.SyncTransforms(); + return lit(); + } + finally + { + RenderSettings.ambientMode = ambientMode; + RenderSettings.ambientLight = ambientLight; + RenderSettings.skybox = skybox; + RenderSettings.reflectionIntensity = reflectionIntensity; + } + } + + static Camera Looking(List owner, Vector3 at, Vector3 looking) + { + var cameraObject = new GameObject("camera"); + owner.Add(cameraObject); + var up = Mathf.Abs(looking.y) > 0.5f ? Vector3.forward : Vector3.up; + cameraObject.transform.SetPositionAndRotation(at, Quaternion.LookRotation(looking, up)); + var camera = cameraObject.AddComponent(); + camera.enabled = false; + camera.clearFlags = CameraClearFlags.SolidColor; + camera.backgroundColor = Color.black; + camera.nearClipPlane = 0.05f; + camera.farClipPlane = 20; + camera.fieldOfView = 60; + return camera; + } + + static void Lightmapped(ChiselModelComponent model) + { + UnityEditor.GameObjectUtility.SetStaticEditorFlags(model.gameObject, UnityEditor.StaticEditorFlags.ContributeGI); + model.RenderSettings.receiveGI = ReceiveGI.Lightmaps; + model.SyncModelSettingsStore(); + Update(); + } + + static MeshRenderer RendererOf(ChiselModelComponent model) + { + foreach (var renderable in model.generated.renderables) + { + if (renderable != null && renderable.Valid && renderable.HasGeometry && !renderable.debugVisualizationRenderer) + return renderable.meshRenderer; + } + Assert.Fail("the model has no renderer"); + return null; + } + + // How bright the light probes are at a point: their constant term, averaged over red, green and blue + static float ProbeBrightness(Vector3 at) + { + LightProbes.GetInterpolatedProbe(at, null, out var probe); + return (probe[0, 0] + probe[1, 0] + probe[2, 0]) / 3; + } + + // Bakes the lamp, and how bright the camera sees the baked light alone: with the lamp off, as before a bake a baked + // light is drawn live + static float BakedBrightness(Light lamp, Camera camera) + { + lamp.enabled = true; + Assert.That(InTheDark(() => UnityEditor.Lightmapping.Bake()), Is.True, "baking"); + lamp.enabled = false; + return InTheDark(() => Brightness(camera)); + } + + // A lightmapped room with a lamp baked into its middle and light probes round it: how bright its floor looks, and + // the probes are in its middle + (float floor, float probe) Baked(Floor floor, out ChiselModelComponent model, out Camera camera, out Light lamp) + { + model = FloorModel(floor); + Lightmapped(model); + var lampObject = new GameObject("lamp"); + roots.Add(lampObject); + lampObject.transform.position = kRoomMiddle; + lamp = lampObject.AddComponent(); + lamp.type = LightType.Point; + lamp.range = 8; + lamp.intensity = 3; + lamp.lightmapBakeType = LightmapBakeType.Baked; + var probes = lampObject.AddComponent(); + probes.probePositions = new[] { new Vector3(-1, -1, -1), new Vector3(1, -1, -1), new Vector3(-1, -1, 1), new Vector3(1, -1, 1), + new Vector3(-1, 1, -1), new Vector3(1, 1, -1), new Vector3(-1, 1, 1), new Vector3(1, 1, 1) }; + var view = camera = Looking(roots, new Vector3(2, 1, 2), Vector3.down); + + var baked = BakedBrightness(lamp, view); + Assert.That(RendererOf(model).lightmapIndex, Is.GreaterThanOrEqualTo(0), $"{floor} has a lightmap"); + Assert.That(baked, Is.GreaterThan(0.05f), $"the baked lamp lights the floor of {floor}"); + var probe = ProbeBrightness(kRoomMiddle); + Assert.That(probe, Is.GreaterThan(0), $"the light probes in {floor} are lit"); + return (baked, probe); + } + + const string kBakeFolder = "Assets/ChiselBakeTest"; + + // A lamp baked into a room lights its floor and its light probes as in the same room carved out of a solid, and + // after the room is changed, baking again lights it again. Lighting is baked into a saved scene: one of its own, + // in place of the test runner's, which gets an empty one back + [Test] + public void ABakedLamp_LightsARoomAsACarvedOne_AndAgainAfterAnEdit() + { + if (!UnityEditor.AssetDatabase.IsValidFolder(kBakeFolder)) + UnityEditor.AssetDatabase.CreateFolder("Assets", kBakeFolder.Substring("Assets/".Length)); + var scene = UnityEditor.SceneManagement.EditorSceneManager.NewScene(UnityEditor.SceneManagement.NewSceneSetup.EmptyScene, + UnityEditor.SceneManagement.NewSceneMode.Single); + Assume.That(UnityEditor.SceneManagement.EditorSceneManager.SaveScene(scene, kBakeFolder + "/bake.unity"), Is.True, "the scene is saved"); + try + { + BakeTwice(); + } + finally + { + roots.Clear(); + UnityEditor.SceneManagement.EditorSceneManager.NewScene(UnityEditor.SceneManagement.NewSceneSetup.EmptyScene, + UnityEditor.SceneManagement.NewSceneMode.Single); + Update(); + UnityEditor.AssetDatabase.DeleteAsset(kBakeFolder); + } + } + + void BakeTwice() + { + var hadSettings = UnityEditor.Lightmapping.TryGetLightingSettings(out var previousSettings); + var settings = new LightingSettings + { + bakedGI = true, + lightmapResolution = 4, + lightmapPadding = 2, + lightmapMaxSize = 256, + directSampleCount = 8, + indirectSampleCount = 8, + environmentSampleCount = 8, + maxBounces = 1, + ao = false, + directionalityMode = LightmapsMode.NonDirectional, + filteringMode = LightingSettings.FilterMode.None + }; + assets.Add(settings); + try + { + UnityEditor.Lightmapping.lightingSettings = settings; + var carved = Baked(Floor.OfACarvedRoom, out _, out _, out _); + foreach (var root in roots) + UnityEngine.Object.DestroyImmediate(root); + roots.Clear(); + Update(); + UnityEditor.Lightmapping.Clear(); + + var room = Baked(Floor.OfASubtractiveWorkflowRoom, out var model, out var camera, out var lamp); + Assert.That(room.floor, Is.EqualTo(carved.floor).Within(carved.floor * 0.15f), $"the floor: {room.floor}, in the carved room {carved.floor}"); + Assert.That(room.probe, Is.EqualTo(carved.probe).Within(carved.probe * 0.15f), $"the light probes: {room.probe}, in the carved room {carved.probe}"); + + // the room made longer: its lightmap no longer fits, and baking again gives it one that does + var box = model.GetComponentInChildren(); + box.Max = new float3(5, 3, 4); + box.OnValidate(); + Update(); + Assert.That(RendererOf(model).lightmapIndex, Is.EqualTo(-1), "the changed room kept a lightmap that doesn't fit it"); + var again = BakedBrightness(lamp, camera); + Assert.That(RendererOf(model).lightmapIndex, Is.GreaterThanOrEqualTo(0), "the changed room has a lightmap"); + Assert.That(again, Is.EqualTo(room.floor).Within(room.floor * 0.25f), $"the floor after baking again: {again}, before {room.floor}"); + } + finally + { + UnityEditor.Lightmapping.Clear(); + if (hadSettings) + UnityEditor.Lightmapping.lightingSettings = previousSettings; + } + } + + // A lamp in a room lights its walls, floor and ceiling as it does those of the same room carved out of a solid: they + // face it, their normals into the room + [Test] + public void ALampInARoom_LightsItAsInACarvedRoom() + { + var looking = new[] { Vector3.down, Vector3.up, Vector3.left, Vector3.forward }; + var carved = new float[looking.Length]; + FloorModel(Floor.OfACarvedRoom); + for (int i = 0; i < looking.Length; i++) + carved[i] = LitByALamp(looking[i]); + foreach (var root in roots) + UnityEngine.Object.DestroyImmediate(root); + roots.Clear(); + Update(); + + FloorModel(Floor.OfASubtractiveWorkflowRoom); + for (int i = 0; i < looking.Length; i++) + { + Assume.That(carved[i], Is.GreaterThan(0.05f), $"the lamp lights the carved room looking {looking[i]}"); + var lit = LitByALamp(looking[i]); + Assert.That(lit, Is.EqualTo(carved[i]).Within(carved[i] * 0.02f), $"looking {looking[i]}: {lit}, in the carved room {carved[i]}"); + } + } + + // Every triangle's lightmap coordinates (uv2), keyed by its corners wound the other way, model by model + static Dictionary<(Vector3Int, Vector3Int, Vector3Int), Vector2[]> LightmapUVs(ChiselModelComponent model, bool reversed) + { + var found = new Dictionary<(Vector3Int, Vector3Int, Vector3Int), Vector2[]>(); + foreach (var renderable in model.generated.renderables) + { + if (renderable == null || renderable.sharedMesh == null) + continue; + var mesh = renderable.sharedMesh; + var positions = mesh.vertices; + var uv2 = mesh.uv2; + if (uv2.Length != positions.Length) + continue; + var indices = mesh.triangles; + for (int t = 0; t + 2 < indices.Length; t += 3) + { + int a = indices[t], b = indices[t + 1], c = indices[t + 2]; + var key = reversed ? WoundKey(KeyOf(positions[a]), KeyOf(positions[c]), KeyOf(positions[b])) + : WoundKey(KeyOf(positions[a]), KeyOf(positions[b]), KeyOf(positions[c])); + found[key] = new[] { uv2[a], uv2[b], uv2[c] }; + } + } + return found; + } + + static float Area(Vector2[] corners) => Mathf.Abs((corners[1].x - corners[0].x) * (corners[2].y - corners[0].y) - + (corners[2].x - corners[0].x) * (corners[1].y - corners[0].y)) * 0.5f; + + // A room's faces get as much of the lightmap as those of the same room carved out of a solid, inside it + [Test] + public void ARoomsLightmapUVs_AreAsInACarvedRoom() + { + var carved = Model(); + Box(carved, new float3(0, 0, 0), new float3(4, 3, 4)); + var outside = LightmapUVs(carved, reversed: true); + Assume.That(outside.Count, Is.EqualTo(12), "the box's twelve triangles have lightmap coordinates"); + + SetSubtractiveWorkflow(carved, true); + var inside = LightmapUVs(carved, reversed: false); + Assert.That(inside.Count, Is.EqualTo(12), "the room's twelve triangles have lightmap coordinates"); + foreach (var pair in inside) + { + Assert.That(outside.TryGetValue(pair.Key, out var before), Is.True, "a triangle of the room is the box's turned round"); + foreach (var uv in pair.Value) + Assert.That(uv.x >= 0 && uv.x <= 1 && uv.y >= 0 && uv.y <= 1, Is.True, $"{uv} is outside the lightmap"); + Assert.That(Area(pair.Value), Is.EqualTo(Area(before)).Within(Area(before) * 1e-3f), "as much of the lightmap"); + } + } + + // A pillar between a lamp and the floor shadows it, in the subtractive workflow (a subtractive brush in the room) as + // in a room carved out of a solid (an additive brush in it) + [Test] + public void APillarInARoom_ShadowsTheFloorFromALamp([Values(Floor.OfACarvedRoom, Floor.OfASubtractiveWorkflowRoom)] Floor floor) + { + var model = FloorModel(floor); + Box(model, new float3(2, 0, 1.5f), new float3(2.5f, 3, 2.5f), + floor == Floor.OfASubtractiveWorkflowRoom ? CSGOperationType.Subtractive : CSGOperationType.Additive); + var lampAt = new Vector3(1, 1.5f, 2); + var cameraAt = new Vector3(3.3f, 1, 2); + var unshadowed = LitByALamp(lampAt, cameraAt, Vector3.down, LightShadows.None); + Assume.That(unshadowed, Is.GreaterThan(0.05f), "the lamp lights the floor without shadows"); + var shadowed = LitByALamp(lampAt, cameraAt, Vector3.down, LightShadows.Hard); + Assert.That(shadowed, Is.LessThan(unshadowed * 0.2f), $"the pillar doesn't shadow the floor: {shadowed} with shadows, {unshadowed} without"); + } + + static readonly string[] kScenes = { "two overlapping rooms", "a room with a pillar", "two rooms side by side", "a room in a room" }; + + static void Build(ChiselModelComponent model, string scene) + { + switch (scene) + { + case "two overlapping rooms": + Box(model, new float3(0, 0, 0), new float3(4, 3, 4)); + Box(model, new float3(2, 0, 2), new float3(6, 2, 6)); + break; + case "a room with a pillar": + Box(model, new float3(0, 0, 0), new float3(6, 3, 6)); + Box(model, new float3(2, 0, 2), new float3(3, 3, 3), CSGOperationType.Subtractive); + break; + case "two rooms side by side": + Box(model, new float3(0, 0, 0), new float3(4, 3, 4)); + Box(model, new float3(4, 0, 1), new float3(8, 2, 3)); + break; + case "a room in a room": + Box(model, new float3(0, 0, 0), new float3(6, 3, 6)); + Box(model, new float3(1, 1, 1), new float3(2, 2, 2)); + break; + } + } + + [TestCaseSource(nameof(kScenes))] + public void CarvedRooms_AreDrawnTurnedRound(string scene) + { + var model = Model(); + Build(model, scene); + var without = Drawn(model); + SetSubtractiveWorkflow(model, true); + AssertTurnedRound(without, Drawn(model), scene); + } + + // Every face of a room faces into it, and its normals do too + [Test] + public void ARoom_FacesInward() + { + var model = Model(); + SetSubtractiveWorkflow(model, true); + Box(model, new float3(-2, -1, -3), new float3(2, 1, 3)); + var triangles = Drawn(model); + Assert.That(triangles.Count, Is.EqualTo(12), "a box's six faces, two triangles each"); + foreach (var triangle in triangles) + { + var middle = (triangle.a.position + triangle.b.position + triangle.c.position) / 3; + Assert.That(math.dot(triangle.WindingNormal, -middle), Is.GreaterThan(0), $"the triangle at {(Vector3)middle} faces out"); + foreach (var corner in new[] { triangle.a, triangle.b, triangle.c }) + Assert.That(math.dot(corner.normal, -middle), Is.GreaterThan(0), $"the normal at {(Vector3)corner.position} of the face at {(Vector3)middle} points out"); + } + } + + // Turning the setting on and off again draws what was drawn before, and is noticed each time + [Test] + public void TurningTheSettingOnAndOff_RebuildsTheModel() + { + var model = Model(); + Build(model, "a room with a pillar"); + var before = Drawn(model); + SetSubtractiveWorkflow(model, true); + var on = Drawn(model); + AssertTurnedRound(before, on, "turned on"); + SetSubtractiveWorkflow(model, false); + AssertTurnedRound(on, Drawn(model), "turned off again"); + } + } +} diff --git a/Components/Tests/ChiselSubtractiveWorkflowTests.cs.meta b/Components/Tests/ChiselSubtractiveWorkflowTests.cs.meta new file mode 100644 index 00000000..9d8b9ec5 --- /dev/null +++ b/Components/Tests/ChiselSubtractiveWorkflowTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: b7825575d1fb73f4d824a88b8230806b \ No newline at end of file diff --git a/Components/Tests/ChiselTextureScaleTests.cs b/Components/Tests/ChiselTextureScaleTests.cs index 012fad12..fd462733 100644 --- a/Components/Tests/ChiselTextureScaleTests.cs +++ b/Components/Tests/ChiselTextureScaleTests.cs @@ -306,11 +306,13 @@ public void MovingTheTexture_MovesItAsItIsSeen() Assert.That(math.distance(drawnAfter, drawnBefore), Is.LessThan(1e-5f)); } - // Locking the texture to the object or the world doesn't change how it looks now + // Locking the texture to the object or the world doesn't change how it looks now, on faces seen from inside too [Test] - public void ToggledTextureLock_LooksTheSame() + public void ToggledTextureLock_LooksTheSame([Values] bool subtractiveWorkflow) { var model = Model(); + model.renderSettings.subtractiveWorkflow = subtractiveWorkflow; + model.SyncModelSettingsStore(); var material = MaterialWith(Texture(256, 64)); var box = Box(model, material); box.transform.SetPositionAndRotation(new Vector3(2.3f, 0.7f, -1.1f), Quaternion.Euler(0, 30, 0)); diff --git a/Components/Tests/StagedInputHashTests.cs b/Components/Tests/StagedInputHashTests.cs index 3051311f..4557b7f3 100644 --- a/Components/Tests/StagedInputHashTests.cs +++ b/Components/Tests/StagedInputHashTests.cs @@ -219,6 +219,16 @@ public void ADifferentModelSetting_IsAChange() }); } + [Test] + public void TheSubtractiveWorkflow_IsAChange() + { + AssertBothAgree("turning on the model's subtractive workflow", () => + { + model.renderSettings.subtractiveWorkflow = true; + model.SyncModelSettingsStore(); + }); + } + // What a brush is made of is an index into the contents list, and a project may only have the one it starts // with, so this only requires the two hashes to agree [Test] diff --git a/Core/2.Processing/Algorithms/MeshAlgorithms.cs b/Core/2.Processing/Algorithms/MeshAlgorithms.cs index 49d6e022..7763257f 100644 --- a/Core/2.Processing/Algorithms/MeshAlgorithms.cs +++ b/Core/2.Processing/Algorithms/MeshAlgorithms.cs @@ -102,6 +102,37 @@ public static void ComputeUVs(NativeList vertices, float4x4 uv0Mat } } + /// + /// A face drawn turned round is seen from behind its brush's plane, where the uvs its surface gives read mirrored + /// left to right: its u is negated, so by default it reads as the face does from the front. Being the same for + /// every mapping, it keeps what the uvs match (texture lock, the uv tools), and a mirror in the surface's own uv + /// matrix still mirrors it. + /// + public static float4x4 TurnedUVMatrix(float4x4 uvMatrix) + { + uvMatrix.c0.x = -uvMatrix.c0.x; + uvMatrix.c1.x = -uvMatrix.c1.x; + uvMatrix.c2.x = -uvMatrix.c2.x; + uvMatrix.c3.x = -uvMatrix.c3.x; + return uvMatrix; + } + + /// + /// Turns the uvs of the vertices drawn turned round, whose normals face away from frontNormal (the brush plane's), + /// as turns their mapping. + /// + public static void TurnUVs(NativeList vertices, float3 frontNormal) + { + for (int i = 0; i < vertices.Length; i++) + { + var vertex = vertices[i]; + if (math.dot(vertex.normal, frontNormal) >= 0) + continue; + vertex.uv0.x = -vertex.uv0.x; + vertices[i] = vertex; + } + } + /// /// The axes a surface's lightmap chart lies along in its plane. They follow the world: a floor's run along x and z, a /// wall's along the ground and up, so the texels of a surface in an axis' plane line up with its edges, and surfaces in @@ -138,28 +169,36 @@ public static void ComputeLightmapCoordinates(NativeList vertices, /// bitangent the same for v, for the affine mapping uv = uvMatrix * position. Every triangle of the surface gives /// that same answer - except one as thin as a float step, whose corners round to one point, which gives NaN. The /// exact CSG draws such triangles where brushes meet a hair out of line, and a NaN tangent lights its surface NaN. - /// Each vertex's tangent is made perpendicular to its own normal, which normal smoothing may have turned. + /// Each vertex's tangent is made perpendicular to its own normal, which normal smoothing may have turned. The vertices + /// drawn turned round, whose normals face away from frontNormal, take the mapping turnedUVMatrix gives them. /// - public static void ComputeTangents(NativeList vertices, float3 planeNormal, float4x4 uvMatrix) + public static void ComputeTangents(NativeList vertices, float3 planeNormal, float4x4 uvMatrix, float4x4 turnedUVMatrix, float3 frontNormal) { - // u = dot(a, position) + ..., v = dot(b, position) + ...: rows 0 and 1 of the mapping var n = math.normalizesafe((double3)planeNormal); - var a = new double3(uvMatrix.c0.x, uvMatrix.c1.x, uvMatrix.c2.x); - var b = new double3(uvMatrix.c0.y, uvMatrix.c1.y, uvMatrix.c2.y); - // In the plane: a.T = 1, b.T = 0 and a.B = 0, b.B = 1, solved by T = (b x n) / det, B = (n x a) / det - var determinant = math.dot(n, math.cross(a, b)); - var mapped = determinant != 0 && math.isfinite(determinant); - var tangent = mapped ? math.cross(b, n) / determinant : double3.zero; - var bitangent = mapped ? math.cross(n, a) / determinant : double3.zero; + PlaneTangents(n, uvMatrix, out var tangent, out var bitangent); + PlaneTangents(n, turnedUVMatrix, out var turnedTangent, out var turnedBitangent); for (int i = 0; i < vertices.Length; i++) { var vertex = vertices[i]; var normal = math.normalizesafe((double3)vertex.normal, n); - vertex.tangent = Tangent(normal, tangent, bitangent); + vertex.tangent = math.dot(vertex.normal, frontNormal) >= 0 ? Tangent(normal, tangent, bitangent) + : Tangent(normal, turnedTangent, turnedBitangent); vertices[i] = vertex; } } + static void PlaneTangents(double3 n, float4x4 uvMatrix, out double3 tangent, out double3 bitangent) + { + // u = dot(a, position) + ..., v = dot(b, position) + ...: rows 0 and 1 of the mapping + var a = new double3(uvMatrix.c0.x, uvMatrix.c1.x, uvMatrix.c2.x); + var b = new double3(uvMatrix.c0.y, uvMatrix.c1.y, uvMatrix.c2.y); + // In the plane: a.T = 1, b.T = 0 and a.B = 0, b.B = 1, solved by T = (b x n) / det, B = (n x a) / det + var determinant = math.dot(n, math.cross(a, b)); + var mapped = determinant != 0 && math.isfinite(determinant); + tangent = mapped ? math.cross(b, n) / determinant : double3.zero; + bitangent = mapped ? math.cross(n, a) / determinant : double3.zero; + } + static float4 Tangent(double3 normal, double3 tangent, double3 bitangent) { var perpendicular = tangent - normal * math.dot(normal, tangent); diff --git a/Core/2.Processing/Jobs/GenerateSurfaceTrianglesJob.cs b/Core/2.Processing/Jobs/GenerateSurfaceTrianglesJob.cs index f2c81c2a..0de8a909 100644 --- a/Core/2.Processing/Jobs/GenerateSurfaceTrianglesJob.cs +++ b/Core/2.Processing/Jobs/GenerateSurfaceTrianglesJob.cs @@ -56,6 +56,20 @@ public readonly int Compare(ChiselQuerySurface x, ChiselQuerySurface y) } readonly static CompareSortByBasePlaneIndex kCompareSortByBasePlaneIndex = new(); + // faceNormal, or turned round when every registered vertex faces the other way (UniqueVertexMapper.RegisterVertices + // turns a reverse aligned part's normal) + static float3 DrawnNormal(NativeList vertices, float3 faceNormal) + { + if (vertices.Length == 0) + return faceNormal; + for (int v = 0; v < vertices.Length; v++) + { + if (math.dot(vertices[v].normal, faceNormal) >= 0) + return faceNormal; + } + return -faceNormal; + } + // After a surface's triangles have been registered: normal smoothing, UVs, tangents, lightmap coordinates, the decals on // it and its render buffer. unsafe void FinishSurface(int surf, int brushNodeOrder, ulong entityID, ref BlobArray baseSurfaces, float4x4 treeToPlane, float4x4 nodeToTree, float3 finalFaceNormal, @@ -65,6 +79,9 @@ unsafe void FinishSurface(int surf, int brushNodeOrder, ulong entityID, ref Blob NativeArray decalCandidateStart, SlotLayout slots) { var baseSurfaceCount = slots.baseSurfaceCount; + // the side the surface is drawn on: turned round from finalFaceNormal when all its parts are (a subtractive + // brush's walls; a pillar in the subtractive workflow). Hotspot tiles are laid out as seen from there + var drawnNormal = DrawnNormal(uniqueVertexMapper.surfaceRenderVertices, finalFaceNormal); // a painted surface gets its paint's grid points as vertices, before anything is worked out from them if (paint.TryGetRange(entityID, baseSurfaces[surf].descriptionIndex, out var subdivision)) PaintSubdivision.Subdivide(surfaceIndexList, ref uniqueVertexMapper, finalFaceNormal, paint, subdivision); @@ -84,6 +101,7 @@ unsafe void FinishSurface(int surf, int brushNodeOrder, ulong entityID, ref Blob var sectionInput = default(HotspotSectionInput); var hotspotInfo = default(HotspotSurfaceInfo); var hotspotSource = default(HotspotSurfaceSource); + var hotspotMapped = false; if (hotspot > 0 && hotspot <= hotspotLayouts.Length && hotspotLayouts[hotspot - 1].tileCount > 0) { var layout = hotspotLayouts[hotspot - 1]; @@ -98,7 +116,7 @@ unsafe void FinishSurface(int surf, int brushNodeOrder, ulong entityID, ref Blob var ownUnits = 1.0f; if (cap) { - if (math.dot(capNormal, finalFaceNormal) < 0) + if (math.dot(capNormal, drawnNormal) < 0) capNormal = -capNormal; var localNormal = math.mul(math.transpose(new float3x3(nodeToTree)), capNormal); // locked to the object, in the brush's own space and units; otherwise the tree's @@ -116,16 +134,16 @@ unsafe void FinishSurface(int surf, int brushNodeOrder, ulong entityID, ref Blob { lead = surf; if (baseSurfaces[surf].textureInWorld) - HotspotMatcher.Frame(finalFaceNormal, baseSurfaces[surf].hotspotRotation, baseSurfaces[surf].hotspotMirror, out hotspotRight, out hotspotUp); + HotspotMatcher.Frame(drawnNormal, baseSurfaces[surf].hotspotRotation, baseSurfaces[surf].hotspotMirror, out hotspotRight, out hotspotUp); else { - // the brush's own normal, facing as the drawn face does (inwards in the subtractive workflow) + // the brush's own normal, facing as the drawn face does var ownNormal = math.normalizesafe(baseSurfaces[surf].localPlane.xyz); var toTree = math.transpose(math.inverse(nodeToTree)); - if (math.dot(math.mul(toTree, new float4(ownNormal, 0)).xyz, finalFaceNormal) < 0) + if (math.dot(math.mul(toTree, new float4(ownNormal, 0)).xyz, drawnNormal) < 0) ownNormal = -ownNormal; - HotspotMatcher.Frame(finalFaceNormal, baseSurfaces[surf].localPlane.xyz, nodeToTree, baseSurfaces[surf].hotspotRotation, baseSurfaces[surf].hotspotMirror, out hotspotRight, out hotspotUp); - ownUnits = HotspotMatcher.OwnUnits(finalFaceNormal, ownNormal, math.inverse(nodeToTree), baseSurfaces[surf].hotspotRotation, baseSurfaces[surf].hotspotMirror); + HotspotMatcher.Frame(drawnNormal, baseSurfaces[surf].localPlane.xyz, nodeToTree, baseSurfaces[surf].hotspotRotation, baseSurfaces[surf].hotspotMirror, out hotspotRight, out hotspotUp); + ownUnits = HotspotMatcher.OwnUnits(drawnNormal, ownNormal, math.inverse(nodeToTree), baseSurfaces[surf].hotspotRotation, baseSurfaces[surf].hotspotMirror); } shape = HotspotMatcher.ShapeOf(uniqueVertexMapper.surfaceColliderVertices.AsArray(), hotspotRight, hotspotUp); HotspotMatcher.MaskOf(ref shape, uniqueVertexMapper.surfaceColliderVertices.AsArray(), surfaceIndexList.AsArray(), hotspotRight, hotspotUp); @@ -137,7 +155,7 @@ unsafe void FinishSurface(int surf, int brushNodeOrder, ulong entityID, ref Blob pinnedSheet: baseSurfaces[lead].hotspotPinnedSheet); // coplanar neighbours with this layout and frame, of any brush, are matched again together (HotspotGroups) if (!cap) - hotspotSource = new HotspotSurfaceSource { layout = hotspot, right = hotspotRight, up = hotspotUp, normal = finalFaceNormal, seed = seed, + hotspotSource = new HotspotSurfaceSource { layout = hotspot, right = hotspotRight, up = hotspotUp, normal = drawnNormal, seed = seed, pinned = baseSurfaces[surf].hotspotPinned, pinnedSheet = baseSurfaces[surf].hotspotPinnedSheet, density = density, offset = baseSurfaces[surf].hotspotOffset, world = baseSurfaces[surf].textureInWorld }; @@ -149,6 +167,7 @@ unsafe void FinishSurface(int surf, int brushNodeOrder, ulong entityID, ref Blob layout = sheet; uvMat = HotspotMatcher.Mapping(hotspotTiles[choice.tile], layout, shape, choice, hotspotRight, hotspotUp); cornerUVs = false; + hotspotMapped = true; // a tile that repeats, has a border, or whose repeats are moved along (a cap is mapped whole): what is drawn is cut // where its sections meet, after the model's weld (OutputHotspotSections) if (!cap && (hotspotTiles[choice.tile].border > 0 || choice.Repeated || math.any(baseSurfaces[surf].hotspotOffset != 0) || @@ -169,10 +188,19 @@ unsafe void FinishSurface(int surf, int brushNodeOrder, ulong entityID, ref Blob } } + // the parts drawn turned round (a subtractive brush's walls; all of them in the subtractive workflow) are seen from + // behind the brush's plane: their u runs the other way, so the texture reads as from the front. A hotspot tile is + // laid out from the drawn side already + var frontNormal = subtractiveWorkflow ? -finalFaceNormal : finalFaceNormal; + var turnUVs = !hotspotMapped; + var turnedUVMat = turnUVs ? MeshAlgorithms.TurnedUVMatrix(uvMat) : uvMat; + MeshAlgorithms.ComputeUVs(uniqueVertexMapper.surfaceRenderVertices, uvMat); if (cornerUVs) surfaceCorners.ApplyUVs(uniqueVertexMapper.surfaceRenderVertices); - MeshAlgorithms.ComputeTangents(uniqueVertexMapper.surfaceRenderVertices, finalFaceNormal, uvMat); + if (turnUVs) + MeshAlgorithms.TurnUVs(uniqueVertexMapper.surfaceRenderVertices, frontNormal); + MeshAlgorithms.ComputeTangents(uniqueVertexMapper.surfaceRenderVertices, finalFaceNormal, uvMat, turnedUVMat, frontNormal); MeshAlgorithms.ComputeLightmapCoordinates(uniqueVertexMapper.surfaceRenderVertices, finalFaceNormal); // Decals on this surface, each in its own slot @@ -195,11 +223,13 @@ unsafe void FinishSurface(int surf, int brushNodeOrder, ulong entityID, ref Blob onSurface = new NativeArray(candidateCount, Allocator.Temp); onSurfaceIndices = new UnsafeList(candidateCount, Allocator.Temp); var pointOnPlane = (double3)uniqueVertexMapper.surfaceRenderVertices[0].position; - var uDirection = new double3(uvMat.c0.x, uvMat.c1.x, uvMat.c2.x); + // the u of the texture as it is seen, on the side the surface is drawn on + var seenUVMat = math.dot(drawnNormal, frontNormal) < 0 ? turnedUVMat : uvMat; + var uDirection = new double3(seenUVMat.c0.x, seenUVMat.c1.x, seenUVMat.c2.x); for (int k = 0; k < candidateCount; k++) { var volume = decalVolumes[candidates[k]]; - onSurface[k] = volume.IsOmni ? volume.OnSurface(finalFaceNormal, pointOnPlane, uDirection) : volume; + onSurface[k] = volume.IsOmni ? volume.OnSurface(drawnNormal, pointOnPlane, uDirection) : volume; onSurfaceIndices.Add(k); } volumes = onSurface; @@ -220,7 +250,9 @@ unsafe void FinishSurface(int surf, int brushNodeOrder, ulong entityID, ref Blob MeshAlgorithms.ComputeUVs(remaining.renderVertices, uvMat); if (cornerUVs) surfaceCorners.ApplyUVs(remaining.renderVertices); - MeshAlgorithms.ComputeTangents(remaining.renderVertices, finalFaceNormal, uvMat); + if (turnUVs) + MeshAlgorithms.TurnUVs(remaining.renderVertices, frontNormal); + MeshAlgorithms.ComputeTangents(remaining.renderVertices, finalFaceNormal, uvMat, turnedUVMat, frontNormal); MeshAlgorithms.ComputeLightmapCoordinates(remaining.renderVertices, finalFaceNormal); } for (int k = 0; k < candidateCount; k++) @@ -239,6 +271,8 @@ unsafe void FinishSurface(int surf, int brushNodeOrder, ulong entityID, ref Blob MeshAlgorithms.ComputeUVs(decalOutput.renderVertices, uvMat); if (cornerUVs) surfaceCorners.ApplyUVs(decalOutput.renderVertices); + if (turnUVs) + MeshAlgorithms.TurnUVs(decalOutput.renderVertices, frontNormal); } MeshAlgorithms.ComputeTangents(decalOutput.indices, decalOutput.renderVertices); MeshAlgorithms.ComputeLightmapCoordinates(decalOutput.renderVertices, finalFaceNormal); @@ -936,7 +970,7 @@ public unsafe void Execute(int index) brushMax = math.max(brushMax, vertices[v]); } } - FindDecalCandidates(ref baseSurfaces, nodeToTreeInvTrans, vertices.Length > 0, brushMin, brushMax, entityID, decalCandidates, decalTargeted, decalCandidateStart); + FindDecalCandidates(ref baseSurfaces, nodeToTreeInvTrans, vertices.Length > 0, brushMin, brushMax, entityID, parts, decalCandidates, decalTargeted, decalCandidateStart); if (decalCandidates.Length > 0) decalBuilder = DecalSurfaceBuilder.Create(Allocator.Temp); @@ -1023,8 +1057,25 @@ static void BoundsOf(NativeArray vertices, out float3 min, out float3 ma } } + // Whether every part of a surface the CSG kept is reverse aligned: drawn turned round from its face normal + // (UniqueVertexMapper.RegisterVertices), as DrawnNormal finds from its vertices + static bool PartsReversed(NativeList parts, int surf) + { + var any = false; + for (int p = 0; p < parts.Length; p++) + { + var part = parts[p]; + if (part.x != surf || part.w < 3 || part.y == (int)kDiscardedPart) + continue; + if (part.y != (int)CategoryIndex.ReverseAligned && part.y != (int)CategoryIndex.ValidReverseAligned) + return false; + any = true; + } + return any; + } + unsafe void FindDecalCandidates(ref BlobArray baseSurfaces, float4x4 nodeToTreeInvTrans, bool hasVertices, float3 brushMin, float3 brushMax, - ulong brushEntityID, NativeList candidates, NativeList targeted, NativeArray start) + ulong brushEntityID, NativeList parts, NativeList candidates, NativeList targeted, NativeArray start) { candidates.Clear(); targeted.Clear(); @@ -1063,7 +1114,8 @@ unsafe void FindDecalCandidates(ref BlobArray baseSurfaces, float4x ref var volume = ref volumes[d]; if (volume.IsOmni) { - if (!volume.Reaches(subtractiveWorkflow ? -plane : plane)) + // the plane facing the side the surface is drawn on + if (!volume.Reaches(subtractiveWorkflow != PartsReversed(parts, s) ? -plane : plane)) continue; } else { diff --git a/Core/ExtensionMethods/Geometry/MathExtensions.cs b/Core/ExtensionMethods/Geometry/MathExtensions.cs index 741994d4..af0a93b0 100644 --- a/Core/ExtensionMethods/Geometry/MathExtensions.cs +++ b/Core/ExtensionMethods/Geometry/MathExtensions.cs @@ -386,23 +386,25 @@ public static double3 ProjectPointPlane(double3 point, double4 plane) } + // Whether p, in the triangle's plane, is in the triangle or on its edges: on the edge two triangles share it is in both, + // never in neither [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool PointInTriangle(float3 p, float3 a, float3 b, float3 c) { var cp1A = math.cross(c - b, p - b); var cp2A = math.cross(c - b, a - b); var dotA = math.dot(cp1A, cp2A); - var sameSideA = dotA > 0; + var sameSideA = dotA >= 0; var cp1B = math.cross(c - a, p - a); var cp2B = math.cross(c - a, b - a); var dotB = math.dot(cp1B, cp2B); - var sameSideB = dotB > 0; + var sameSideB = dotB >= 0; var cp1C = math.cross(b - a, p - a); var cp2C = math.cross(b - a, c - a); var dotC = math.dot(cp1C, cp2C); - var sameSideC = dotC > 0; + var sameSideC = dotC >= 0; return sameSideA && sameSideB && diff --git a/Core/Tests/MathExtensionsTests.cs b/Core/Tests/MathExtensionsTests.cs index 335d69d9..3cf8125e 100644 --- a/Core/Tests/MathExtensionsTests.cs +++ b/Core/Tests/MathExtensionsTests.cs @@ -142,6 +142,22 @@ public void PointInTriangle_InteriorTrue_ExteriorFalse() Assert.That(MathExtensions.PointInTriangle(new float3(1f, 1f, 0), a, b, c), Is.False); } + // A point on an edge or a corner is in the triangle: on the edge two triangles share, it is in both, not in neither + [Test] + public void PointInTriangle_OnAnEdgeOrCorner_IsIn() + { + var a = new float3(0, 0, 0); + var b = new float3(1, 0, 0); + var c = new float3(0, 1, 0); + var d = new float3(1, 1, 0); + var onTheSharedEdge = new float3(0.5f, 0.5f, 0); + Assert.That(MathExtensions.PointInTriangle(onTheSharedEdge, a, b, c), Is.True); + Assert.That(MathExtensions.PointInTriangle(onTheSharedEdge, b, d, c), Is.True); + Assert.That(MathExtensions.PointInTriangle(new float3(0.5f, 0, 0), a, b, c), Is.True, "on an outer edge"); + Assert.That(MathExtensions.PointInTriangle(b, a, b, c), Is.True, "a corner"); + Assert.That(MathExtensions.PointInTriangle(new float3(2, 0, 0), a, b, c), Is.False, "on an edge's line, past the triangle"); + } + [Test] public void GetTriangleArraySize_MatchesTriangularNumbers() { diff --git a/Editor/SceneView/ChiselDefaultPlacementTools.cs b/Editor/SceneView/ChiselDefaultPlacementTools.cs index 84bba4c4..7e819506 100644 --- a/Editor/SceneView/ChiselDefaultPlacementTools.cs +++ b/Editor/SceneView/ChiselDefaultPlacementTools.cs @@ -142,10 +142,7 @@ public override void OnSceneGUI(SceneView sceneView, Rect dragArea) generatedComponent.gameObject.SetActive(!flat); if (flat) break; - generatedComponent.Operation = forceOperation ?? - ((height < 0 && modelBeneathCursor) ? - CSGOperationType.Subtractive : - CSGOperationType.Additive); + generatedComponent.Operation = forceOperation ?? DrawnOperation(height, modelBeneathCursor); PlacementToolDefinition.OnUpdate(ref generatedComponent.definition, height); generatedComponent.OnValidate(); ChiselActiveMaterial.GiveTo(generatedComponent); @@ -274,10 +271,7 @@ public override void OnSceneGUI(SceneView sceneView, Rect dragArea) if ((generatoreModeFlags & PlacementFlags.AlwaysFaceUp) == PlacementFlags.AlwaysFaceCameraXZ) generatedComponent.Operation = forceOperation ?? CSGOperationType.Additive; else - generatedComponent.Operation = forceOperation ?? - ((height < 0 && modelBeneathCursor) ? - CSGOperationType.Subtractive : - CSGOperationType.Additive); + generatedComponent.Operation = forceOperation ?? DrawnOperation(height, modelBeneathCursor); PlacementToolDefinition.OnUpdate(ref generatedComponent.definition, bounds); generatedComponent.OnValidate(); ChiselActiveMaterial.GiveTo(generatedComponent); diff --git a/Editor/SceneView/ChiselPlacementToolInstance.cs b/Editor/SceneView/ChiselPlacementToolInstance.cs index 6bf2b600..555c9d01 100644 --- a/Editor/SceneView/ChiselPlacementToolInstance.cs +++ b/Editor/SceneView/ChiselPlacementToolInstance.cs @@ -140,6 +140,13 @@ internal static string ShortName(string name) } + // The operation of a drawn shape when none is chosen: out of or into the surface of the model beneath it + // (ChiselModelComponent.OperationOutOfSurface); drawn on the grid, away from any model, it adds + internal static CSGOperationType DrawnOperation(float height, ChiselModelComponent modelBeneathCursor) + { + return modelBeneathCursor ? modelBeneathCursor.OperationOutOfSurface(height) : CSGOperationType.Additive; + } + public bool IsGenerating { get; private set; } public bool InToolBox diff --git a/Editor/Tests/ChiselPickingPlaneTests.cs b/Editor/Tests/ChiselPickingPlaneTests.cs index ddf0e114..7230c954 100644 --- a/Editor/Tests/ChiselPickingPlaneTests.cs +++ b/Editor/Tests/ChiselPickingPlaneTests.cs @@ -72,6 +72,23 @@ public void ASurfaceSeenFromOutside_KeepsItsPlane() Assert.That(intersection.worldPlane.normal.z, Is.EqualTo(1).Within(1e-4f)); } + // In a model with the subtractive workflow the box is a room: its surface, picked from inside, faces the viewer + [Test] + public void ASurfaceOfASubtractiveWorkflowRoom_FacesTheViewer() + { + Assert.That(BoxFacingPlusZ(out var box, out var brush, out var surfaceIndex, out var faceZ), Is.True); + var model = box.GetComponentInParent(); + model.renderSettings.subtractiveWorkflow = true; + model.SyncModelSettingsStore(); + UpdateModels(); + var intersection = ChiselSelectionManager.PickedIntersection(box.gameObject, brush, surfaceIndex, + worldCameraOrigin: Vector3.zero, + worldIntersectionPos: new Vector3(0, 0, faceZ)); + Assert.That(intersection.worldPlane.normal.z, Is.EqualTo(-1).Within(1e-4f)); + Assert.That(intersection.worldPlaneIntersection.z, Is.EqualTo(faceZ).Within(1e-4f)); + Assert.That(intersection.treeNode, Is.EqualTo(box), "the room's brush"); + } + [Test] public void ASurfaceSeenFromInside_FacesTheViewer() { diff --git a/Editor/Tests/ChiselPlacementToolsTests.cs b/Editor/Tests/ChiselPlacementToolsTests.cs index 5fe5461d..784bab33 100644 --- a/Editor/Tests/ChiselPlacementToolsTests.cs +++ b/Editor/Tests/ChiselPlacementToolsTests.cs @@ -65,6 +65,48 @@ public void ShortName_IsInitialsOrFirstLetters() Assert.That(ChiselPlacementToolInstance.ShortName("Box"), Is.EqualTo("Bo")); } + static ChiselModelComponent Model(bool subtractiveWorkflow) + { + var model = new GameObject("placement test").AddComponent(); + model.renderSettings.subtractiveWorkflow = subtractiveWorkflow; + return model; + } + + // pulled out of a surface a shape adds to the model, pushed into it it cuts + [Test] + public void DrawnOnASurface_PulledOutAdds_PushedInCuts() + { + var model = Model(subtractiveWorkflow: false); + try + { + Assert.That(ChiselPlacementToolInstance.DrawnOperation( 1, model), Is.EqualTo(CSGOperationType.Additive)); + Assert.That(ChiselPlacementToolInstance.DrawnOperation(-1, model), Is.EqualTo(CSGOperationType.Subtractive)); + } + finally { Object.DestroyImmediate(model.gameObject); } + } + + // with the subtractive workflow the brushes are the empty space: pulled out of a room's surface a shape cuts (a + // pillar), pushed into it it adds (a pit) + [Test] + public void DrawnOnASubtractiveWorkflowSurface_PulledOutCuts_PushedInAdds() + { + var model = Model(subtractiveWorkflow: true); + try + { + Assert.That(ChiselPlacementToolInstance.DrawnOperation( 1, model), Is.EqualTo(CSGOperationType.Subtractive)); + Assert.That(ChiselPlacementToolInstance.DrawnOperation(-1, model), Is.EqualTo(CSGOperationType.Additive)); + } + finally { Object.DestroyImmediate(model.gameObject); } + } + + // drawn on the grid, away from any model, a shape adds whichever way it is drawn + [Test] + public void DrawnOnTheGrid_Adds() + { + Assert.That(ChiselPlacementToolInstance.DrawnOperation( 1, null), Is.EqualTo(CSGOperationType.Additive)); + Assert.That(ChiselPlacementToolInstance.DrawnOperation(-1, null), Is.EqualTo(CSGOperationType.Additive)); + } + static T Tool() where T : ScriptableObject { return ScriptableObject.CreateInstance(); } [Test]